Index: /issm/branches/trunk-jpl-damage/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-damage/Makefile.am	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/Makefile.am	(revision 12878)
@@ -1,3 +1,3 @@
-EXTRA_DIST = reconf  scripts test m4 examples cron etc doc packages contributors.txt 
+EXTRA_DIST = reconf scripts test m4 examples cron etc doc packages contributors.txt 
 SUBDIRS = src bin
 bin_SCRIPTS=config.h startup.m README.rtf
Index: /issm/branches/trunk-jpl-damage/README
===================================================================
--- /issm/branches/trunk-jpl-damage/README	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/README	(revision 12878)
@@ -22,5 +22,5 @@
 ------------------------------------------------------------------------------
 
-Website: ttp://issm.jpl.nasa.gov/ for additional information.
+Website: http://issm.jpl.nasa.gov/ for additional information.
 
 ------------------------------------------------------------------------------
Index: /issm/branches/trunk-jpl-damage/configs/config-arm-linux.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-arm-linux.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/configs/config-arm-linux.sh	(revision 12878)
@@ -3,11 +3,9 @@
 ./configure \
 	--prefix=$ISSM_DIR \
-    --host="arm-linux" \
+    --build="i386-apple-darwin10.8.0" \
+    --host="arm-linux-androideabi" \
+    --enable-shared \
+    --without-fortran \
 	--without-modules \
-    CC=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-gcc \
-    GCC=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-gcc \
-    CXX=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-g++ \
-	--with-vendor=arm-linux \
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
-	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install\
-    --without-fortran-lib
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install 
Index: /issm/branches/trunk-jpl-damage/configs/config-discover.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-discover.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/configs/config-discover.sh	(revision 12878)
@@ -0,0 +1,27 @@
+#!/bin/csh
+
+#PETSc 3.2
+#MPI /usr/local/intel/mpi/4.0.3.008/lib64/
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-matlab-dir=$MATLAB_DIR \
+ --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/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-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-petsc-arch=$ISSM_ARCH \
+ --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+ --with-scalapack-dir="/usr/local/intel/mkl/10.1.2.024/lib/64/" \
+ --with-blacs-dir="/usr/local/intel/mkl/10.1.2.024/lib/64/" \
+ --with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
+ --with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
+ --with-blas-lapack-dir="/usr/local/intel/mkl/10.1.2.024/lib/64/" \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-O3 -xS" \
+ --with-vendor=intel-discover
+
Index: /issm/branches/trunk-jpl-damage/configs/config-greenplanet.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-greenplanet.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/configs/config-greenplanet.sh	(revision 12878)
@@ -1,3 +1,3 @@
-#!/bin/csh
+#!/bin/sh
 
 #PETSc 3.2
@@ -10,4 +10,5 @@
  --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="/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" \
Index: /issm/branches/trunk-jpl-damage/configs/config-linux64-ad.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-linux64-ad.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/configs/config-linux64-ad.sh	(revision 12878)
@@ -0,0 +1,20 @@
+#!/bin/sh
+
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-modules\
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install\
+	--without-thermal \
+	--without-control \
+	--without-hydrology \
+	--without-diagnostic \
+	--without-balanced \
+	--without-responses \
+	--without-slope \
+	--without-rifts \
+	--without-steadystate \
+	--without-transient \
+	--without-3d \
+	--without-groundingline \
+	--without-kriging  \
+	--with-adolc-dir=$ADOLC_DIR 
Index: /issm/branches/trunk-jpl-damage/configs/config-linux64-astrid-petsc3.3.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-linux64-astrid-petsc3.3.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/configs/config-linux64-astrid-petsc3.3.sh	(revision 12878)
@@ -0,0 +1,33 @@
+#!/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: /issm/branches/trunk-jpl-damage/configs/config-linux64-astrid-petscdev.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-linux64-astrid-petscdev.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/configs/config-linux64-astrid-petscdev.sh	(revision 12878)
@@ -0,0 +1,37 @@
+#!/bin/sh
+
+#External packages versions:
+#petsc Dev: FH trying out
+#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-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-spai-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-hypre-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-prometheus-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-superlu-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-spooles-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-pastix-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: /issm/branches/trunk-jpl-damage/configs/config-linux64-astrid-python.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-linux64-astrid-python.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/configs/config-linux64-astrid-python.sh	(revision 12878)
@@ -0,0 +1,25 @@
+#!/bin/sh
+
+#External packages versions:
+#petsc 3.1 or 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-python-version=2.7\
+ --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-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/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 -lutil" \
+ --with-numthreads=32 \
+ --enable-debugging
Index: /issm/branches/trunk-jpl-damage/configs/config-macosx-snowleopard-bothapis.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-macosx-snowleopard-bothapis.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/configs/config-macosx-snowleopard-bothapis.sh	(revision 12878)
@@ -0,0 +1,35 @@
+#!/bin/sh
+
+#petsc 3.2
+#mpich 1.4
+
+#export FCFLAGS=" -m32"
+#export FFLAGS=" -m32"
+#export CFLAGS=" -arch i386"
+#export CXXFLAGS=" -arch i386"
+
+pythonversion=2.7
+
+./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-version=$pythonversion \
+	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Python.framework/Versions/$pythonversion/lib/python$pythonversion/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: /issm/branches/trunk-jpl-damage/configs/config-macosx-snowleopard-python.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-macosx-snowleopard-python.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/configs/config-macosx-snowleopard-python.sh	(revision 12878)
@@ -0,0 +1,29 @@
+#!/bin/sh
+
+#petsc 3.2
+#mpich 1.4
+
+pythonversion=2.7
+
+./configure \
+	--prefix=$ISSM_DIR \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
+	--with-python-version=$pythonversion \
+	--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-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: /issm/branches/trunk-jpl-damage/configs/config-macosx64-ad.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-macosx64-ad.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/configs/config-macosx64-ad.sh	(revision 12878)
@@ -0,0 +1,18 @@
+#!/bin/sh
+
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-modules\
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install\
+	--without-thermal \
+	--without-control \
+	--without-hydrology \
+	--without-diagnostic \
+	--without-balanced \
+	--without-responses \
+	--without-slope \
+	--without-rifts \
+	--without-steadystate \
+	--without-transient \
+	--without-3d \
+	--without-groundingline
Index: /issm/branches/trunk-jpl-damage/configs/config-macosx64-chris.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-macosx64-chris.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/configs/config-macosx64-chris.sh	(revision 12878)
@@ -0,0 +1,28 @@
+#!/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: /issm/branches/trunk-jpl-damage/configs/config-macosx64-gsl.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-macosx64-gsl.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/configs/config-macosx64-gsl.sh	(revision 12878)
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-modules\
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install
+	#--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install 
+    #--without-fortran-lib
Index: /issm/branches/trunk-jpl-damage/configs/config-macosx64-larour-ad.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-macosx64-larour-ad.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/configs/config-macosx64-larour-ad.sh	(revision 12878)
@@ -1,23 +1,7 @@
 #!/bin/sh
 
-#petsc 3.2
-#mpich 1.4
-
 ./configure \
-	--with-serial=no\
 	--prefix=$ISSM_DIR \
-	--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 " \
-	--without-blas-lapack-dir \
-	--with-chaco-dir=$ISSM_DIR/externalpackages/chaco/install \
-	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
-	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/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-adic2-dir=$ISSM_DIR/externalpackages/adic/install/ \
-	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install/ \
-	--with-numthreads=8 \
+	--without-modules\
 	--without-thermal \
 	--without-control \
@@ -31,13 +15,6 @@
 	--without-transient \
 	--without-3d \
-	--without-groundingline
- 
-#--without-prognostic \
-#--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/ \
+	--without-groundingline \
+	--without-kriging  \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install
+	#--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install\
Index: /issm/branches/trunk-jpl-damage/configs/config-macosx64-larour-python.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-macosx64-larour-python.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/configs/config-macosx64-larour-python.sh	(revision 12878)
@@ -4,9 +4,12 @@
 #mpich 1.4
 
+pythonversion=2.7
+
 ./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/Python.framework/Versions/3.2/lib/python3.2/site-packages/numpy/core/include/numpy\
+	--with-python-version=$pythonversion \
+	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/lib/python$pythonversion/site-packages/numpy/core/include/numpy\
 	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
 	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
Index: /issm/branches/trunk-jpl-damage/configs/config-macosx64-larour.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-macosx64-larour.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/configs/config-macosx64-larour.sh	(revision 12878)
@@ -24,4 +24,4 @@
 	--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-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install 
Index: /issm/branches/trunk-jpl-damage/configs/config-pleiades-petscdev.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/configs/config-pleiades-petscdev.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/configs/config-pleiades-petscdev.sh	(revision 12878)
@@ -0,0 +1,28 @@
+#!/bin/csh
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-modules=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.04/include \
+ --with-mpi-lib="-L/nasa/sgi/mpt/2.04/lib/ -lmpi -lpthread -lgfortran" \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+ --with-mkl-dir=/nasa/intel/mkl/10.0.011/lib/64/ \
+ --with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
+ --with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/src/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-spai-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-hypre-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-prometheus-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-superlu-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-spooles-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-pastix-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-O3 -xS" \
+ --with-vendor=intel-pleiades
Index: /issm/branches/trunk-jpl-damage/configure.ac
===================================================================
--- /issm/branches/trunk-jpl-damage/configure.ac	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/configure.ac	(revision 12878)
@@ -2,5 +2,5 @@
 
 #AUTOCONF
-AC_INIT([ISSM],[4.1],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_INIT([ISSM],[4.2.1],[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
@@ -10,7 +10,6 @@
 AC_PROG_CPP
 AC_PROG_CXX([cccl cl icl g++])
-#AC_PROG_F77([ifort g77 gfortran])
+AC_PROG_F77([ifort g77 gfortran])
 #Libraries and linking
-AC_PROG_RANLIB
 AC_F77_LIBRARY_LDFLAGS
 AC_PATH_XTRA      #figure out X library and include paths
@@ -23,6 +22,11 @@
 AM_PROG_CC_C_O
 
-##LIBTOOL?
-#AC_PROG_LIBTOOL
+AM_PROG_AR
+AC_PROG_RANLIB
+
+# To produce shared libraries uncomment LT_INIT. In theory, Libtool can be initialized
+# even if all linking is static, since, if not shared libraries are to be produce, libtool
+# will act simply as a wrapper around AR and Ranlib.
+#
 #LT_INIT
 
@@ -31,5 +35,4 @@
 
 #AM_PROG_AR must be placed after ISSM_OPTIONS
-AM_PROG_AR
 
 #List all Makefiles
Index: /issm/branches/trunk-jpl-damage/etc/environment.csh
===================================================================
--- /issm/branches/trunk-jpl-damage/etc/environment.csh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/etc/environment.csh	(revision 12878)
@@ -127,2 +127,14 @@
 setenv VALGRIND_DIR {$VALGRIND_DIR}
 setenv PATH {$PATH}:{$VALGRIND_DIR}
+
+#MERCURIAL
+#setenv PYTHONPATH {$PYTHONPATH}:{$MERCURIAL_DIR}/mercurial/pure/
+setenv PYTHONPATH {$MERCURIAL_DIR}/mercurial/pure/
+setenv PATH {$PATH}:{$MERCURIAL_DIR}
+
+#GSL
+setenv GSL_DIR {$GSL_DIR}
+setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$GSL_DIR}/lib
+
+#CMAKE
+setenv PATH {$PATH}:{$CMAKE_DIR}/bin
Index: /issm/branches/trunk-jpl-damage/etc/environment.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/etc/environment.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/etc/environment.sh	(revision 12878)
@@ -39,5 +39,5 @@
 #PETSC
 export PETSC_DIR
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$PETSC_DIR/lib/$ISSM_ARCH"
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$PETSC_DIR/lib/$ISSM_ARCH:$PETSC_DIR/lib"
 export LD_RUN_PATH="$LD_RUN_PATH:$PETSC_DIR/lib/$ISSM_ARCH"
 
@@ -262,5 +262,5 @@
 export PATH="$PYTHON_DIR/bin:$PATH"
 export PYTHONPATH="$PYTHONPATH:$ISSM_DIR/src/modules/python"
-export LD_LIBRARY_PATH=$ISSM_DIR/src/modules/python:$LD_LIBRARY_PATH
+export LD_LIBRARY_PATH=$ISSM_DIR/src/modules/python:$ISSM_DIR/externalpackages/python/install/lib:$LD_LIBRARY_PATH
 export PYTHONSTARTUP
 
@@ -270,2 +270,26 @@
 #GIT
 export PATH="$PATH:$GIT_DIR/install/bin"
+
+#NCVIEW
+export PATH="$PATH:$NCVIEW_DIR/install"
+
+#TCLX
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$TCLX_DIR"
+export LD_RUN_PATH="$LD_RUN_PATH:$TCLX_DIR"
+
+
+#ASPELL
+export PATH="$ASPELL_DIR/install/bin:$PATH"
+
+
+#ESMF
+export ESMF_DIR=$ISSM_DIR/externalpackages/esmf/esmf
+export ESMF_COMPILER=gfortran
+export ESMF_COMM=mpich2
+
+#HDF5
+export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$HDF5_DIR/lib"
+export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$HDF5_DIR/lib"
+export LIBRARY_PATH="$LIBRARY_PATH:$HDF5_DIR/lib"
+export C_INCLUDE_PATH="$C_INCLUDE_PATH:$HDF5_DIR/include"
+
Index: /issm/branches/trunk-jpl-damage/etc/environment_variables.csh
===================================================================
--- /issm/branches/trunk-jpl-damage/etc/environment_variables.csh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/etc/environment_variables.csh	(revision 12878)
@@ -81,4 +81,13 @@
 set SSH_DIR={$ISSM_DIR}/externalpackages/ssh
 
+#mercurial
+set MERCURIAL_DIR={$ISSM_DIR}/externalpackages/mercurial/install
+
 #valgrind
 set VALGRIND_DIR={$ISSM_DIR}/externalpackages/valgrind/install/bin
+
+#gsl
+set GSL_DIR={$ISSM_DIR}/externalpackages/gsl/install
+
+#cmake
+set CMAKE_DIR={$ISSM_DIR}/externalpackages/cmake/install
Index: /issm/branches/trunk-jpl-damage/etc/environment_variables.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/etc/environment_variables.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/etc/environment_variables.sh	(revision 12878)
@@ -182,7 +182,4 @@
 ANDROID_SDK_DIR="$ANDROID_DIR/android-sdk/install-sdk"
 
-#android-ant
-ANDROID_ANT_DIR="$ANDROID_DIR/android-sdk/install-ant"
-
 #gsl
 GSL_DIR="$ISSM_DIR/externalpackages/gsl/install"
@@ -192,4 +189,5 @@
 
 #PYTHON
+PYTHON_VER=2.7
 PYTHON_DIR="$ISSM_DIR/externalpackages/python/install"
 PYTHONSTARTUP="$ISSM_DIR/startup.py"
@@ -201,2 +199,14 @@
 #GIT
 GIT_DIR="$ISSM_DIR/externalpackages/git"
+
+#NCVIEW
+NCVIEW_DIR="$ISSM_DIR/externalpackages/ncview"
+
+#TCLX
+TCLX_DIR="$ISSM_DIR/externalpackages/tclx/install/lib/tclx8.4"
+
+#ASPELL
+ASPELL_DIR="$ISSM_DIR/externalpackages/aspell/"
+
+#HDF5
+export HDF5_DIR=$ISSM_DIR/externalpackages/hdf5/install
Index: /issm/branches/trunk-jpl-damage/externalpackages/adolc/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/adolc/install-macosx64.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/adolc/install-macosx64.sh	(revision 12878)
@@ -0,0 +1,61 @@
+#!/bin/bash
+
+#some issues on macosx64 with ISSM's autoconf. you might want to run native to mac on this.
+
+#Some cleanup
+rm -rf install ADOL-C-2.2.0 src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ADOL-C-2.2.0.tar.gz' 'ADOL-C-2.2.0.tar.gz'
+
+#Create install directories
+mkdir install src
+
+#Untar 
+tar -zxvf  ADOL-C-2.2.0.tar.gz
+
+#Move ADOL-C into install directory
+mv ADOL-C-2.2.0/* src
+rm -rf ADOL-C-2.2.0
+
+#Compile ADOL-C
+cd src 
+
+#export CC=gcc
+#export CXX=g++
+#export CFLAGS="-arch x86_64"
+#export CXXFLAGS="-arch x86_64"
+
+./configure \
+	--prefix=$ISSM_DIR/externalpackages/adolc/install \
+	--enable-sparse \
+	--enable-docexa \
+	--enable-addexa \
+	--disable-shave
+
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+
+#Ok, bug with libtool: replace all LIBTOOL= by LIBTOOL=libtool 
+#in all Makefiles
+for i in `find ./ -name Makefile `
+do
+	echo $i
+	cat $i | sed 's/LIBTOOL =/LIBTOOL = libtool/g' > $i.bak 
+	mv $i.bak $i
+done
+
+#remake: 
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+
Index: /issm/branches/trunk-jpl-damage/externalpackages/adolc/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/adolc/install.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/adolc/install.sh	(revision 12878)
@@ -22,4 +22,9 @@
 cd src 
 
+export CC=gcc
+export CXX=g++
+export CFLAGS="-arch x86_64"
+export CXXFLAGS="-arch x86_64"
+
 ./configure \
 	--prefix=$ISSM_DIR/externalpackages/adolc/install \
Index: /issm/branches/trunk-jpl-damage/externalpackages/aspell/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/aspell/install.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/aspell/install.sh	(revision 12878)
@@ -0,0 +1,61 @@
+#!/bin/bash
+
+#0: cleanup
+#1:  install aspell
+#2:  install en dictionary
+step=2
+
+
+#Some cleanup
+if  [[ $step  == "0" ]]; then
+	rm -rf src install dicts
+	rm -rf aspell-0.50.5
+	rm -rf aspell5-en-6.0.0
+fi
+
+#install aspell
+if  [[ $step  == "1" ]]; then
+
+	mkdir src install dicts
+
+	#Download from ISSM server
+	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/aspell-0.50.5.tar.gz' 'aspell-0.50.5.tar.gz'
+
+	#Untar 
+	tar -zxvf  aspell-0.50.5.tar.gz
+
+	#Move aspell into src directory
+	mv aspell-0.50.5/* src
+	rm -rf aspell-0.50.5
+
+	#Configure aspell
+	cd src
+	./configure \
+		--prefix="$ISSM_DIR/externalpackages/aspell/install" \
+
+	#Compile and install aspell
+	if [ -z $1 ]; then
+		make
+	else
+		make -j $1
+	fi
+	make install
+fi
+
+#languages
+if  [[ $step  == "2" ]]; then
+
+	#Download from ISSM server
+	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/aspell5-en-6.0.0.tar.gz' 'aspell5-en-6.0.0.tar.gz'
+
+	#Untar 
+	tar -zxvf  aspell5-en-6.0.0.tar.gz
+
+	#Move aspell into src directory
+	mv aspell5-en-6.0.0 dicts
+
+	#install
+	cd dicts/aspell5-en-6.0.0
+	./configure
+	make install
+fi
Index: /issm/branches/trunk-jpl-damage/externalpackages/dakota/install-discover.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/dakota/install-discover.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/dakota/install-discover.sh	(revision 12878)
@@ -0,0 +1,99 @@
+#!/bin/bash
+
+#Get number of cpus
+NUMCPUS=$1;
+
+#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 ./ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H ./ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C ./NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C ./NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C ./NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C ./NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp ./LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \
+--prefix="$ISSM_DIR/externalpackages/dakota/install/" \
+--without-graphics  \
+--with-pic \
+--disable-mpi \
+--with-blas="-L/usr/local/intel/mkl/10.1.2.024/lib/64 -lmkl_lapack -lmkl -lguide -lpthread" \
+--with-lapack="-L/usr/local/intel/mkl/10.1.2.024/lib/64 -lmkl_lapack -lmkl -lguide -lpthread"
+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 [ -z $NUMCPUS ];
+then
+	make
+	make install
+else
+	make -j $NUMCPUS
+	make -j $NUMCPUS 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: /issm/branches/trunk-jpl-damage/externalpackages/esmf/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/esmf/install.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/esmf/install.sh	(revision 12878)
@@ -0,0 +1,50 @@
+#!/bin/bash
+
+#0: cleanup
+#1: install
+#2: test
+
+install=2
+
+export ESMF_DIR=$ISSM_DIR/externalpackages/esmf/esmf
+export ESMF_COMPILER=gfortran
+export ESMF_COMM=mpich2
+
+if [[ $install == "0" ]]; then
+	#Some cleanup
+	rm -rf esmf_5_2_0rp2
+	rm -rf esmf
+fi
+
+if [[ $install == "1" ]]; then
+
+	#Download from ISSM server
+	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/esmf_5_2_0rp2_src.tar.gz' 'esmf_5_2_0rp2_src.tar.gz'
+
+	#Untar 
+	tar -zxvf  esmf_5_2_0rp2_src.tar.gz
+
+
+	#Configure esmf
+	cd esmf
+
+
+
+	#Compile and install esmf
+	if [ -z $1 ]; then
+		make
+		make install
+	else
+		make -j $1
+		make -j $1 install
+	fi
+fi
+
+if [[ $install == "2" ]]; then
+	cd esmf
+	if [ -z $1 ]; then
+		make all_tests
+	else
+		make -j $1 all_tests
+	fi
+fi
Index: /issm/branches/trunk-jpl-damage/externalpackages/export_fig/export_fig.m
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/export_fig/export_fig.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/export_fig/export_fig.m	(revision 12878)
@@ -16,4 +16,5 @@
 %   export_fig ... -<colorspace>
 %   export_fig ... -append
+%   export_fig ... -bookmark
 %   export_fig(..., handle)
 %
@@ -120,4 +121,6 @@
 %             exists, the figure is to be appended as a new page, instead
 %             of being overwritten (default).
+%   -bookmark - option to indicate that a bookmark with the name of the
+%               figure is to be created in the output file (pdf only).
 %   handle - The handle of the figure or axes (can be an array of handles
 %            of several axes, but these must be in the same figure) to be
@@ -159,4 +162,8 @@
 % 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for
 %           reporting it).
+% 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling
+%           bookmarking of figures in pdf files.
+% 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep
+%           tick marks fixed.
 
 function [im alpha] = export_fig(varargin)
@@ -194,11 +201,14 @@
 Hlims = findall(fig, 'Type', 'axes');
 if ~cls
-    % Record the old axes limit modes
+    % Record the old axes limit and tick modes
     Xlims = make_cell(get(Hlims, 'XLimMode'));
     Ylims = make_cell(get(Hlims, 'YLimMode'));
     Zlims = make_cell(get(Hlims, 'ZLimMode'));
-end
-% Set all axes limit modes to manual, so the limits can't change
-set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual');
+    Xtick = make_cell(get(Hlims, 'XTickMode'));
+    Ytick = make_cell(get(Hlims, 'YTickMode'));
+    Ztick = make_cell(get(Hlims, 'ZTickMode'));
+end
+% Set all axes limit and tick modes to manual, so the limits and ticks can't change
+set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual', 'XTickMode', 'manual', 'YTickMode', 'manual', 'ZTickMode', 'manual');
 % Set to print exactly what is there
 set(fig, 'InvertHardcopy', 'off');
@@ -403,4 +413,12 @@
             eps_remove_background(tmp_nam);
         end
+        % Add a bookmark to the PDF if desired
+        if options.bookmark
+            fig_nam = get(fig, 'Name');
+            if isempty(fig_nam)
+                warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.');
+            end
+            add_bookmark(tmp_nam, fig_nam);
+        end
         % Generate a pdf
         eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);
@@ -435,7 +453,7 @@
     % Reset the hardcopy mode
     set(fig, 'InvertHardcopy', old_mode);
-    % Reset the axes limit modes
+    % Reset the axes limit and tick modes
     for a = 1:numel(Hlims)
-        set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a});
+        set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a}, 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a});
     end
 end
@@ -462,4 +480,5 @@
                  'aa_factor', 3, ...
                  'magnify', 1, ...
+                 'bookmark', false, ...
                  'quality', []);
 native = false; % Set resolution to native of an image
@@ -504,4 +523,6 @@
                 case 'append'
                     options.append = true;
+                case 'bookmark'
+                    options.bookmark = true;
                 case 'native'
                     native = true;
@@ -743,6 +764,40 @@
 % Helper function
 function A = make_cell(A)
- if ~iscell(A)
-     A = {A};
- end
- 
+if ~iscell(A)
+    A = {A};
+end
+return
+
+function add_bookmark(fname, bookmark_text)
+% Adds a bookmark to the temporary EPS file after %%EndPageSetup
+% Read in the file
+fh = fopen(fname, 'r');
+if fh == -1
+    error('File %s not found.', fname);
+end
+try
+    fstrm = fread(fh, '*char')';
+catch ex
+    fclose(fh);
+    rethrow(ex);
+end
+fclose(fh);
+
+% Include standard pdfmark prolog to maximize compatibility
+fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse'));
+% Add page bookmark
+fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text));
+
+% Write out the updated file
+fh = fopen(fname, 'w');
+if fh == -1
+    error('Unable to open %s for writing.', fname);
+end
+try
+    fwrite(fh, fstrm, 'char*1');
+catch ex
+    fclose(fh);
+    rethrow(ex);
+end
+fclose(fh);
+return
Index: /issm/branches/trunk-jpl-damage/externalpackages/export_fig/print2array.m
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/export_fig/print2array.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/export_fig/print2array.m	(revision 12878)
@@ -41,4 +41,7 @@
 % 27/1/2012 Bug fix affecting painters rendering tall figures. Thanks to
 % Ken Campbell for reporting it.
+
+% 3/4/2012 Bug fix to median input. Thanks to Andy Matthews for reporting
+% it.
 
 function [A bcol] = print2array(fig, res, renderer)
@@ -119,5 +122,5 @@
             end
         end
-        bcol = median([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))], 1);
+        bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
         for c = 1:size(A, 3)
             A(:,[1:l-1, r+1:end],c) = bcol(c);
Index: /issm/branches/trunk-jpl-damage/externalpackages/export_fig/print2eps.m
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/export_fig/print2eps.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/export_fig/print2eps.m	(revision 12878)
@@ -45,4 +45,6 @@
 % alias can lead to another font being swapped in.
 
+% 10/4/2012 Make the font swapping case insensitive.
+
 function print2eps(name, fig, varargin)
 options = {'-depsc2'};
@@ -57,33 +59,42 @@
 end
 % Find all the used fonts in the figure
-fonts = get(findall(fig, '-property', 'FontName'), 'FontName');
+font_handles = findall(fig, '-property', 'FontName');
+fonts = get(font_handles, 'FontName');
 if ~iscell(fonts)
     fonts = {fonts};
 end
-fonts = unique(fonts);
 % Map supported font aliases onto the correct name
+fontsl = lower(fonts);
 for a = 1:numel(fonts)
-    f = lower(fonts{a});
+    f = fontsl{a};
     f(f==' ') = [];
     switch f
         case {'times', 'timesnewroman', 'times-roman'}
-            fonts{a} = 'Times-Roman';
+            fontsl{a} = 'times-roman';
         case {'arial', 'helvetica'}
-            fonts{a} = 'Helvetica';
+            fontsl{a} = 'helvetica';
         case {'newcenturyschoolbook', 'newcenturyschlbk'}
-            fonts{a} = 'NewCenturySchlbk';
+            fontsl{a} = 'newcenturyschlbk';
         otherwise
     end
 end
+fontslu = unique(fontsl);
 % Determine the font swap table
 matlab_fonts = {'Helvetica', 'Times-Roman', 'Palatino', 'Bookman', 'Helvetica-Narrow', 'Symbol', ...
                 'AvantGarde', 'NewCenturySchlbk', 'Courier', 'ZapfChancery', 'ZapfDingbats'};
-require_swap = find(~ismember(fonts, matlab_fonts));
-unused_fonts = find(~ismember(matlab_fonts, fonts));
-font_swap = min(numel(require_swap), numel(unused_fonts));
-font_swap = [reshape(matlab_fonts(unused_fonts(1:font_swap)), 1, font_swap); reshape(fonts(require_swap(1:font_swap)), 1, font_swap)];
+matlab_fontsl = lower(matlab_fonts);
+require_swap = find(~ismember(fontslu, matlab_fontsl));
+unused_fonts = find(~ismember(matlab_fontsl, fontslu));
+font_swap = cell(3, 0);
+for a = 1:min(numel(require_swap), numel(unused_fonts))
+    ind = find(strcmp(fontslu{require_swap(a)}, fontsl));
+    n = numel(ind);
+    font_swap(1,end+1:end+n) = reshape(mat2cell(font_handles(ind), ones(n, 1)), 1, []);
+    font_swap(2,end-n+1:end) = matlab_fonts(unused_fonts(a));
+    font_swap(3,end-n+1:end) = reshape(fonts(ind), 1, []);
+end
 % Swap the fonts
 for a = 1:size(font_swap, 2)
-    set(findall(fig, 'FontName', font_swap{2,a}), 'FontName', font_swap{1,a});
+    set(font_swap{1,a}, 'FontName', font_swap{2,a});
 end
 % Set paper size
@@ -114,7 +125,8 @@
     % Reset the font names in the figure
     for a = 1:size(font_swap, 2)
-        set(findall(fig, 'FontName', font_swap{1,a}), 'FontName', font_swap{2,a});
+        set(font_swap{1,a}, 'FontName', font_swap{3,a});
     end
     % Replace the font names in the eps file
+    font_swap = font_swap(2:3,:);
     try
         swap_fonts(name, font_swap{:});
Index: /issm/branches/trunk-jpl-damage/externalpackages/gdal/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/gdal/install.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/gdal/install.sh	(revision 12878)
@@ -22,4 +22,5 @@
 	--prefix="$ISSM_DIR/externalpackages/gdal/install" \
 	--without-python \
+	--without-png \
 	--with-netcdf=no \
 	--with-jasper=no \
Index: sm/branches/trunk-jpl-damage/externalpackages/gsl/install-android-4.0.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/gsl/install-android-4.0.sh	(revision 12877)
+++ 	(revision )
@@ -1,38 +1,0 @@
-#!/bin/bash
-
-#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
-
-./configure \
-    CC=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-gcc\
-    LD=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-ld\
-    AR=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-ar\
-    RANLIB=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-ranlib\
-    NM=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-nm\
-    OBJ_EXT=o\
-    LIB_EXT=a\
-    --host="arm-linux"\
-	--prefix="$ISSM_DIR/externalpackages/gsl/install" 
-
-#Compile gsl
-if [ -z $1 ]; then
-	make
-else
-	make -j $1
-fi
-
-make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/gsl/install-android.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/gsl/install-android.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/gsl/install-android.sh	(revision 12878)
@@ -0,0 +1,43 @@
+#!/bin/bash
+
+source $ANDROID_DIR/android_aux.sh
+
+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.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
+fi
+
+#Configure gsl
+if [[ $step == "2" || $step == "0" ]]; then
+    cd src
+    
+    autoreconf -iv --force -I $LIBTOOL_DIR/share/aclocal/ 
+
+    ./configure \
+        --build="i386-apple-darwin10.8.0" \
+        --host=$host_triplet\
+	    --prefix="$ISSM_DIR/externalpackages/gsl/install/" 
+fi
+
+#Compile gsl
+if [[ $step == "3" || $step == "0" ]]; then
+    if [ -z $1 ]; then
+	    make $j 
+    else
+	    make -j $j 
+    fi
+
+    make install
+fi
Index: /issm/branches/trunk-jpl-damage/externalpackages/gslib/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/gslib/install.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/gslib/install.sh	(revision 12878)
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gslib90_ls.tar.gz' 'gslib90_ls.tar.gz'
+
+#Untar 
+tar -zxvf  gslib90_ls.tar.gz
+
+#Move gslib into install directory
+mv gslib90/* install
+rm -rf gslib90
+
+#Change compiler to gfortran
+cd install
+cat Makefile | sed -e "s/FC=g95/FC=gfortran/g" > Makefile.bak
+mv Makefile.bak Makefile
+cat gslib/Makefile | sed -e "s/FC=g95/FC=gfortran/g" > Makefile.bak
+mv Makefile.bak gslib/Makefile
+make 
Index: /issm/branches/trunk-jpl-damage/externalpackages/h5py/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/h5py/install.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/h5py/install.sh	(revision 12878)
@@ -0,0 +1,24 @@
+#!/bin/bash
+
+#needed further along
+export HDF5_DIR=$ISSM_DIR/externalpackages/hdf5/install
+
+#Some cleanup
+rm -rf install h5py-2.0.1
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/h5py-2.0.1.tar.gz' 'h5py-2.0.1.tar.gz'
+
+#Untar 
+tar -zxvf  h5py-2.0.1.tar.gz
+
+#Move h5py to install directory
+rm -rf install/*
+mv h5py-2.0.1/* install/
+rm -rf h5py-2.0.1
+
+#Configure and compile
+cd install
+python setup.py build –hdf5=$ISSM_DIR/externalpackages/hdf5/install
+python setup.py install
Index: /issm/branches/trunk-jpl-damage/externalpackages/hdf5/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/hdf5/install.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/hdf5/install.sh	(revision 12878)
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install hdf5-1.8.9
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/hdf5-1.8.9.tar.gz' 'hdf5-1.8.9.tar.gz'
+
+#Untar 
+tar -zxvf  hdf5-1.8.9.tar.gz
+
+#Move hdf5 to src directory
+rm -rf src/*
+mv hdf5-1.8.9/* src/
+rm -rf hdf5-1.8.9
+
+#Configure and compile
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/hdf5/install" 
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/ipython/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/ipython/install.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/ipython/install.sh	(revision 12878)
@@ -3,7 +3,6 @@
 #Some cleanup
 rm -rf src
-rm -rf install
 rm -rf ipython-0.12
-mkdir src install
+mkdir src 
 
 #Download from ISSM server
Index: /issm/branches/trunk-jpl-damage/externalpackages/lapack/configs/linux64/make.inc
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/lapack/configs/linux64/make.inc	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/lapack/configs/linux64/make.inc	(revision 12878)
@@ -16,5 +16,5 @@
 OPTS     = -fPIC -O2
 DRVOPTS  = $(OPTS)
-NOOPT    = -O0
+NOOPT    = -fPIC -O0
 LOADER   = gfortran
 LOADOPTS =
Index: /issm/branches/trunk-jpl-damage/externalpackages/libtool/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/libtool/install.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/libtool/install.sh	(revision 12878)
@@ -2,15 +2,17 @@
 
 #Some cleanup
-rm -rf install libtool-2.2.6b src
+rm -rf install libtool[\w.- ]* src
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libtool-2.2.6b.tar.gz' 'libtool-2.2.6b.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libtool' 'libtool'
 
 #Untar 
-tar -zxvf  libtool-2.2.6b.tar.gz
+tar -zxvf  libtool[\w.-]*.tar.gz
+rm libtool[\w.-]*.tar.gz
+
 
 #Move libtool into src directory
-mv libtool-2.2.6b src
+mv libtool[\w.-]* src
 
 #Compile libtool
Index: /issm/branches/trunk-jpl-damage/externalpackages/matlab/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/matlab/install.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/matlab/install.sh	(revision 12878)
@@ -6,4 +6,5 @@
 #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
@@ -15,3 +16,4 @@
 #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
Index: /issm/branches/trunk-jpl-damage/externalpackages/metis/configs/4.0/discover/Makefile.in.patch
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/metis/configs/4.0/discover/Makefile.in.patch	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/metis/configs/4.0/discover/Makefile.in.patch	(revision 12878)
@@ -0,0 +1,10 @@
+3c3,5
+< CC = cc
+---
+> CC = icc
+> OBJ_EXT=o
+> LIB_EXT=a
+6c8
+< OPTFLAGS = -O2 
+---
+> OPTFLAGS = -DLINUX -fPIC
Index: /issm/branches/trunk-jpl-damage/externalpackages/metis/install-4.0-discover.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/metis/install-4.0-discover.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/metis/install-4.0-discover.sh	(revision 12878)
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install metis-4.0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/metis-4.0.tar.gz' 'metis-4.0.tar.gz'
+
+#Untar 
+tar -zxvf  metis-4.0.tar.gz
+
+#Move metis into install directory
+mv metis-4.0/* install
+rm -rf metis-4.0
+
+#Apply patches
+cd install 
+patch -p1 < ../metis-4.0.patch
+patch Makefile.in ../configs/4.0/discover/Makefile.in.patch
+
+#Compile
+make
Index: /issm/branches/trunk-jpl-damage/externalpackages/modules/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/modules/install-macosx64.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/modules/install-macosx64.sh	(revision 12878)
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install
+rm -rf modules-3.2.9
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/modules-3.2.9.tar.gz' 'modules-3.2.9.tar.gz'
+
+#Untar 
+tar -zxvf  modules-3.2.9.tar.gz
+
+#Move modules into src directory
+
+#Configure modules
+cd modules-3.2.9
+./configure \
+	--prefix=$ISSM_DIR/externalpackages/modules/install\
+	--with-module-path=$ISSM_DIR/externalpackages/modules/install/modules/files\
+	--with-version-path=$ISSM_DIR/externalpackages/modules/install/modules/versions\
+	--with-tcl-lib=$ISSM_DIR/externalpackages/tcl/install/Library/Frameworks/Tcl.framework/Versions/8.5\
+	--with-tcl-inc=$ISSM_DIR/externalpackages/tcl/install/Library/Frameworks/Tcl.framework/Versions/8.5/Headers\
+	--with-tcl-ver=8.5\
+	--with-tclx-lib=$ISSM_DIR/externalpackages/tclx/install/lib/tclx8.4\
+    --with-tclx-inc=$ISSM_DIR/externalpackages/tclx/install/include\
+	--with-tclx-ver=8.4\
+	--with-etc-path=$ISSM_DIR/externalpackages/modules/install/modules/etc\
+	--with-skel-path=$ISSM_DIR/externalpackages/modules/install/modules/etc/skel\
+	--disable-dependency-tracking
+
+#Compile and install modules
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/modules/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/modules/install.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/modules/install.sh	(revision 12878)
@@ -0,0 +1,21 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/modules-3.2.9c.tar.gz modules-3.2.9c.tar.gz
+
+#Untar and move python into install directory
+tar -zxvf  modules-3.2.9c.tar.gz
+mv modules-3.2.9 install
+
+#Configure doxygen
+cd install
+./configure \
+  --prefix "$ISSM_DIR/externalpackages/modules/install" \
+  --without-x
+
+#compile and install
+make
+make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/ncview/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/ncview/install.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/ncview/install.sh	(revision 12878)
@@ -18,5 +18,5 @@
 cd install
 ./configure \
-	--prefix "$ISSM_DIR/externalpackages/ncview/install" \
+	--prefix="$ISSM_DIR/externalpackages/ncview/install" \
 	--x-libraries=/usr/X11/lib/ \
 	--x-includes=/usr/X11/include/ \
Index: /issm/branches/trunk-jpl-damage/externalpackages/netcdf-python/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/netcdf-python/install.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/netcdf-python/install.sh	(revision 12878)
@@ -0,0 +1,29 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install netCDF4-1.0
+mkdir install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py "http://issm.jpl.nasa.gov/files/externalpackages/netCDF4-1.0.tar.gz" "netCDF4-1.0.tar.gz"
+
+#Untar 
+tar -zxvf  netCDF4-1.0.tar.gz
+
+#for later: 
+rm -rf ISSMDIR
+echo $ISSM_DIR | sed 's/\//\\\//g' > ISSMDIR
+ISSMDIR=`cat ISSMDIR` && rm -rf ISSMDIR
+
+#Move netCDF4 to install directory
+rm -rf install/*
+mv netCDF4-1.0/* install/
+rm -rf netCDF4-1.0
+
+#Configur and compile
+cd install
+#edit setup.cfg to point to hdf5 and netcdf
+cat setup.cfg.template  | sed "s/\#netCDF4_dir = \/usr\/local/netCDF4_dir = $ISSMDIR\/externalpackages\/netcdf\/install/g"  | sed "s/\#HDF5_dir = \/usr\/local/HDF5_DIR = $ISSMDIR\/externalpackages\/hdf5\/install/g" > setup.cfg
+
+python setup.py build 
+python setup.py install
Index: /issm/branches/trunk-jpl-damage/externalpackages/netcdf/install-4.0.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/netcdf/install-4.0.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/netcdf/install-4.0.sh	(revision 12878)
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src install netcdf-4.0.1
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py "http://issm.jpl.nasa.gov/files/externalpackages/netcdf-4.0.1.tar.gz" "netcdf-4.0.1.tar.gz"
+
+#Untar 
+tar -zxvf  netcdf-4.0.1.tar.gz
+
+#Move netcdf to install directory
+rm -rf src/*
+mv netcdf-4.0.1/* src/
+rm -rf netcdf-4.0.1
+
+#Configure and compile
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/netcdf/install"  
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/netcdf/install-4.2.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/netcdf/install-4.2.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/netcdf/install-4.2.sh	(revision 12878)
@@ -0,0 +1,28 @@
+#!/bin/bash
+
+#you need hdf5 compiled, as well as doxygen for the documentation
+
+#Some cleanup
+rm -rf src install netcdf-4.2
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py "http://issm.jpl.nasa.gov/files/externalpackages/netcdf-4.2.tar.gz" "netcdf-4.2.tar.gz"
+
+#Untar 
+tar -zxvf  netcdf-4.2.tar.gz
+
+#Move netcdf to install directory
+rm -rf src/*
+mv netcdf-4.2/* src/
+rm -rf netcdf-4.2
+
+#Configure and compile
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/netcdf/install"  
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: sm/branches/trunk-jpl-damage/externalpackages/netcdf/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/netcdf/install.sh	(revision 12877)
+++ 	(revision )
@@ -1,26 +1,0 @@
-#!/bin/bash
-
-#Some cleanup
-rm -rf install netcdf-4.0.1
-mkdir install
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/netcdf-4.0.1.tar.gz' 'netcdf-4.0.1.tar.gz'
-
-#Untar 
-tar -zxvf  netcdf-4.0.1.tar.gz
-
-#Move netcdf to install directory
-rm -rf install/*
-mv netcdf-4.0.1/* install/
-rm -rf netcdf-4.0.1
-
-#Configure and compile
-cd install
-./configure  --prefix="$ISSM_DIR/externalpackages/netcdf/install" 
-if [ -z $1 ]; then
-	make
-else
-	make -j $1
-fi
-make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/nose/install-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/nose/install-linux64.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/nose/install-linux64.sh	(revision 12878)
@@ -0,0 +1,29 @@
+#!/bin/bash
+#Install Python nose module
+
+pythonversion=2
+	
+rm -rf src 
+
+if [[ $pythonversion == "3" ]];then
+
+	svn checkout http://python-nose.googlecode.com/svn/branches/py3k
+	mv py3k src
+
+	cd src
+	python ./setup.py build
+	python ./setup.py install
+fi
+
+if [[ $pythonversion == "2" ]];then
+
+	#Download from ISSM server
+	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/nose-1.1.2.tar.gz' 'nose-1.1.2.tar.gz'
+	tar -zxvf  nose-1.1.2.tar.gz
+	mv nose-1.1.2 src
+	rm -rf nose-1.1.2
+
+	cd src
+	python ./setup.py build
+	python ./setup.py install
+fi
Index: /issm/branches/trunk-jpl-damage/externalpackages/octave/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/octave/install.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/octave/install.sh	(revision 12878)
@@ -2,29 +2,29 @@
 
 #Some cleanup
-version=3.6.1
-rm -rf src install octave-$version octave-$version.tar.gz
+rm -rf src install octave-3.6.2 
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py "http://issm.jpl.nasa.gov/files/externalpackages/octave-$version.tar.gz" "octave-$version.tar.gz"
+$ISSM_DIR/scripts/DownloadExternalPackage.py "http://issm.jpl.nasa.gov/files/externalpackages/octave-3.6.2.tar.gz" "octave-3.6.2.tar.gz"
 
 #Untar 
-tar -zxvf  octave-$version.tar.gz
+tar -zxvf  octave-3.6.2.tar.gz
 
 #Move octave into install directory
-mv octave-$version/* src
-rm -rf octave-$version
+mv octave-3.6.2/* src
+rm -rf octave-3.6.2
 
 #install
 cd src 
+./configure \
+ --prefix=$ISSM_DIR/externalpackages/octave/install \
+ --disable-readline
 
-exit
-make 
-
-#Compile 
-cd ../install
-mkdir lib
-cd lib
-cp ../../src/*.a .
-ln -s octave_LINUX.a octave.a
-ln -s octave_LINUX.a liboctave.a
+if [ -z $NUMCPUS ];
+then
+	make
+	make install
+else
+	make -j $NUMCPUS
+	make -j $NUMCPUS install
+fi
Index: /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.2-discover.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.2-discover.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.2-discover.sh	(revision 12878)
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+#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" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--PETSC_ARCH="$ISSM_ARCH" \
+	--with-batch=1 \
+	--with-debugging=0 \
+	--with-shared-libraries=0 \
+	--known-mpi-shared-libraries=1 \
+	--with-mpi-dir=/usr/local/intel/mpi/4.0.3.008/lib64/ \
+	--with-blas-lapack-dir=/usr/local/intel/mkl/10.1.2.024/lib/64/ \
+	--with-scalapack-lib=/usr/local/intel/mkl/10.1.2.024/lib/64/libmkl_scalapack_lp64.a \
+	--with-scalapack-include=/usr/local/intel/mkl/10.1.2.024/include/ \
+	--with-blacs-lib=/usr/local/intel/mkl/10.1.2.024/lib/64/libmkl_blacs_intelmpi_lp64.a \
+	--with-blacs-include=/usr/local/intel/mkl/10.1.2.024/include/ \
+	--download-mumps=yes \
+	--download-scalapack=no \
+	--download-blacs=no \
+	--download-plapack=yes \
+	--download-parmetis=yes \
+	--with-pic=1
+
+echo "== Follow PETSc's instructions"
Index: /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.2-linux64-python.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.2-linux64-python.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.2-linux64-python.sh	(revision 12878)
@@ -0,0 +1,36 @@
+#!/bin/bash
+
+#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=$ISSM_DIR/externalpackages/mpich2/install \
+	--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/branches/trunk-jpl-damage/externalpackages/petsc/install-3.2-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.2-linux64.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.2-linux64.sh	(revision 12878)
@@ -22,5 +22,5 @@
 	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
 	--with-debugging=0 \
-	--with-shared-libraries=0 \
+	--with-shared-libraries=1 \
 	--download-mumps=yes \
 	--download-scalapack=yes \
Index: /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.3-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.3-linux64.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.3-linux64.sh	(revision 12878)
@@ -0,0 +1,36 @@
+#!/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
+
+#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-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 \
+	--download-metis=yes \
+	--with-pic=1
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.3-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.3-macosx64.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-3.3-macosx64.sh	(revision 12878)
@@ -0,0 +1,35 @@
+#!/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
+
+#configure
+cd src
+./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/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 \
+	--download-metis=yes 
+
+#Compile petsc and install it
+make
+make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-dev-pleiades.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-dev-pleiades.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/petsc/install-dev-pleiades.sh	(revision 12878)
@@ -0,0 +1,123 @@
+#!/bin/bash
+#Step 0: download
+#Step 1: install before plapack crasehs
+#Step 2: After Plapack implodes
+STEP=0
+
+if [ $STEP -eq 0 ]; then
+	# Adapted from petsc 3.2. 
+	# Used Mercurial to get code
+	rm -rf src
+	hg clone http://petsc.cs.iit.edu/petsc/petsc-dev src
+	cd src
+	hg clone http://petsc.cs.iit.edu/petsc/BuildSystem config/BuildSystem
+fi
+
+# To update (via Mercurial):
+#      cd petsc-dev
+#      hg pull -u
+#      cd config/BuildSystem
+#      hg pull -u
+
+
+# configure script
+# Note: using metis from externalpackages did not work...
+# for now downloading new metis
+#   -then rename metis in externalpackages to metis2
+if [ $STEP -eq 1 ]; then
+
+	mkdir install
+
+	#configure
+	cd src
+	./config/configure.py \
+		--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+		--with-batch=1  \
+		--PETSC_ARCH="$ISSM_ARCH" \
+		--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+		--with-debugging=0 \
+		--with-shared-libraries=0 \
+		--with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
+		--known-mpi-shared-libraries=1 \
+		--with-mpi-lib=/nasa/sgi/mpt/2.04/lib/libmpi.so \
+		--with-mpi-include=/nasa/sgi/mpt/2.04/include  \
+		--download-mumps=yes \
+		--download-plapack=yes \
+		--download-scalapack=yes \
+		--download-blacs=yes  \
+		--download-blas=yes \
+		--download-f-blas-lapack=yes \
+		--download-parmetis=yes \
+		--download-metis=yes \
+		--download-trilinos=yes \
+		--download-euclid=yes \
+		--download-pastix=yes \
+		--download-ptscotch=yes \
+		--download-spooles=yes \
+		--download-spai=yes \
+		--download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
+		--FFLAGS=-I/usr/include \
+		--with-cc=icc \
+		--with-fc=ifort \
+		--COPTFLAGS=" -O3 -xS" \
+		--FOPTFLAGS=" -O3 -xS" \
+		--CXXOPTFLAGS=" -O3 -xS" \
+		--with-pic=1
+	echo "== Fix Plapack compilation manually (http://issm.jpl.nasa.gov/documentation/faq/petsc32/) =="
+	echo "== Then run STEP=2 =="
+fi
+if [ $STEP -eq 2 ]; then
+	cd src
+	./config/configure.py \
+	 --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	 --with-batch=1  \
+	 --PETSC_ARCH="$ISSM_ARCH" \
+	 --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	 --with-debugging=0 \
+	 --with-shared-libraries=0 \
+	 --with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
+	 --with-mpi-lib=/nasa/sgi/mpt/2.04/lib/libmpi.so \
+	 --with-mpi-include=/nasa/sgi/mpt/2.04/include  \
+	 --known-mpi-shared-libraries=1 \
+	 --download-mumps=yes \
+	 --download-scalapack=yes \
+	 --download-blacs=yes  \
+	 --download-blas=yes \
+	 --with-f-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/src/$ISSM_ARCH \
+	 --download-parmetis=yes \
+	 --download-metis=yes \
+	 --with-cxx=icpc \
+	 --download-hypre=yes \
+	 --download-trilinos=yes \
+	 --download-prometheus=yes \
+	 --download-euclid=yes \
+	 --download-pastix=yes \
+	 --download-ptscotch=yes \
+	 --download-spooles=yes \
+	 --download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
+	 --with-spai-dir=$ISSM_DIR/externalpackages/petsc/src/$ISSM_ARCH \
+	 --with-plapack-dir=$ISSM_DIR/externalpackages/petsc/src/$ISSM_ARCH \
+	 --FFLAGS=-I/usr/include \
+	 --with-cc=icc \
+	 --with-fc=ifort \
+	 --COPTFLAGS=" -O3 -xS" \
+	 --FOPTFLAGS=" -O3 -xS" \
+	 --CXXOPTFLAGS=" -O3 -xS" \
+	 --with-pic=1
+	 cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -q debug 
+#PBS -l select=1:ncpus=1:model=har 
+#PBS -l walltime=200 
+#PBS -W group_list=s1010 
+#PBS -m e 
+. /usr/share/modules/init/bash 
+module load comp-intel/11.1.046 
+module load mpi-sgi/mpt.2.04  #DEFINES MPI_Type_create_indexed_block
+module load math/intel_mkl_64_10.0.011 
+export PATH="$PATH:." 
+export MPI_GROUP_MAX=64 
+mpiexec -np 1 ./conftest-linux-gnu-ia64-intel.py
+EOF
+	echo "== Follow PETSc's instructions"
+fi
Index: /issm/branches/trunk-jpl-damage/externalpackages/python/install-2.7.2-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/python/install-2.7.2-linux64.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/python/install-2.7.2-linux64.sh	(revision 12878)
@@ -0,0 +1,35 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-2.7.2
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-2.7.2.tgz Python-2.7.2.tgz
+
+#exports
+export CC
+
+#Untar and move python into install directory
+tar -zxvf  Python-2.7.2.tgz
+mv Python-2.7.2/* src
+rm -rf Python-2.7.2
+
+#Configure python
+cd src 
+./configure \
+ --prefix="$ISSM_DIR/externalpackages/python/install" \
+ --enable-shared
+
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+cd ../install/include
+cp python2.7/* ./
+cd ../lib
+ln -s  libpython2.7.so.1.0 libpython.so
Index: /issm/branches/trunk-jpl-damage/externalpackages/python/install-2.7.2-macosx-lion.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/python/install-2.7.2-macosx-lion.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/python/install-2.7.2-macosx-lion.sh	(revision 12878)
@@ -0,0 +1,42 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-2.7.2
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-2.7.2.tgz Python-2.7.2.tgz
+
+#exports
+export CC
+
+#Untar and move python into install directory
+tar -zxvf  Python-2.7.2.tgz
+mv Python-2.7.2/* src
+rm -rf Python-2.7.2
+
+#Configure and compile
+cd src 
+./configure \
+ --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+cd ../install
+
+#get rid of bin, because it's just a copy of
+#Library/Frameworks/Python.framework/Versions/2.7/bin, and will not reflect
+#new changes being made
+rm -rf bin
+ln -s Library/Frameworks/Python.framework/Headers include
+ln -s Library/Frameworks/Python.framework/Versions/2.7/lib lib
+ln -s Library/Frameworks/Python.framework/Versions/2.7/bin bin
+
+#Patch pyport.h:
+cd include
+patch pyport.h $ISSM_DIR/externalpackages/python/patches/pyport.h.patch
Index: /issm/branches/trunk-jpl-damage/externalpackages/python/install-2.7.2-macosx-snowleopard.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/python/install-2.7.2-macosx-snowleopard.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/python/install-2.7.2-macosx-snowleopard.sh	(revision 12878)
@@ -0,0 +1,40 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-2.7.2
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-2.7.2.tgz Python-2.7.2.tgz
+
+#exports
+export CC
+export MACOSX_DEPLOYMENT_TARGET=10.6
+
+#Untar and move python into install directory
+tar -zxvf  Python-2.7.2.tgz
+mv Python-2.7.2/* src
+rm -rf Python-2.7.2
+
+#Configure doxygen
+cd src 
+# --enable-framework needs to have the form "$SOME_PATH/Library/Frameworks" to avoid installing components in /Applications directory
+# --prefix is recognized as $SOME_PATH as long as this form is taken, so it's not necessary to include
+./configure --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
+
+#make
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+cd ../install
+ln -s Library/Frameworks/Python.framework/Headers include
+ln -s Library/Frameworks/Python.framework/Versions/2.7/lib lib
+
+#Patch pyport.h:
+cd include
+patch pyport.h ../patch/pyport.h.patch
Index: /issm/branches/trunk-jpl-damage/externalpackages/python/install-3.2.2-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/python/install-3.2.2-linux64.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/python/install-3.2.2-linux64.sh	(revision 12878)
@@ -0,0 +1,36 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-3.2.2
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-3.2.2.tgz Python-3.2.2.tgz
+
+#exports
+export CC
+
+#Untar and move python into install directory
+tar -zxvf  Python-3.2.2.tgz
+mv Python-3.2.2/* src
+rm -rf Python-3.2.2
+
+#Configure python
+cd src 
+./configure \
+ --prefix="$ISSM_DIR/externalpackages/python/install" \
+ --enable-shared
+
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+cd ../install/bin
+ln -s python3.2 python 
+cd ../
+ln -s Python.framework/Versions/3.2/include/python3.2m include
+ln -s Python.framework/Versions/3.2/lib/ lib
Index: /issm/branches/trunk-jpl-damage/externalpackages/python/install-3.2.2-macosx-lion.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/python/install-3.2.2-macosx-lion.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/python/install-3.2.2-macosx-lion.sh	(revision 12878)
@@ -0,0 +1,39 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-3.2.2
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-3.2.2.tgz Python-3.2.2.tgz
+
+#exports
+export CC
+
+#Untar and move python into install directory
+tar -zxvf  Python-3.2.2.tgz
+mv Python-3.2.2/* src
+rm -rf Python-3.2.2
+
+#Configure doxygen
+cd src 
+./configure \
+ --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
+
+#obsolete? 
+#./configure --prefix="$ISSM_DIR/externalpackages/python/install" --enable-framework="$ISSM_DIR/externalpackages/python/install"
+
+#make
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+cd install/bin
+ln -s python3.2 python 
+cd ../
+ln -s Python.framework/Versions/3.2/include/python3.2m include
+ln -s Python.framework/Versions/3.2/lib/ lib
Index: /issm/branches/trunk-jpl-damage/externalpackages/python/install-3.2.2-macosx-snowleopard.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/python/install-3.2.2-macosx-snowleopard.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/python/install-3.2.2-macosx-snowleopard.sh	(revision 12878)
@@ -0,0 +1,39 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-3.2.2
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-3.2.2.tgz Python-3.2.2.tgz
+
+#exports
+export CC
+export MACOSX_DEPLOYMENT_TARGET=10.6
+
+#Untar and move python into install directory
+tar -zxvf  Python-3.2.2.tgz
+mv Python-3.2.2/* src
+rm -rf Python-3.2.2
+
+#Configure doxygen
+cd src 
+# --enable-framework needs to have the form "$SOME_PATH/Library/Frameworks" to avoid installing components in /Applications directory
+# --prefix is recognized as $SOME_PATH as long as this form is taken, so it's not necessary to include
+./configure \
+ --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
+
+#make
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+cd install/bin
+ln -s python3.2 python 
+cd ../
+ln -s Python.framework/Versions/3.2/include/python3.2m include
+ln -s Python.framework/Versions/3.2/lib/ lib
Index: sm/branches/trunk-jpl-damage/externalpackages/python/install-linux64-astrid.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/python/install-linux64-astrid.sh	(revision 12877)
+++ 	(revision )
@@ -1,43 +1,0 @@
-#!/bin/bash
-#wget http://python.org/ftp/python/version/Python-version.tgz
-
-#version=3.2.2
-version=2.7.2
-
-#Some cleanup
-rm -rf install src
-rm -rf Python-$version
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-$version.tgz Python-$version.tgz
-
-#exports
-export CC
-
-#Untar and move python into install directory
-tar -zxvf  Python-$version.tgz
-mv Python-$version/* src
-rm -rf Python-$version
-
-#Configure doxygen
-cd src 
-./configure --prefix="$ISSM_DIR/externalpackages/python/install" 
-
-if [ -z $1 ]; then
-	make
-else
-	make -j $1
-fi
-make install
-
-#Some modifications to be done in case version is 3.2: 
-if [[ $version == "3.2.2" ]]; then 
-	cd install/bin
-	ln -s python3.2 python 
-	cd ../
-	ln -s Python.framework/Versions/3.2/include/python3.2m include
-	ln -s Python.framework/Versions/3.2/lib/ lib
-
-
-fi
Index: sm/branches/trunk-jpl-damage/externalpackages/python/install-macosx-lion.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/python/install-macosx-lion.sh	(revision 12877)
+++ 	(revision )
@@ -1,42 +1,0 @@
-#!/bin/bash
-#wget http://python.org/ftp/python/version/Python-version.tgz
-
-#version=3.2.2
-version=2.7.2
-
-#Some cleanup
-rm -rf install src
-rm -rf Python-$version
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-$version.tgz Python-$version.tgz
-
-#exports
-export CC
-
-#Untar and move python into install directory
-tar -zxvf  Python-$version.tgz
-mv Python-$version/* src
-rm -rf Python-$version
-
-#Configure doxygen
-cd src 
-./configure --prefix="$ISSM_DIR/externalpackages/python/install" --enable-framework="$ISSM_DIR/externalpackages/python/install"
-if [ -z $1 ]; then
-	make
-else
-	make -j $1
-fi
-make install
-
-#Some modifications to be done in case version is 3.2: 
-if [[ $version == "3.2.2" ]]; then 
-	cd install/bin
-	ln -s python3.2 python 
-	cd ../
-	ln -s Python.framework/Versions/3.2/include/python3.2m include
-	ln -s Python.framework/Versions/3.2/lib/ lib
-
-
-fi
Index: sm/branches/trunk-jpl-damage/externalpackages/python/install-macosx-snowleopard.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/python/install-macosx-snowleopard.sh	(revision 12877)
+++ 	(revision )
@@ -1,41 +1,0 @@
-#!/bin/bash
-#wget http://python.org/ftp/python/version/Python-version.tgz
-
-#version=3.2.2
-version=2.7.2
-
-#Some cleanup
-rm -rf install src
-rm -rf Python-$version
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-$version.tgz Python-$version.tgz
-
-#exports
-export CC
-export MACOSX_DEPLOYMENT_TARGET=10.6
-
-#Untar and move python into install directory
-tar -zxvf  Python-$version.tgz
-mv Python-$version/* src
-rm -rf Python-$version
-
-#Configure doxygen
-cd src 
-./configure --prefix="$ISSM_DIR/externalpackages/python/install" --enable-framework="$ISSM_DIR/externalpackages/python/install" --enable-universalsdk --with-universal-archs="32-bit"
-if [ -z $1 ]; then
-	make
-else
-	make -j $1
-fi
-make install
-
-#Some modifications to be done in case version is 3.2: 
-if [[ $version == "3.2.2" ]]; then 
-	cd install/bin
-	ln -s python3.2 python 
-	cd ../
-	ln -s Python.framework/Versions/3.2/include/python3.2m include
-	ln -s Python.framework/Versions/3.2/lib/ lib
-fi
Index: /issm/branches/trunk-jpl-damage/externalpackages/python/patches/pyport.h.patch
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/python/patches/pyport.h.patch	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/python/patches/pyport.h.patch	(revision 12878)
@@ -0,0 +1,22 @@
+680a681
+> #ifdef isalnum
+682a684,685
+> #endif
+> #ifdef isalpha
+684a688,689
+> #endif
+> #ifdef islower
+686a692,693
+> #endif
+> #ifdef isspace
+688a696,697
+> #endif
+> #ifdef isupper
+690a700,701
+> #endif
+> #ifdef tolower
+692a704,705
+> #endif
+> #ifdef toupper
+695a709
+> #endif
Index: /issm/branches/trunk-jpl-damage/externalpackages/python/patches/pyport.h.patch.bugreport
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/python/patches/pyport.h.patch.bugreport	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/python/patches/pyport.h.patch.bugreport	(revision 12878)
@@ -0,0 +1,1 @@
+http://bugs.python.org/issue10910
Index: /issm/branches/trunk-jpl-damage/externalpackages/scipy/README
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/scipy/README	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/scipy/README	(revision 12878)
@@ -1,2 +1,9 @@
-You will find instructions on scipy at: 
+For OSX 10.7 (Lion), the instructions here can be followed:  
 http://www.scipy.org/Installing_SciPy/Mac_OS_X
+
+For OSX 10.6 (Snow Leopard), the scipy folks recommend gcc and g++ version 4.0.
+However, ISSM needs the gfortran version recommended in $ISSM_DIR/externalpackages/gfortran.
+On the webpage listed above, make sure the "export CC" and "export CXX" commands point to the 
+binaries associated with this gfortran version (likely in /usr/local/gfortran/bin by default).
+Once this gfortran is installed, the install script in this directory for Snow Leopard should
+work.
Index: /issm/branches/trunk-jpl-damage/externalpackages/scipy/install-linux64.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/scipy/install-linux64.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/scipy/install-linux64.sh	(revision 12878)
@@ -1,3 +1,5 @@
 #!/bin/bash
+PYVERSION=2.7
+PYTHON=python${PYVERSION}
 
 #1: install numpy
@@ -25,4 +27,7 @@
 	python setup.py build
 	python setup.py install
+	cd ..
+	${PYTHON} -c "import numpy; print 'Installed NumPy', numpy.__version__"
+	${PYTHON} -c "import numpy; numpy.test()"
 
 	
@@ -42,4 +47,7 @@
 	python setup.py build
 	python setup.py install
+	cd ..
+	${PYTHON} -c "import scipy; print 'Installed SciPy', scipy.__version__"
+	${PYTHON} -c "import scipy; scipy.test()"
 
 elif [[ $install == "3" ]];then 
Index: /issm/branches/trunk-jpl-damage/externalpackages/scipy/install-macosx-snowleopard.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/scipy/install-macosx-snowleopard.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/scipy/install-macosx-snowleopard.sh	(revision 12878)
@@ -8,6 +8,8 @@
 install=2
 
-export CC=/usr/bin/gcc-4.0
-export CXX=/usr/bin/g++-4.0
+# gfortran 4.6 (see ISSM_DIR/externalpackages/gfortran) is necessary for ISSM compilation.
+# On OSX 10.6, this recommended version gets installed in /usr/local/gfortran 
+export CC=/usr/local/gfortran/bin/gcc
+export CXX=/usr/local/gfortran/bin/g++
 
 if [[ $install == "1" ]];then 
@@ -22,4 +24,5 @@
 	cd ..
 	${PYTHON} -c "import numpy; print 'Installed NumPy', numpy.__version__"
+	${PYTHON} -c "import numpy; numpy.test()"
 	
 elif [[ $install == "2" ]];then 
@@ -34,4 +37,5 @@
 	cd ..
 	${PYTHON} -c "import scipy; print 'Installed SciPy', scipy.__version__"
+	${PYTHON} -c "import scipy; scipy.test()"
 
 elif [[ $install == "3" ]];then 
Index: /issm/branches/trunk-jpl-damage/externalpackages/tao/install-2.0.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/tao/install-2.0.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/tao/install-2.0.sh	(revision 12878)
@@ -0,0 +1,23 @@
+#!/bin/bash
+#http://www.mcs.anl.gov/research/projects/tao/download/index.html
+
+#Compatible with PETSc 3.2
+
+#Some cleanup
+rm -rf install tao-2.0-p3
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tao-2.0-p3.tar.gz' 'tao-2.0-p3.tar.gz'
+
+#Untar 
+tar -zxvf  tao-2.0-p3.tar.gz
+
+#move into place
+mv tao-2.0-p3/* install/
+rm -rf tao-2.0-p3
+cd install
+export TAO_DIR="$ISSM_DIR/externalpackages/tao/install/"
+
+#petsc needs to be compiled with --with-clanguage=C++
+make
Index: /issm/branches/trunk-jpl-damage/externalpackages/tao/install-2.1.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/tao/install-2.1.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/tao/install-2.1.sh	(revision 12878)
@@ -0,0 +1,23 @@
+#!/bin/bash
+#http://www.mcs.anl.gov/research/projects/tao/download/index.html
+
+#compatible with PETSc 3.3
+
+#Some cleanup
+rm -rf install tao-2.1-p0
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tao-2.1-p0.tar.gz' 'tao-2.1-p0.tar.gz'
+
+#Untar 
+tar -zxvf  tao-2.1-p0.tar.gz
+
+#move into place
+mv tao-2.1-p0/* install/
+rm -rf tao-2.1-p0
+cd install
+export TAO_DIR="$ISSM_DIR/externalpackages/tao/install/"
+
+#petsc needs to be compiled with --with-clanguage=C++
+make
Index: sm/branches/trunk-jpl-damage/externalpackages/tao/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/tao/install.sh	(revision 12877)
+++ 	(revision )
@@ -1,22 +1,0 @@
-#!/bin/bash
-#http://www.mcs.anl.gov/research/projects/tao/download/index.html
-#wget http://www.mcs.anl.gov/research/projects/tao/download/tao-2.0-p3.tar.gz
-
-#Some cleanup
-rm -rf install tao-2.0-p3
-mkdir install
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tao-2.0-p3.tar.gz' 'tao-2.0-p3.tar.gz'
-
-#Untar 
-tar -zxvf  tao-2.0-p3.tar.gz
-
-#move into place
-mv tao-2.0-p3/* install/
-rm -rf tao-2.0-p3
-cd install
-export TAO_DIR="$ISSM_DIR/externalpackages/tao/install/"
-
-#petsc needs to be compiled with --with-clanguage=C++
-make
Index: /issm/branches/trunk-jpl-damage/externalpackages/tcl/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/tcl/install.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/tcl/install.sh	(revision 12878)
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf tcl8.5.11
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tcl8.5.11.tar.gz' 'tcl8.5.11.tar.gz'
+
+#Untar 
+tar -zxvf  tcl8.5.11.tar.gz
+
+#Move tcl into src directory
+mv tcl8.5.11/* src
+rm -rf tcl8.5.11
+
+#Configure tcl
+ver="8.4.12"
+
+cd src
+make -C ./macosx install INSTALL_ROOT="$ISSM_DIR/externalpackages/tcl/install"
Index: /issm/branches/trunk-jpl-damage/externalpackages/tclx/install.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/tclx/install.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/tclx/install.sh	(revision 12878)
@@ -0,0 +1,31 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf tclx8.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tclx8.4.tar.gz' 'tclx8.4.tar.gz'
+
+#Untar 
+tar -zxvf  tclx8.4.tar.gz
+
+#Move tclx into src directory
+mv tclx8.4/* src
+rm -rf tclx8.4
+
+#Configure tclx
+cd src
+./configure --prefix="$ISSM_DIR/externalpackages/tclx/install"  \
+			--exec-prefix="$ISSM_DIR/externalpackages/tclx/install"  \
+	        --with-tcl=$ISSM_DIR/externalpackages/tcl/install/Library/Frameworks/Tcl.framework
+
+#Compile and install tclx
+if [ -z $1 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/branches/trunk-jpl-damage/externalpackages/triangle/configs/android/configure.make
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/triangle/configs/android/configure.make	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/triangle/configs/android/configure.make	(revision 12878)
@@ -0,0 +1,20 @@
+# This makefile configures build process to cross-compile to the android platform.
+# The binary tools referenced below are specifically configured to target armeabi-v7a.
+# Furthermore, the compilers (which are simply wrappers around GNU GCC) are set to
+# produce binaries that are EABI compliant.
+#
+# Note that the AAPCS standard defines 'EABI' as a moniker used to specify
+# a _family_ of similar but distinct ABIs. Android follows the little-endian
+# ARM GNU/Linux ABI as documented in the following document:
+#
+# http://www.codesourcery.com/gnu_toolchains/arm/arm_gnu_linux_abi.pdf
+
+source $ANDROID_DIR/android_aux.sh
+
+CC=${toolchain_path}-gcc
+AR=${toolchain_path}-ar
+RANLIB=${toolchain_path}-ranlib
+CSWITCHES = $(CFLAGS)
+TRILIBDEFS = -DTRILIBRARY
+OBJ_EXT=o
+LIB_EXT=a
Index: sm/branches/trunk-jpl-damage/externalpackages/triangle/install-android-4.0.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/triangle/install-android-4.0.sh	(revision 12877)
+++ 	(revision )
@@ -1,33 +1,0 @@
-#!/bin/bash
-
-#use matlab? 
-matlab=0
-
-#Some cleanup 
-rm -rf install triangle
-mkdir install
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
-
-#Untar 
-cd install
-cp ../triangle.zip ./
-unzip triangle.zip
-
-#copy new makefile
-cp ../configs/android/android-4.0/configure.make ./
-cp ../makefile ./
-
-#Patch triangle.c 
-if [[ $matlab == "1" ]];then
-	patch triangle.c ../triangle.c.patch.matlab
-else
-	patch triangle.c ../triangle.c.patch.python
-fi
-
-#Compile triangle
-make
-
-#Patch triangle.h
-patch triangle.h ../triangle.h.patch
Index: /issm/branches/trunk-jpl-damage/externalpackages/triangle/install-android.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/triangle/install-android.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/triangle/install-android.sh	(revision 12878)
@@ -0,0 +1,34 @@
+#!/bin/bash
+source $ANDROID_DIR/android_aux.sh
+
+# use matlab? 
+matlab=0
+
+# Some cleanup 
+rm -rf install triangle
+mkdir install
+
+# Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+# Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+# copy new makefile
+cp ../configs//android/configure.make ./
+cp ../makefile ./
+
+# Patch triangle.c 
+if [[ $matlab == "1" ]];then
+	patch triangle.c ../triangle.c.patch.matlab
+else
+	patch triangle.c ../triangle.c.patch.python
+fi
+
+# Compile triangle
+make -j $j
+
+# Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/branches/trunk-jpl-damage/externalpackages/triangle/install-discover.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/triangle/install-discover.sh	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/externalpackages/triangle/install-discover.sh	(revision 12878)
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+#Some cleanup 
+rm -rf install triangle
+mkdir install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#Untar 
+cd install
+cp ../triangle.zip ./
+unzip triangle.zip
+
+#copy new makefile
+cp ../configs/pleiades/configure.make ./
+cp ../makefile ./
+
+#Patch triangle.c 
+patch triangle.c ../triangle.c.patch
+
+#Compile triangle
+make
+
+#Patch triangle.h
+patch triangle.h ../triangle.h.patch
Index: /issm/branches/trunk-jpl-damage/externalpackages/triangle/install-macosx64.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/triangle/install-macosx64.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/triangle/install-macosx64.sh	(revision 12878)
@@ -1,7 +1,3 @@
 #!/bin/bash
-
-#use matlab? 
-matlab=0
-
 
 #Some cleanup 
@@ -22,9 +18,5 @@
 
 #Patch triangle.c 
-if [[ $matlab == "1" ]];then
-	patch triangle.c ../triangle.c.patch.matlab
-else
-	patch triangle.c ../triangle.c.patch.python
-fi
+patch triangle.c ../triangle.c.patch
 
 #Compile triangle
Index: /issm/branches/trunk-jpl-damage/externalpackages/triangle/triangle.c.patch
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/triangle/triangle.c.patch	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/triangle/triangle.c.patch	(revision 12878)
@@ -5,6 +5,6 @@
 >  * double precision activation in exactinit(); The rest is not changed. 
 >  * We also created the ice_makefile to compile Triangle into a library. */
-> #include <mat.h>
-> #include <matrix.h>
+> /* #include <mat.h>
+> #include <matrix.h> */
 > #define ANSI_DECLARATORS
 > #define NO_TIMER
@@ -134,11 +134,11 @@
 <   memptr = (VOID *) malloc((unsigned int) size);
 ---
->   memptr = (VOID *) mxMalloc((unsigned int) size);
->   //memptr = (VOID *) malloc((unsigned int) size);
+>   //memptr = (VOID *) mxMalloc((unsigned int) size);
+>   memptr = (VOID *) malloc((unsigned int) size);
 1447c1543,1544
 <   free(memptr);
 ---
->   //free(memptr);
->   mxFree(memptr);
+>   free(memptr);
+>   //mxFree(memptr);
 3665,3670c3762,3767
 < void printtriangle(struct mesh *m, struct behavior *b, struct otri *t)
Index: sm/branches/trunk-jpl-damage/externalpackages/triangle/triangle.c.patch.matlab
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/triangle/triangle.c.patch.matlab	(revision 12877)
+++ 	(revision )
@@ -1,164 +1,0 @@
-0a1,10
-> /*Notes for the Ice code: 
->  * to be able to compile Triangle within a mex function that can run within 
->  * matlab, we had to change the allocation routine trimalloc, as well as the 
->  * double precision activation in exactinit(); The rest is not changed. 
->  * We also created the ice_makefile to compile Triangle into a library. */
-> #include <mat.h>
-> #include <matrix.h>
-> #define ANSI_DECLARATORS
-> #define NO_TIMER
-> 
-347a358
-> #ifndef _WIN_
-348a360
-> #endif
-641d652
-< 
-817a829,922
-> /*Some missing prototypes: */
-> int scale_expansion_zeroelim(int elen, REAL *e, REAL b, REAL *h);
-> int fast_expansion_sum_zeroelim(int elen, REAL *e, int flen, REAL *f, REAL *h);
-> void poolzero(struct memorypool *pool);
-> int triunsuitable(vertex triorg, vertex tridest, vertex triapex, REAL area);
-> triangle *triangletraverse(struct mesh *m);
-> void pooldeinit(struct memorypool *pool);
-> void printtriangle(struct mesh *m, struct behavior *b, struct otri *t);
-> VOID *poolalloc(struct memorypool *pool);
-> void enqueuebadtriang(struct mesh *m, struct behavior *b,
->                       struct badtriang *badtri);
-> void triangulatepolygon(struct mesh *m, struct behavior *b,
->                         struct otri *firstedge, struct otri *lastedge,
->                         int edgecount, int doflip, int triflaws);
-> void triangledealloc(struct mesh *m, triangle *dyingtriangle);
-> void unflip(struct mesh *m, struct behavior *b, struct otri *flipedge);
-> void vertexmedian(vertex *sortarray, int arraysize, int median, int axis);
-> REAL counterclockwiseadapt(vertex pa, vertex pb, vertex pc, REAL detsum);
-> REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent);
-> void enqueuebadtri(struct mesh *m, struct behavior *b, struct otri *enqtri,
->                    REAL minedge, vertex enqapex, vertex enqorg, vertex enqdest);
-> void alternateaxes(vertex *sortarray, int arraysize, int axis);
-> REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent);
-> void maketriangle(struct mesh *m, struct behavior *b, struct otri *newotri);
-> REAL counterclockwise(struct mesh *m, struct behavior *b,
->                       vertex pa, vertex pb, vertex pc);
-> vertex vertextraverse(struct mesh *m);
-> void mergehulls(struct mesh *m, struct behavior *b, struct otri *farleft,
->                 struct otri *innerleft, struct otri *innerright,
->                 struct otri *farright, int axis);
-> REAL incircle(struct mesh *m, struct behavior *b,
->               vertex pa, vertex pb, vertex pc, vertex pd);
-> void poolrestart(struct memorypool *pool);
-> void trifree(VOID *memptr);
-> struct splaynode *splay(struct mesh *m, struct splaynode *splaytree,
->                         vertex searchpoint, struct otri *searchtri);
-> void eventheapdelete(struct event **heap, int heapsize, int eventnum);
-> void eventheapdelete(struct event **heap, int heapsize, int eventnum);
-> void flip(struct mesh *m, struct behavior *b, struct otri *flipedge);
-> void check4deadevent(struct otri *checktri, struct event **freeevents,
->                      struct event **eventheap, int *heapsize);
-> REAL orient3d(struct mesh *m, struct behavior *b,
->               vertex pa, vertex pb, vertex pc, vertex pd,
->               REAL aheight, REAL bheight, REAL cheight, REAL dheight);
-> REAL circletop(struct mesh *m, vertex pa, vertex pb, vertex pc, REAL ccwabc);
-> void poolinit(struct memorypool *pool, int bytecount, int itemcount,
->               int firstitemcount, int alignment);
-> void eventheapinsert(struct event **heap, int heapsize, struct event *newevent);
-> int rightofhyperbola(struct mesh *m, struct otri *fronttri, vertex newsite);
-> void insertsubseg(struct mesh *m, struct behavior *b, struct otri *tri,
->                   int subsegmark);
-> int scoutsegment(struct mesh *m, struct behavior *b, struct otri *searchtri,
->                  vertex endpoint2, int newmark);
-> vertex getvertex(struct mesh *m, struct behavior *b, int number);
-> void internalerror();
-> unsigned long randomnation(unsigned int choices);
-> struct splaynode *splayinsert(struct mesh *m, struct splaynode *splayroot,
->                               struct otri *newkey, vertex searchpoint);
-> void delaunayfixup(struct mesh *m, struct behavior *b,
->                    struct otri *fixuptri, int leftside);
-> void traversalinit(struct memorypool *pool);
-> enum insertvertexresult insertvertex(struct mesh *m, struct behavior *b,
->                                      vertex newvertex, struct otri *searchtri,
->                                      struct osub *splitseg,
->                                      int segmentflaws, int triflaws);
-> void conformingedge(struct mesh *m, struct behavior *b,
->                     vertex endpoint1, vertex endpoint2, int newmark);
-> enum finddirectionresult finddirection(struct mesh *m, struct behavior *b,
->                                        struct otri *searchtri,
->                                        vertex searchpoint);
-> VOID *traverse(struct memorypool *pool);
-> void deletevertex(struct mesh *m, struct behavior *b, struct otri *deltri);
-> void pooldealloc(struct memorypool *pool, VOID *dyingitem);
-> int checkseg4encroach(struct mesh *m, struct behavior *b,
->                       struct osub *testsubseg);
-> void badsubsegdealloc(struct mesh *m, struct badsubseg *dyingseg);
-> void vertexdealloc(struct mesh *m, vertex dyingvertex);
-> void vertexsort(vertex *sortarray, int arraysize);
-> void tallyencs(struct mesh *m, struct behavior *b);
-> void splittriangle(struct mesh *m, struct behavior *b,
->                    struct badtriang *badtri);
-> subseg *subsegtraverse(struct mesh *m);
-> enum locateresult locate(struct mesh *m, struct behavior *b,
->                          vertex searchpoint, struct otri *searchtri);
-> void writenodes(struct mesh *m, struct behavior *b, REAL **pointlist,
->                 REAL **pointattriblist, int **pointmarkerlist);
-> void writevoronoi(struct mesh *m, struct behavior *b, REAL **vpointlist,
->                   REAL **vpointattriblist, int **vpointmarkerlist,
->                   int **vedgelist, int **vedgemarkerlist, REAL **vnormlist);
-> void writeneighbors(struct mesh *m, struct behavior *b, int **neighborlist);
-> void testtriangle(struct mesh *m, struct behavior *b, struct otri *testtri);
-> void triangleinit(struct mesh *m);
-> 
-> 
-1408a1514
-> void triexit(int status);
-1410d1515
-< #ifdef ANSI_DECLARATORS
-1412,1416d1516
-< #else /* not ANSI_DECLARATORS */
-< void triexit(status)
-< int status;
-< #endif /* not ANSI_DECLARATORS */
-< 
-1421c1521
-< #ifdef ANSI_DECLARATORS
----
-> VOID *trimalloc(int size);
-1423,1427d1522
-< #else /* not ANSI_DECLARATORS */
-< VOID *trimalloc(size)
-< int size;
-< #endif /* not ANSI_DECLARATORS */
-< 
-1431c1526,1527
-<   memptr = (VOID *) malloc((unsigned int) size);
----
->   memptr = (VOID *) mxMalloc((unsigned int) size);
->   //memptr = (VOID *) malloc((unsigned int) size);
-1447c1543,1544
-<   free(memptr);
----
->   //free(memptr);
->   mxFree(memptr);
-3665,3670c3762,3767
-< void printtriangle(struct mesh *m, struct behavior *b, struct otri *t)
-< #else /* not ANSI_DECLARATORS */
-< void printtriangle(m, b, t)
-< struct mesh *m;
-< struct behavior *b;
-< struct otri *t;
----
-> void printtriangle(struct mesh *m, struct behavior *b, struct otri *t){
-> //#else /* not ANSI_DECLARATORS */
-> //void printtriangle(m, b, t)
-> //struct mesh *m;
-> //struct behavior *b;
-> //struct otri *t;
-3673c3770
-< {
----
-> //{
-4910c5007
-<   _FPU_SETCW(cword);
----
->   //_FPU_SETCW(cword); //taken care of by Matlab
Index: sm/branches/trunk-jpl-damage/externalpackages/triangle/triangle.c.patch.python
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/triangle/triangle.c.patch.python	(revision 12877)
+++ 	(revision )
@@ -1,164 +1,0 @@
-0a1,10
-> /*Notes for the Ice code: 
->  * to be able to compile Triangle within a mex function that can run within 
->  * matlab, we had to change the allocation routine trimalloc, as well as the 
->  * double precision activation in exactinit(); The rest is not changed. 
->  * We also created the ice_makefile to compile Triangle into a library. */
-> /* #include <mat.h>
-> #include <matrix.h> */
-> #define ANSI_DECLARATORS
-> #define NO_TIMER
-> 
-347a358
-> #ifndef _WIN_
-348a360
-> #endif
-641d652
-< 
-817a829,922
-> /*Some missing prototypes: */
-> int scale_expansion_zeroelim(int elen, REAL *e, REAL b, REAL *h);
-> int fast_expansion_sum_zeroelim(int elen, REAL *e, int flen, REAL *f, REAL *h);
-> void poolzero(struct memorypool *pool);
-> int triunsuitable(vertex triorg, vertex tridest, vertex triapex, REAL area);
-> triangle *triangletraverse(struct mesh *m);
-> void pooldeinit(struct memorypool *pool);
-> void printtriangle(struct mesh *m, struct behavior *b, struct otri *t);
-> VOID *poolalloc(struct memorypool *pool);
-> void enqueuebadtriang(struct mesh *m, struct behavior *b,
->                       struct badtriang *badtri);
-> void triangulatepolygon(struct mesh *m, struct behavior *b,
->                         struct otri *firstedge, struct otri *lastedge,
->                         int edgecount, int doflip, int triflaws);
-> void triangledealloc(struct mesh *m, triangle *dyingtriangle);
-> void unflip(struct mesh *m, struct behavior *b, struct otri *flipedge);
-> void vertexmedian(vertex *sortarray, int arraysize, int median, int axis);
-> REAL counterclockwiseadapt(vertex pa, vertex pb, vertex pc, REAL detsum);
-> REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent);
-> void enqueuebadtri(struct mesh *m, struct behavior *b, struct otri *enqtri,
->                    REAL minedge, vertex enqapex, vertex enqorg, vertex enqdest);
-> void alternateaxes(vertex *sortarray, int arraysize, int axis);
-> REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent);
-> void maketriangle(struct mesh *m, struct behavior *b, struct otri *newotri);
-> REAL counterclockwise(struct mesh *m, struct behavior *b,
->                       vertex pa, vertex pb, vertex pc);
-> vertex vertextraverse(struct mesh *m);
-> void mergehulls(struct mesh *m, struct behavior *b, struct otri *farleft,
->                 struct otri *innerleft, struct otri *innerright,
->                 struct otri *farright, int axis);
-> REAL incircle(struct mesh *m, struct behavior *b,
->               vertex pa, vertex pb, vertex pc, vertex pd);
-> void poolrestart(struct memorypool *pool);
-> void trifree(VOID *memptr);
-> struct splaynode *splay(struct mesh *m, struct splaynode *splaytree,
->                         vertex searchpoint, struct otri *searchtri);
-> void eventheapdelete(struct event **heap, int heapsize, int eventnum);
-> void eventheapdelete(struct event **heap, int heapsize, int eventnum);
-> void flip(struct mesh *m, struct behavior *b, struct otri *flipedge);
-> void check4deadevent(struct otri *checktri, struct event **freeevents,
->                      struct event **eventheap, int *heapsize);
-> REAL orient3d(struct mesh *m, struct behavior *b,
->               vertex pa, vertex pb, vertex pc, vertex pd,
->               REAL aheight, REAL bheight, REAL cheight, REAL dheight);
-> REAL circletop(struct mesh *m, vertex pa, vertex pb, vertex pc, REAL ccwabc);
-> void poolinit(struct memorypool *pool, int bytecount, int itemcount,
->               int firstitemcount, int alignment);
-> void eventheapinsert(struct event **heap, int heapsize, struct event *newevent);
-> int rightofhyperbola(struct mesh *m, struct otri *fronttri, vertex newsite);
-> void insertsubseg(struct mesh *m, struct behavior *b, struct otri *tri,
->                   int subsegmark);
-> int scoutsegment(struct mesh *m, struct behavior *b, struct otri *searchtri,
->                  vertex endpoint2, int newmark);
-> vertex getvertex(struct mesh *m, struct behavior *b, int number);
-> void internalerror();
-> unsigned long randomnation(unsigned int choices);
-> struct splaynode *splayinsert(struct mesh *m, struct splaynode *splayroot,
->                               struct otri *newkey, vertex searchpoint);
-> void delaunayfixup(struct mesh *m, struct behavior *b,
->                    struct otri *fixuptri, int leftside);
-> void traversalinit(struct memorypool *pool);
-> enum insertvertexresult insertvertex(struct mesh *m, struct behavior *b,
->                                      vertex newvertex, struct otri *searchtri,
->                                      struct osub *splitseg,
->                                      int segmentflaws, int triflaws);
-> void conformingedge(struct mesh *m, struct behavior *b,
->                     vertex endpoint1, vertex endpoint2, int newmark);
-> enum finddirectionresult finddirection(struct mesh *m, struct behavior *b,
->                                        struct otri *searchtri,
->                                        vertex searchpoint);
-> VOID *traverse(struct memorypool *pool);
-> void deletevertex(struct mesh *m, struct behavior *b, struct otri *deltri);
-> void pooldealloc(struct memorypool *pool, VOID *dyingitem);
-> int checkseg4encroach(struct mesh *m, struct behavior *b,
->                       struct osub *testsubseg);
-> void badsubsegdealloc(struct mesh *m, struct badsubseg *dyingseg);
-> void vertexdealloc(struct mesh *m, vertex dyingvertex);
-> void vertexsort(vertex *sortarray, int arraysize);
-> void tallyencs(struct mesh *m, struct behavior *b);
-> void splittriangle(struct mesh *m, struct behavior *b,
->                    struct badtriang *badtri);
-> subseg *subsegtraverse(struct mesh *m);
-> enum locateresult locate(struct mesh *m, struct behavior *b,
->                          vertex searchpoint, struct otri *searchtri);
-> void writenodes(struct mesh *m, struct behavior *b, REAL **pointlist,
->                 REAL **pointattriblist, int **pointmarkerlist);
-> void writevoronoi(struct mesh *m, struct behavior *b, REAL **vpointlist,
->                   REAL **vpointattriblist, int **vpointmarkerlist,
->                   int **vedgelist, int **vedgemarkerlist, REAL **vnormlist);
-> void writeneighbors(struct mesh *m, struct behavior *b, int **neighborlist);
-> void testtriangle(struct mesh *m, struct behavior *b, struct otri *testtri);
-> void triangleinit(struct mesh *m);
-> 
-> 
-1408a1514
-> void triexit(int status);
-1410d1515
-< #ifdef ANSI_DECLARATORS
-1412,1416d1516
-< #else /* not ANSI_DECLARATORS */
-< void triexit(status)
-< int status;
-< #endif /* not ANSI_DECLARATORS */
-< 
-1421c1521
-< #ifdef ANSI_DECLARATORS
----
-> VOID *trimalloc(int size);
-1423,1427d1522
-< #else /* not ANSI_DECLARATORS */
-< VOID *trimalloc(size)
-< int size;
-< #endif /* not ANSI_DECLARATORS */
-< 
-1431c1526,1527
-<   memptr = (VOID *) malloc((unsigned int) size);
----
->   //memptr = (VOID *) mxMalloc((unsigned int) size);
->   memptr = (VOID *) malloc((unsigned int) size);
-1447c1543,1544
-<   free(memptr);
----
->   free(memptr);
->   //mxFree(memptr);
-3665,3670c3762,3767
-< void printtriangle(struct mesh *m, struct behavior *b, struct otri *t)
-< #else /* not ANSI_DECLARATORS */
-< void printtriangle(m, b, t)
-< struct mesh *m;
-< struct behavior *b;
-< struct otri *t;
----
-> void printtriangle(struct mesh *m, struct behavior *b, struct otri *t){
-> //#else /* not ANSI_DECLARATORS */
-> //void printtriangle(m, b, t)
-> //struct mesh *m;
-> //struct behavior *b;
-> //struct otri *t;
-3673c3770
-< {
----
-> //{
-4910c5007
-<   _FPU_SETCW(cword);
----
->   //_FPU_SETCW(cword); //taken care of by Matlab
Index: /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/Synchronize.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 12878)
@@ -6,5 +6,5 @@
 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 "[Aa-Zz]Enum," | grep -v StringToEnum | sed -e "s/,//g" | awk '{ printf "syn keyword cConstant " $1 "\n"}' >> temp
+cat ../../../../../src/c/EnumDefinitions/EnumDefinitions.h | grep -e "[0-9]Enum," -e "[aA-zZ]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
Index: /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/c.vim
===================================================================
--- /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/c.vim	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/externalpackages/vim/addons/vim/syntax/c.vim	(revision 12878)
@@ -404,9 +404,9 @@
 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
 "ISSM containers:
-syn keyword	cType		Constraints DataSet Elements Inputs Loads Materials Nodes Parameters Results Vertices
+syn keyword	cType		Constraints DataSet Elements Inputs Loads Materials Nodes Parameters Results Vertices Options
 "Petsc
-syn keyword	cType		Vec Mat
+syn keyword	cType		Vec Mat SeqVec SeqMat
 "other ISSM's syntax
-syn keyword	cType		mxArray ErrorException
+syn keyword	cType		mxArray ErrorException QuadtreeBox IssmDouble IssmPDouble
 
 "ISSM's objects begin
@@ -545,5 +545,5 @@
 syn keyword cType Mesh
 syn keyword cType Geometry
-syn keyword cType QuadTree
+syn keyword cType BamgQuadtree
 syn keyword cType SetOfE4
 syn keyword cType Variogram
@@ -551,4 +551,5 @@
 syn keyword cType ExponentialVariogram
 syn keyword cType SphericalVariogram
+syn keyword cType PowerVariogram
 syn keyword cType Quadtree
 syn keyword cType Observation
@@ -649,4 +650,5 @@
 syn keyword cConstant MaterialsRhoIceEnum
 syn keyword cConstant MaterialsRhoWaterEnum
+syn keyword cConstant MaterialsRhoFreshwaterEnum
 syn keyword cConstant MaterialsMuWaterEnum
 syn keyword cConstant MaterialsThermalExchangeVelocityEnum
@@ -694,8 +696,15 @@
 syn keyword cConstant SettingsResultsAsPatchesEnum
 syn keyword cConstant SettingsWaitonlockEnum
-syn keyword cConstant DebugPetscProfilingEnum
-syn keyword cConstant PetscProfilingCurrentMemEnum
-syn keyword cConstant PetscProfilingCurrentFlopsEnum
-syn keyword cConstant PetscProfilingSolutionTimeEnum
+syn keyword cConstant SurfaceforcingsDelta18oEnum
+syn keyword cConstant SurfaceforcingsDelta18oTemperaturesPresentdayEnum
+syn keyword cConstant SurfaceforcingsDelta18oTemperaturesLgmEnum
+syn keyword cConstant SurfaceforcingsDelta18oSurfaceEnum
+syn keyword cConstant SurfaceforcingsIsdelta18oEnum
+syn keyword cConstant SurfaceforcingsPrecipitationsPresentdayEnum
+syn keyword cConstant DebugProfilingEnum
+syn keyword cConstant ProfilingCurrentMemEnum
+syn keyword cConstant ProfilingCurrentFlopsEnum
+syn keyword cConstant ProfilingSolutionTimeEnum
+syn keyword cConstant MaxIterationConvergenceFlagEnum
 syn keyword cConstant SteadystateMaxiterEnum
 syn keyword cConstant SteadystateNumRequestedOutputsEnum
@@ -796,4 +805,5 @@
 syn keyword cConstant IntParamEnum
 syn keyword cConstant IntVecParamEnum
+syn keyword cConstant TransientParamEnum
 syn keyword cConstant MacAyeal2dIceFrontEnum
 syn keyword cConstant MacAyeal3dIceFrontEnum
@@ -915,4 +925,5 @@
 syn keyword cConstant StressTensorzzEnum
 syn keyword cConstant IceVolumeEnum
+syn keyword cConstant TotalSmbEnum
 syn keyword cConstant P0Enum
 syn keyword cConstant P1Enum
Index: /issm/branches/trunk-jpl-damage/m4/issm_options.m4
===================================================================
--- /issm/branches/trunk-jpl-damage/m4/issm_options.m4	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/m4/issm_options.m4	(revision 12878)
@@ -12,5 +12,14 @@
 		AC_DEFINE([_ISSM_DEBUG_],[1],[Macro to enable debugging in ISSM])
 	fi
-	dnl }}}
+
+	dnl }}}
+    dnl shared build {{{
+    AC_ARG_ENABLE([shared],                                                dnl feature
+        AS_HELP_STRING([--enable-shared], [produce libISSM.so.0]),         dnl help string
+        [enable_shared=$enableval],                                        dnl action if given
+        [enable_shared=no])                                                dnl action if not given
+    AM_CONDITIONAL([SHARED], [test $enable_shared = yes])
+    dnl }}}
+
 	dnl Modules build {{{
 	AC_ARG_WITH([modules],
@@ -60,4 +69,9 @@
 			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_ "
+			export CFLAGS=" -O3 -D_INTEL_LINUX_ "
 		elif test $VENDOR = intel-pleiades; then
 			export CC=icc
@@ -65,10 +79,4 @@
 			export CXXFLAGS=" -O3 -xS -D_INTEL_LINUX_ "
 			export CFLAGS=" -O3 -xS -D_INTEL_LINUX_ "
-		elif test $VENDOR = arm-linux; then
-			export CC=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-gcc
-			export GCC=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-gcc
-			export CXX=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-g++
-			export AR=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-ar
-			export RANLIB=$ANDROID_DIR/arm-linux-android-4.0/bin/arm-linux-androideabi-ranlib
         else
 		AC_MSG_ERROR([unknow compiler vendor!])
@@ -308,24 +316,4 @@
 	AC_MSG_RESULT($HAVE_BOOST)
 	dnl }}}
-	dnl python-version{{{
-	AC_ARG_WITH([python-version],
-	  AS_HELP_STRING([--with-python-version = PYTHONVERSION],[python version.]),
-	  [PYTHONVERSION=$withval],[PYTHONVERSION=""])
-	AC_MSG_CHECKING(for python version)
-
-	HAVE_PYTHON3="no"
-
-	dnl recover major: 
-	PYTHON_MAJOR=${PYTHONVERSION%.*}
-
-	if test x$PYTHON_MAJOR = x3; then
-		dnl are we running python 3?
-		HAVE_PYTHON3="yes"
-	fi
-	AC_DEFINE_UNQUOTED([_PYTHON_MAJOR_],$PYTHON_MAJOR,[python version major])
-
-	AM_CONDITIONAL([PYTHON3], [test x$HAVE_PYTHON3 = xyes])
-	AC_MSG_RESULT($PYTHON_MAJOR)
-	dnl }}}
 	dnl python{{{
 	AC_ARG_WITH([python-dir],
@@ -336,9 +324,37 @@
 	if test -d "$PYTHON_ROOT"; then
 		dnl defaults
+		HAVE_PYTHON3="no"
 		HAVE_PYTHON=yes
+		
+		AC_ARG_WITH([python-version],
+		  AS_HELP_STRING([--with-python-version = PYTHONVERSION],[python version.]),
+		  [PYTHONVERSION=$withval],[PYTHONVERSION=""])
+		AC_MSG_CHECKING(for python version)
+
+		dnl recover major: 
+		PYTHON_MAJOR=${PYTHONVERSION%.*}
+
+		if test x$PYTHON_MAJOR = x3; then
+			dnl are we running python 3?
+			HAVE_PYTHON3="yes"
+		fi
+		AC_DEFINE_UNQUOTED([_PYTHON_MAJOR_],$PYTHON_MAJOR,[python version major])
+		AC_MSG_RESULT($PYTHON_MAJOR)
+
 		PYTHONINCL=-I$PYTHON_ROOT/include
 		PYTHONLIB="-L$PYTHON_ROOT/lib -lpython$PYTHONVERSION"
 		PYTHONEXT=.so
-		PYTHONLINK="-dynamiclib"
+
+		case "${host_os}" in
+			*cygwin*)
+			PYTHONLINK="-shared"
+			;;
+			*linux*)
+			PYTHONLINK="-shared"
+			;;
+			*darwin*)
+			PYTHONLINK="-dynamiclib"
+			;;
+		esac
 
 		AC_DEFINE([_HAVE_PYTHON_],[1],[with Python in ISSM src])
@@ -352,5 +368,7 @@
 	fi
 	AM_CONDITIONAL([PYTHON], [test x$HAVE_PYTHON = xyes])
+	AM_CONDITIONAL([PYTHON3], [test x$HAVE_PYTHON3 = xyes])
 	AC_MSG_RESULT($HAVE_PYTHON)
+
 	dnl }}}
 	dnl python-numpy{{{
@@ -429,5 +447,5 @@
 			dnl defaults
 			HAVE_ADOLC=yes
-			ADOLCINCL="-I$ADOLC_ROOT/include/adolc -I$ADOLC_ROOT/include"
+			ADOLCINCL="-I$ADOLC_ROOT/include"
 			ADOLCLIB="-L$ADOLC_ROOT/lib64 -ladolc"
 
@@ -483,5 +501,5 @@
 		HAVE_GSL=yes
 		GSLINCL="-I$GSL_ROOT/include"
-		GSLLIB="-L$GSL_ROOT/lib/ -lgsl -lgslcblas -lm"
+		GSLLIB="-dy -L$GSL_ROOT/lib/ -lgsl -lgslcblas -lm"
 
 		AC_DEFINE([_HAVE_GSL_],[1],[with gsl in ISSM src])
@@ -523,7 +541,7 @@
 	  [METIS_ROOT=$withval],[METIS_ROOT=""])
 
+   AC_MSG_CHECKING(for metis headers and libraries in $METIS_ROOT)
+
 	if test -d "$METIS_ROOT"; then
-
-		AC_MSG_CHECKING(for metis headers and libraries in $METIS_ROOT)
 
 		dnl first figure out version of metis: does the VERSION file exist?
@@ -579,4 +597,5 @@
 	fi
 	AM_CONDITIONAL([METIS], [test x$HAVE_METIS = xyes])
+	AC_MSG_RESULT($HAVE_METIS)
 	dnl }}}
 	dnl mpi{{{
@@ -746,5 +765,9 @@
 		dnl defaults
 		HAVE_SCALAPACK=yes
-		SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lscalapack"
+		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])
@@ -766,5 +789,8 @@
 		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
@@ -779,4 +805,5 @@
 			;;
 		esac
+		fi
 
 		AC_DEFINE([_HAVE_BLASLAPACK_],[1],[with blas lapack in ISSM src])
@@ -853,4 +880,5 @@
 		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
@@ -875,5 +903,9 @@
 		HAVE_BLACS=yes
 		BLACSINCL=""
-		BLACSLIB=-L"$BLACS_ROOT/ -lblacs"
+		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])
@@ -896,5 +928,5 @@
 		HAVE_HYPRE=yes
 		HYPREINCL=""
-		HYPRELIB=-L"$HYPRE_ROOT/ -lHYPRE"
+		HYPRELIB=-L"$HYPRE_ROOT/lib -lHYPRE"
         
 		AC_DEFINE([_HAVE_HYPRE_],[1],[with Blacs in ISSM src])
@@ -906,4 +938,109 @@
 	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],
@@ -944,25 +1081,34 @@
 	dnl }}}
 	dnl fortran{{{
-	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
-	HAVE_FORTRAN=no
-	if test -n "$FORTRAN_LIB" ; then
-        if test x$FORTRAN_LIB = xno; then
-            HAVE_FORTRAN=NO
-        else
-            HAVE_FORTRAN=yes
-            FORTRANLIB="$FORTRAN_LIB"
-
-            AC_DEFINE([_HAVE_FORTRAN_],[1],[with FORTRAN in ISSM src])
-            AC_SUBST([FORTRANLIB])
-        fi
-	fi
-	AM_CONDITIONAL([FORTRAN], [test x$HAVE_FORTRAN = xyes])
-	AC_MSG_RESULT(done)
+	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
+			FORTRANLIB="$FORTRAN_LIB"
+			AC_DEFINE([_HAVE_FORTRAN_],[1],[with FORTRAN in ISSM src])
+			AC_SUBST([FORTRANLIB])
+		fi
+		AC_MSG_RESULT(done)
+	fi
 	dnl }}}
 	dnl graphics{{{
@@ -981,4 +1127,21 @@
 	fi
 	AC_MSG_RESULT(done)
+	dnl }}}
+
+	dnl Capabilities
+	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{{{
@@ -1301,3 +1464,12 @@
 	AC_MSG_RESULT($USE_64BIT_INDICES)
 	dnl }}}
+	dnl circular-dependency{{{
+	AC_ARG_WITH([circular-dependency],
+	  AS_HELP_STRING([--with-circular-dependency = bool],[do we look for circular dependencies, default "yes", ex: --with-circular-dependency="no"]),
+	  [CIRCULAR_DEPENDENCIES=$withval],[CIRCULAR_DEPENDENCIES=yes]) 
+	AC_MSG_CHECKING(for circular dependencies)
+	AM_CONDITIONAL([CIRCULAR_DEPENDENCIES], [test x$CIRCULAR_DEPENDENCIES = xyes])
+	AC_MSG_RESULT($CIRCULAR_DEPENDENCIES) 
+
+	dnl }}}
 ])
Index: /issm/branches/trunk-jpl-damage/m4/libtool.m4
===================================================================
--- /issm/branches/trunk-jpl-damage/m4/libtool.m4	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/m4/libtool.m4	(revision 12878)
@@ -2,5 +2,6 @@
 #
 #   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
-#                 2006, 2007, 2008 Free Software Foundation, Inc.
+#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
+#                 Foundation, Inc.
 #   Written by Gordon Matzigkeit, 1996
 #
@@ -11,5 +12,6 @@
 m4_define([_LT_COPYING], [dnl
 #   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
-#                 2006, 2007, 2008 Free Software Foundation, Inc.
+#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
+#                 Foundation, Inc.
 #   Written by Gordon Matzigkeit, 1996
 #
@@ -38,5 +40,5 @@
 ])
 
-# serial 56 LT_INIT
+# serial 57 LT_INIT
 
 
@@ -67,4 +69,5 @@
 AC_DEFUN([LT_INIT],
 [AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT
+AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl
 AC_BEFORE([$0], [LT_LANG])dnl
 AC_BEFORE([$0], [LT_OUTPUT])dnl
@@ -82,4 +85,6 @@
 AC_REQUIRE([LTOBSOLETE_VERSION])dnl
 m4_require([_LT_PROG_LTMAIN])dnl
+
+_LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}])
 
 dnl Parse OPTIONS
@@ -119,5 +124,5 @@
   esac
 done
-cc_basename=`$ECHO "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
 ])
 
@@ -139,4 +144,9 @@
 [AC_REQUIRE([AC_CANONICAL_HOST])dnl
 AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl
+AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl
+
+_LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl
+dnl
 _LT_DECL([], [host_alias], [0], [The host system])dnl
 _LT_DECL([], [host], [0])dnl
@@ -161,8 +171,11 @@
 m4_require([_LT_FILEUTILS_DEFAULTS])dnl
 m4_require([_LT_CHECK_SHELL_FEATURES])dnl
+m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl
 m4_require([_LT_CMD_RELOAD])dnl
 m4_require([_LT_CHECK_MAGIC_METHOD])dnl
+m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl
 m4_require([_LT_CMD_OLD_ARCHIVE])dnl
 m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+m4_require([_LT_WITH_SYSROOT])dnl
 
 _LT_CONFIG_LIBTOOL_INIT([
@@ -180,5 +193,4 @@
 
 m4_require([_LT_TAG_COMPILER])dnl
-_LT_PROG_ECHO_BACKSLASH
 
 case $host_os in
@@ -194,21 +206,4 @@
 esac
 
-# Sed substitution that helps us do robust quoting.  It backslashifies
-# metacharacters that are still active within double-quoted strings.
-sed_quote_subst='s/\([["`$\\]]\)/\\\1/g'
-
-# Same as above, but do not quote variable references.
-double_quote_subst='s/\([["`\\]]\)/\\\1/g'
-
-# Sed substitution to delay expansion of an escaped shell variable in a
-# double_quote_subst'ed string.
-delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
-
-# Sed substitution to delay expansion of an escaped single quote.
-delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
-
-# Sed substitution to avoid accidental globbing in evaled expressions
-no_glob_subst='s/\*/\\\*/g'
-
 # Global variables:
 ofile=libtool
@@ -250,4 +245,26 @@
 ])# _LT_SETUP
 
+
+# _LT_PREPARE_SED_QUOTE_VARS
+# --------------------------
+# Define a few sed substitution that help us do robust quoting.
+m4_defun([_LT_PREPARE_SED_QUOTE_VARS],
+[# Backslashify metacharacters that are still active within
+# double-quoted strings.
+sed_quote_subst='s/\([["`$\\]]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\([["`\\]]\)/\\\1/g'
+
+# Sed substitution to delay expansion of an escaped shell variable in a
+# double_quote_subst'ed string.
+delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
+
+# Sed substitution to delay expansion of an escaped single quote.
+delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
+
+# Sed substitution to avoid accidental globbing in evaled expressions
+no_glob_subst='s/\*/\\\*/g'
+])
 
 # _LT_PROG_LTMAIN
@@ -409,5 +426,5 @@
 # must have a single quote delimited value for this to work.
 m4_define([_LT_CONFIG_STATUS_DECLARE],
-[$1='`$ECHO "X$][$1" | $Xsed -e "$delay_single_quote_subst"`'])
+[$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`'])
 
 
@@ -419,5 +436,5 @@
 # each variable declared with _LT_DECL (and _LT_TAGDECL) into:
 #
-#    <var>='`$ECHO "X$<var>" | $Xsed -e "$delay_single_quote_subst"`'
+#    <var>='`$ECHO "$<var>" | $SED "$delay_single_quote_subst"`'
 m4_defun([_LT_CONFIG_STATUS_DECLARATIONS],
 [m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames),
@@ -518,10 +535,18 @@
 compiler='$compiler_DEFAULT'
 
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+\$[]1
+_LTECHO_EOF'
+}
+
 # Quote evaled strings.
 for var in lt_decl_all_varnames([[ \
 ]], lt_decl_quote_varnames); do
-    case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in
+    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
     *[[\\\\\\\`\\"\\\$]]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
       ;;
     *)
@@ -534,7 +559,7 @@
 for var in lt_decl_all_varnames([[ \
 ]], lt_decl_dquote_varnames); do
-    case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in
+    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
     *[[\\\\\\\`\\"\\\$]]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
       ;;
     *)
@@ -544,14 +569,36 @@
 done
 
-# Fix-up fallback echo if it was mangled by the above quoting rules.
-case \$lt_ECHO in
-*'\\\[$]0 --fallback-echo"')dnl "
-  lt_ECHO=\`\$ECHO "X\$lt_ECHO" | \$Xsed -e 's/\\\\\\\\\\\\\\\[$]0 --fallback-echo"\[$]/\[$]0 --fallback-echo"/'\`
-  ;;
-esac
-
 _LT_OUTPUT_LIBTOOL_INIT
 ])
 
+# _LT_GENERATED_FILE_INIT(FILE, [COMMENT])
+# ------------------------------------
+# Generate a child script FILE with all initialization necessary to
+# reuse the environment learned by the parent script, and make the
+# file executable.  If COMMENT is supplied, it is inserted after the
+# `#!' sequence but before initialization text begins.  After this
+# macro, additional text can be appended to FILE to form the body of
+# the child script.  The macro ends with non-zero status if the
+# file could not be fully written (such as if the disk is full).
+m4_ifdef([AS_INIT_GENERATED],
+[m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])],
+[m4_defun([_LT_GENERATED_FILE_INIT],
+[m4_require([AS_PREPARE])]dnl
+[m4_pushdef([AS_MESSAGE_LOG_FD])]dnl
+[lt_write_fail=0
+cat >$1 <<_ASEOF || lt_write_fail=1
+#! $SHELL
+# Generated by $as_me.
+$2
+SHELL=\${CONFIG_SHELL-$SHELL}
+export SHELL
+_ASEOF
+cat >>$1 <<\_ASEOF || lt_write_fail=1
+AS_SHELL_SANITIZE
+_AS_PREPARE
+exec AS_MESSAGE_FD>&1
+_ASEOF
+test $lt_write_fail = 0 && chmod +x $1[]dnl
+m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT
 
 # LT_OUTPUT
@@ -563,18 +610,9 @@
 [: ${CONFIG_LT=./config.lt}
 AC_MSG_NOTICE([creating $CONFIG_LT])
-cat >"$CONFIG_LT" <<_LTEOF
-#! $SHELL
-# Generated by $as_me.
-# Run this file to recreate a libtool stub with the current configuration.
-
+_LT_GENERATED_FILE_INIT(["$CONFIG_LT"],
+[# Run this file to recreate a libtool stub with the current configuration.])
+
+cat >>"$CONFIG_LT" <<\_LTEOF
 lt_cl_silent=false
-SHELL=\${CONFIG_SHELL-$SHELL}
-_LTEOF
-
-cat >>"$CONFIG_LT" <<\_LTEOF
-AS_SHELL_SANITIZE
-_AS_PREPARE
-
-exec AS_MESSAGE_FD>&1
 exec AS_MESSAGE_LOG_FD>>config.log
 {
@@ -602,5 +640,5 @@
 configured by $[0], generated by m4_PACKAGE_STRING.
 
-Copyright (C) 2008 Free Software Foundation, Inc.
+Copyright (C) 2011 Free Software Foundation, Inc.
 This config.lt script is free software; the Free Software Foundation
 gives unlimited permision to copy, distribute and modify it."
@@ -647,13 +685,11 @@
 # open by configure.  Here we exec the FD to /dev/null, effectively closing
 # config.log, so it can be properly (re)opened and appended to by config.lt.
-if test "$no_create" != yes; then
-  lt_cl_success=:
-  test "$silent" = yes &&
-    lt_config_lt_args="$lt_config_lt_args --quiet"
-  exec AS_MESSAGE_LOG_FD>/dev/null
-  $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false
-  exec AS_MESSAGE_LOG_FD>>config.log
-  $lt_cl_success || AS_EXIT(1)
-fi
+lt_cl_success=:
+test "$silent" = yes &&
+  lt_config_lt_args="$lt_config_lt_args --quiet"
+exec AS_MESSAGE_LOG_FD>/dev/null
+$SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false
+exec AS_MESSAGE_LOG_FD>>config.log
+$lt_cl_success || AS_EXIT(1)
 ])# LT_OUTPUT
 
@@ -718,13 +754,10 @@
   # text mode, it properly converts lines to CR/LF.  This bash problem
   # is reportedly fixed, but why not run on old versions too?
-  sed '/^# Generated shell functions inserted here/q' "$ltmain" >> "$cfgfile" \
-    || (rm -f "$cfgfile"; exit 1)
-
-  _LT_PROG_XSI_SHELLFNS
-
-  sed -n '/^# Generated shell functions inserted here/,$p' "$ltmain" >> "$cfgfile" \
-    || (rm -f "$cfgfile"; exit 1)
-
-  mv -f "$cfgfile" "$ofile" ||
+  sed '$q' "$ltmain" >> "$cfgfile" \
+     || (rm -f "$cfgfile"; exit 1)
+
+  _LT_PROG_REPLACE_SHELLFNS
+
+   mv -f "$cfgfile" "$ofile" ||
     (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
   chmod +x "$ofile"
@@ -771,4 +804,5 @@
   [C],			[_LT_LANG(C)],
   [C++],		[_LT_LANG(CXX)],
+  [Go],			[_LT_LANG(GO)],
   [Java],		[_LT_LANG(GCJ)],
   [Fortran 77],		[_LT_LANG(F77)],
@@ -790,4 +824,29 @@
   _LT_LANG_$1_CONFIG($1)])dnl
 ])# _LT_LANG
+
+
+m4_ifndef([AC_PROG_GO], [
+############################################################
+# NOTE: This macro has been submitted for inclusion into   #
+#  GNU Autoconf as AC_PROG_GO.  When it is available in    #
+#  a released version of Autoconf we should remove this    #
+#  macro and use it instead.                               #
+############################################################
+m4_defun([AC_PROG_GO],
+[AC_LANG_PUSH(Go)dnl
+AC_ARG_VAR([GOC],     [Go compiler command])dnl
+AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl
+_AC_ARG_VAR_LDFLAGS()dnl
+AC_CHECK_TOOL(GOC, gccgo)
+if test -z "$GOC"; then
+  if test -n "$ac_tool_prefix"; then
+    AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo])
+  fi
+fi
+if test -z "$GOC"; then
+  AC_CHECK_PROG(GOC, gccgo, gccgo, false)
+fi
+])#m4_defun
+])#m4_ifndef
 
 
@@ -822,4 +881,8 @@
 	[m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])])
 
+AC_PROVIDE_IFELSE([AC_PROG_GO],
+  [LT_LANG(GO)],
+  [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])])
+
 AC_PROVIDE_IFELSE([LT_PROG_RC],
   [LT_LANG(RC)],
@@ -832,4 +895,5 @@
 AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)])
 AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)])
+AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)])
 dnl aclocal-1.4 backwards compatibility:
 dnl AC_DEFUN([AC_LIBTOOL_CXX], [])
@@ -837,4 +901,5 @@
 dnl AC_DEFUN([AC_LIBTOOL_FC], [])
 dnl AC_DEFUN([AC_LIBTOOL_GCJ], [])
+dnl AC_DEFUN([AC_LIBTOOL_RC], [])
 
 
@@ -922,5 +987,11 @@
 	  -dynamiclib -Wl,-single_module conftest.c 2>conftest.err
         _lt_result=$?
-	if test -f libconftest.dylib && test ! -s conftest.err && test $_lt_result = 0; then
+	# If there is a non-empty error log, and "single_module"
+	# appears in it, assume the flag caused a linker warning
+        if test -s conftest.err && $GREP single_module conftest.err; then
+	  cat conftest.err >&AS_MESSAGE_LOG_FD
+	# Otherwise, if the output was created with a 0 exit code from
+	# the compiler, it worked.
+	elif test -f libconftest.dylib && test $_lt_result -eq 0; then
 	  lt_cv_apple_cc_single_mod=yes
 	else
@@ -930,4 +1001,5 @@
 	rm -f conftest.*
       fi])
+
     AC_CACHE_CHECK([for -exported_symbols_list linker flag],
       [lt_cv_ld_exported_symbols_list],
@@ -940,4 +1012,32 @@
 	[lt_cv_ld_exported_symbols_list=no])
 	LDFLAGS="$save_LDFLAGS"
+    ])
+
+    AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load],
+      [lt_cv_ld_force_load=no
+      cat > conftest.c << _LT_EOF
+int forced_loaded() { return 2;}
+_LT_EOF
+      echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD
+      $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD
+      echo "$AR cru libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD
+      $AR cru libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD
+      echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD
+      $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD
+      cat > conftest.c << _LT_EOF
+int main() { return 0;}
+_LT_EOF
+      echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD
+      $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err
+      _lt_result=$?
+      if test -s conftest.err && $GREP force_load conftest.err; then
+	cat conftest.err >&AS_MESSAGE_LOG_FD
+      elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then
+	lt_cv_ld_force_load=yes
+      else
+	cat conftest.err >&AS_MESSAGE_LOG_FD
+      fi
+        rm -f conftest.err libconftest.a conftest conftest.c
+        rm -rf conftest.dSYM
     ])
     case $host_os in
@@ -968,5 +1068,5 @@
       _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
     fi
-    if test "$DSYMUTIL" != ":"; then
+    if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then
       _lt_dsymutil='~$DSYMUTIL $lib || :'
     else
@@ -978,6 +1078,6 @@
 
 
-# _LT_DARWIN_LINKER_FEATURES
-# --------------------------
+# _LT_DARWIN_LINKER_FEATURES([TAG])
+# ---------------------------------
 # Checks for linker and compiler features on darwin
 m4_defun([_LT_DARWIN_LINKER_FEATURES],
@@ -988,5 +1088,11 @@
   _LT_TAGVAR(hardcode_automatic, $1)=yes
   _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
-  _LT_TAGVAR(whole_archive_flag_spec, $1)=''
+  if test "$lt_cv_ld_force_load" = "yes"; then
+    _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
+    m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes],
+                  [FC],  [_LT_TAGVAR(compiler_needs_object, $1)=yes])
+  else
+    _LT_TAGVAR(whole_archive_flag_spec, $1)=''
+  fi
   _LT_TAGVAR(link_all_deplibs, $1)=yes
   _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined"
@@ -996,5 +1102,5 @@
   esac
   if test "$_lt_dar_can_shared" = "yes"; then
-    output_verbose_link_cmd=echo
+    output_verbose_link_cmd=func_echo_all
     _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
     _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
@@ -1012,6 +1118,6 @@
 ])
 
-# _LT_SYS_MODULE_PATH_AIX
-# -----------------------
+# _LT_SYS_MODULE_PATH_AIX([TAGNAME])
+# ----------------------------------
 # Links a minimal program and checks the executable
 # for the system default hardcoded library path. In most cases,
@@ -1020,20 +1126,31 @@
 # If we don't find anything, use the default library path according
 # to the aix ld manual.
+# Store the results from the different compilers for each TAGNAME.
+# Allow to override them for all tags through lt_cv_aix_libpath.
 m4_defun([_LT_SYS_MODULE_PATH_AIX],
 [m4_require([_LT_DECL_SED])dnl
-AC_LINK_IFELSE(AC_LANG_PROGRAM,[
-lt_aix_libpath_sed='
-    /Import File Strings/,/^$/ {
-	/^0/ {
-	    s/^0  *\(.*\)$/\1/
-	    p
-	}
-    }'
-aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
-# Check for a 64-bit object if we didn't find anything.
-if test -z "$aix_libpath"; then
-  aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
-fi],[])
-if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+if test "${lt_cv_aix_libpath+set}" = set; then
+  aix_libpath=$lt_cv_aix_libpath
+else
+  AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])],
+  [AC_LINK_IFELSE([AC_LANG_PROGRAM],[
+  lt_aix_libpath_sed='[
+      /Import File Strings/,/^$/ {
+	  /^0/ {
+	      s/^0  *\([^ ]*\) *$/\1/
+	      p
+	  }
+      }]'
+  _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  # Check for a 64-bit object if we didn't find anything.
+  if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
+    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+  fi],[])
+  if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
+    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])="/usr/lib:/lib"
+  fi
+  ])
+  aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])
+fi
 ])# _LT_SYS_MODULE_PATH_AIX
 
@@ -1042,170 +1159,98 @@
 # -------------------
 m4_define([_LT_SHELL_INIT],
-[ifdef([AC_DIVERSION_NOTICE],
-	     [AC_DIVERT_PUSH(AC_DIVERSION_NOTICE)],
-	 [AC_DIVERT_PUSH(NOTICE)])
-$1
-AC_DIVERT_POP
-])# _LT_SHELL_INIT
+[m4_divert_text([M4SH-INIT], [$1
+])])# _LT_SHELL_INIT
+
 
 
 # _LT_PROG_ECHO_BACKSLASH
 # -----------------------
-# Add some code to the start of the generated configure script which
-# will find an echo command which doesn't interpret backslashes.
+# Find how we can fake an echo command that does not interpret backslash.
+# In particular, with Autoconf 2.60 or later we add some code to the start
+# of the generated configure script which will find a shell with a builtin
+# printf (which we can use as an echo command).
 m4_defun([_LT_PROG_ECHO_BACKSLASH],
-[_LT_SHELL_INIT([
-# Check that we are running under the correct shell.
-SHELL=${CONFIG_SHELL-/bin/sh}
-
-case X$lt_ECHO in
-X*--fallback-echo)
-  # Remove one level of quotation (which was required for Make).
-  ECHO=`echo "$lt_ECHO" | sed 's,\\\\\[$]\\[$]0,'[$]0','`
-  ;;
+[ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
+ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
+
+AC_MSG_CHECKING([how to print strings])
+# Test print first, because it will be a builtin if present.
+if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \
+   test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then
+  ECHO='print -r --'
+elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then
+  ECHO='printf %s\n'
+else
+  # Use this function as a fallback that always works.
+  func_fallback_echo ()
+  {
+    eval 'cat <<_LTECHO_EOF
+$[]1
+_LTECHO_EOF'
+  }
+  ECHO='func_fallback_echo'
+fi
+
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO "$*" 
+}
+
+case "$ECHO" in
+  printf*) AC_MSG_RESULT([printf]) ;;
+  print*) AC_MSG_RESULT([print -r]) ;;
+  *) AC_MSG_RESULT([cat]) ;;
 esac
 
-ECHO=${lt_ECHO-echo}
-if test "X[$]1" = X--no-reexec; then
-  # Discard the --no-reexec flag, and continue.
-  shift
-elif test "X[$]1" = X--fallback-echo; then
-  # Avoid inline document here, it may be left over
-  :
-elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' ; then
-  # Yippee, $ECHO works!
-  :
-else
-  # Restart under the correct shell.
-  exec $SHELL "[$]0" --no-reexec ${1+"[$]@"}
-fi
-
-if test "X[$]1" = X--fallback-echo; then
-  # used as fallback echo
-  shift
-  cat <<_LT_EOF
-[$]*
-_LT_EOF
-  exit 0
-fi
-
-# The HP-UX ksh and POSIX shell print the target directory to stdout
-# if CDPATH is set.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-if test -z "$lt_ECHO"; then
-  if test "X${echo_test_string+set}" != Xset; then
-    # find a string as large as possible, as long as the shell can cope with it
-    for cmd in 'sed 50q "[$]0"' 'sed 20q "[$]0"' 'sed 10q "[$]0"' 'sed 2q "[$]0"' 'echo test'; do
-      # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ...
-      if { echo_test_string=`eval $cmd`; } 2>/dev/null &&
-	 { test "X$echo_test_string" = "X$echo_test_string"; } 2>/dev/null
-      then
-        break
-      fi
-    done
-  fi
-
-  if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' &&
-     echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` &&
-     test "X$echo_testing_string" = "X$echo_test_string"; then
-    :
-  else
-    # The Solaris, AIX, and Digital Unix default echo programs unquote
-    # backslashes.  This makes it impossible to quote backslashes using
-    #   echo "$something" | sed 's/\\/\\\\/g'
-    #
-    # So, first we look for a working echo in the user's PATH.
-
-    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-    for dir in $PATH /usr/ucb; do
-      IFS="$lt_save_ifs"
-      if (test -f $dir/echo || test -f $dir/echo$ac_exeext) &&
-         test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' &&
-         echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` &&
-         test "X$echo_testing_string" = "X$echo_test_string"; then
-        ECHO="$dir/echo"
-        break
-      fi
-    done
-    IFS="$lt_save_ifs"
-
-    if test "X$ECHO" = Xecho; then
-      # We didn't find a better echo, so look for alternatives.
-      if test "X`{ print -r '\t'; } 2>/dev/null`" = 'X\t' &&
-         echo_testing_string=`{ print -r "$echo_test_string"; } 2>/dev/null` &&
-         test "X$echo_testing_string" = "X$echo_test_string"; then
-        # This shell has a builtin print -r that does the trick.
-        ECHO='print -r'
-      elif { test -f /bin/ksh || test -f /bin/ksh$ac_exeext; } &&
-	   test "X$CONFIG_SHELL" != X/bin/ksh; then
-        # If we have ksh, try running configure again with it.
-        ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh}
-        export ORIGINAL_CONFIG_SHELL
-        CONFIG_SHELL=/bin/ksh
-        export CONFIG_SHELL
-        exec $CONFIG_SHELL "[$]0" --no-reexec ${1+"[$]@"}
-      else
-        # Try using printf.
-        ECHO='printf %s\n'
-        if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' &&
-	   echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` &&
-	   test "X$echo_testing_string" = "X$echo_test_string"; then
-	  # Cool, printf works
-	  :
-        elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` &&
-	     test "X$echo_testing_string" = 'X\t' &&
-	     echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
-	     test "X$echo_testing_string" = "X$echo_test_string"; then
-	  CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL
-	  export CONFIG_SHELL
-	  SHELL="$CONFIG_SHELL"
-	  export SHELL
-	  ECHO="$CONFIG_SHELL [$]0 --fallback-echo"
-        elif echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` &&
-	     test "X$echo_testing_string" = 'X\t' &&
-	     echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
-	     test "X$echo_testing_string" = "X$echo_test_string"; then
-	  ECHO="$CONFIG_SHELL [$]0 --fallback-echo"
-        else
-	  # maybe with a smaller string...
-	  prev=:
-
-	  for cmd in 'echo test' 'sed 2q "[$]0"' 'sed 10q "[$]0"' 'sed 20q "[$]0"' 'sed 50q "[$]0"'; do
-	    if { test "X$echo_test_string" = "X`eval $cmd`"; } 2>/dev/null
-	    then
-	      break
-	    fi
-	    prev="$cmd"
-	  done
-
-	  if test "$prev" != 'sed 50q "[$]0"'; then
-	    echo_test_string=`eval $prev`
-	    export echo_test_string
-	    exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "[$]0" ${1+"[$]@"}
-	  else
-	    # Oops.  We lost completely, so just stick with echo.
-	    ECHO=echo
-	  fi
-        fi
-      fi
-    fi
-  fi
-fi
-
-# Copy echo and quote the copy suitably for passing to libtool from
-# the Makefile, instead of quoting the original, which is used later.
-lt_ECHO=$ECHO
-if test "X$lt_ECHO" = "X$CONFIG_SHELL [$]0 --fallback-echo"; then
-   lt_ECHO="$CONFIG_SHELL \\\$\[$]0 --fallback-echo"
-fi
-
-AC_SUBST(lt_ECHO)
-])
+m4_ifdef([_AS_DETECT_SUGGESTED],
+[_AS_DETECT_SUGGESTED([
+  test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || (
+    ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+    ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
+    ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
+    PATH=/empty FPATH=/empty; export PATH FPATH
+    test "X`printf %s $ECHO`" = "X$ECHO" \
+      || test "X`print -r -- $ECHO`" = "X$ECHO" )])])
+
 _LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts])
-_LT_DECL([], [ECHO], [1],
-    [An echo program that does not interpret backslashes])
+_LT_DECL([], [ECHO], [1], [An echo program that protects backslashes])
 ])# _LT_PROG_ECHO_BACKSLASH
 
+
+# _LT_WITH_SYSROOT
+# ----------------
+AC_DEFUN([_LT_WITH_SYSROOT],
+[AC_MSG_CHECKING([for sysroot])
+AC_ARG_WITH([sysroot],
+[  --with-sysroot[=DIR] Search for dependent libraries within DIR
+                        (or the compiler's sysroot if not specified).],
+[], [with_sysroot=no])
+
+dnl lt_sysroot will always be passed unquoted.  We quote it here
+dnl in case the user passed a directory name.
+lt_sysroot=
+case ${with_sysroot} in #(
+ yes)
+   if test "$GCC" = yes; then
+     lt_sysroot=`$CC --print-sysroot 2>/dev/null`
+   fi
+   ;; #(
+ /*)
+   lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"`
+   ;; #(
+ no|'')
+   ;; #(
+ *)
+   AC_MSG_RESULT([${with_sysroot}])
+   AC_MSG_ERROR([The sysroot must be an absolute path.])
+   ;;
+esac
+
+ AC_MSG_RESULT([${lt_sysroot:-no}])
+_LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl
+[dependent libraries, and in which our libraries should be installed.])])
 
 # _LT_ENABLE_LOCK
@@ -1237,5 +1282,5 @@
 *-*-irix6*)
   # Find out which ABI we are using.
-  echo '[#]line __oline__ "configure"' > conftest.$ac_ext
+  echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext
   if AC_TRY_EVAL(ac_compile); then
     if test "$lt_cv_prog_gnu_ld" = yes; then
@@ -1330,5 +1375,5 @@
   fi
   ;;
-sparc*-*solaris*)
+*-*solaris*)
   # Find out which ABI we are using.
   echo 'int i;' > conftest.$ac_ext
@@ -1337,5 +1382,18 @@
     *64-bit*)
       case $lt_cv_prog_gnu_ld in
-      yes*) LD="${LD-ld} -m elf64_sparc" ;;
+      yes*)
+        case $host in
+        i?86-*-solaris*)
+          LD="${LD-ld} -m elf_x86_64"
+          ;;
+        sparc*-*-solaris*)
+          LD="${LD-ld} -m elf64_sparc"
+          ;;
+        esac
+        # GNU ld 2.21 introduced _sol2 emulations.  Use them if available.
+        if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then
+          LD="${LD-ld}_sol2"
+        fi
+        ;;
       *)
 	if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
@@ -1355,12 +1413,45 @@
 
 
+# _LT_PROG_AR
+# -----------
+m4_defun([_LT_PROG_AR],
+[AC_CHECK_TOOLS(AR, [ar], false)
+: ${AR=ar}
+: ${AR_FLAGS=cru}
+_LT_DECL([], [AR], [1], [The archiver])
+_LT_DECL([], [AR_FLAGS], [1], [Flags to create an archive])
+
+AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file],
+  [lt_cv_ar_at_file=no
+   AC_COMPILE_IFELSE([AC_LANG_PROGRAM],
+     [echo conftest.$ac_objext > conftest.lst
+      lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD'
+      AC_TRY_EVAL([lt_ar_try])
+      if test "$ac_status" -eq 0; then
+	# Ensure the archiver fails upon bogus file names.
+	rm -f conftest.$ac_objext libconftest.a
+	AC_TRY_EVAL([lt_ar_try])
+	if test "$ac_status" -ne 0; then
+          lt_cv_ar_at_file=@
+        fi
+      fi
+      rm -f conftest.* libconftest.a
+     ])
+  ])
+
+if test "x$lt_cv_ar_at_file" = xno; then
+  archiver_list_spec=
+else
+  archiver_list_spec=$lt_cv_ar_at_file
+fi
+_LT_DECL([], [archiver_list_spec], [1],
+  [How to feed a file listing to the archiver])
+])# _LT_PROG_AR
+
+
 # _LT_CMD_OLD_ARCHIVE
 # -------------------
 m4_defun([_LT_CMD_OLD_ARCHIVE],
-[AC_CHECK_TOOL(AR, ar, false)
-test -z "$AR" && AR=ar
-test -z "$AR_FLAGS" && AR_FLAGS=cru
-_LT_DECL([], [AR], [1], [The archiver])
-_LT_DECL([], [AR_FLAGS], [1])
+[_LT_PROG_AR
 
 AC_CHECK_TOOL(STRIP, strip, :)
@@ -1381,16 +1472,25 @@
   case $host_os in
   openbsd*)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib"
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib"
     ;;
   *)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib"
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib"
     ;;
   esac
-  old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib"
+  old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib"
 fi
+
+case $host_os in
+  darwin*)
+    lock_old_archive_extraction=yes ;;
+  *)
+    lock_old_archive_extraction=no ;;
+esac
 _LT_DECL([], [old_postinstall_cmds], [2])
 _LT_DECL([], [old_postuninstall_cmds], [2])
 _LT_TAGDECL([], [old_archive_cmds], [2],
     [Commands used to build an old-style archive])
+_LT_DECL([], [lock_old_archive_extraction], [0],
+    [Whether to use a lock for old archive extraction])
 ])# _LT_CMD_OLD_ARCHIVE
 
@@ -1417,13 +1517,13 @@
    -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=$?
    cat conftest.err >&AS_MESSAGE_LOG_FD
-   echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings other than the usual output.
-     $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
      $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
      if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
@@ -1465,5 +1565,5 @@
        # Append any errors to the config.log.
        cat conftest.err 1>&AS_MESSAGE_LOG_FD
-       $ECHO "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
+       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
        $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
        if diff conftest.exp conftest.er2 >/dev/null; then
@@ -1525,4 +1625,9 @@
     # Instead, let's just punt: use the minimum linelength reported by
     # all of the supported platforms: 8192 (on NT/2K/XP).
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  mint*)
+    # On MiNT this can take a long time and run out of memory.
     lt_cv_sys_max_cmd_len=8192;
     ;;
@@ -1551,4 +1656,9 @@
     # We know the value 262144 and hardcode it with a safety zone (like BSD)
     lt_cv_sys_max_cmd_len=196608
+    ;;
+
+  os2*)
+    # The test takes a long time on OS/2.
+    lt_cv_sys_max_cmd_len=8192
     ;;
 
@@ -1592,6 +1702,6 @@
       # maximum length that is only half of the actual maximum length, but
       # we can't tell.
-      while { test "X"`$SHELL [$]0 --fallback-echo "X$teststring$teststring" 2>/dev/null` \
-	         = "XX$teststring$teststring"; } >/dev/null 2>&1 &&
+      while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \
+	         = "X$teststring$teststring"; } >/dev/null 2>&1 &&
 	      test $i != 17 # 1/2 MB should be enough
       do
@@ -1644,5 +1754,5 @@
   lt_status=$lt_dlunknown
   cat > conftest.$ac_ext <<_LT_EOF
-[#line __oline__ "configure"
+[#line $LINENO "configure"
 #include "confdefs.h"
 
@@ -1685,5 +1795,11 @@
 #endif
 
-void fnord() { int i=42;}
+/* When -fvisbility=hidden is used, assume the code has been annotated
+   correspondingly for the symbols needed.  */
+#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
+int fnord () __attribute__((visibility("default")));
+#endif
+
+int fnord () { return 42; }
 int main ()
 {
@@ -1694,5 +1810,9 @@
     {
       if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
-      else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
+      else
+        {
+	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
+          else puts (dlerror ());
+	}
       /* dlclose (self); */
     }
@@ -1870,14 +1990,14 @@
    -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
    (eval "$lt_compile" 2>out/conftest.err)
    ac_status=$?
    cat out/conftest.err >&AS_MESSAGE_LOG_FD
-   echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
    if (exit $ac_status) && test -s out/conftest2.$ac_objext
    then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings
-     $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
      $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
      if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
@@ -2038,4 +2158,5 @@
 m4_require([_LT_DECL_OBJDUMP])dnl
 m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_CHECK_SHELL_FEATURES])dnl
 AC_MSG_CHECKING([dynamic linker characteristics])
 m4_if([$1],
@@ -2046,14 +2167,21 @@
     *) lt_awk_arg="/^libraries:/" ;;
   esac
-  lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e "s,=/,/,g"`
-  if $ECHO "$lt_search_path_spec" | $GREP ';' >/dev/null ; then
+  case $host_os in
+    mingw* | cegcc*) lt_sed_strip_eq="s,=\([[A-Za-z]]:\),\1,g" ;;
+    *) lt_sed_strip_eq="s,=/,/,g" ;;
+  esac
+  lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq`
+  case $lt_search_path_spec in
+  *\;*)
     # if the path contains ";" then we assume it to be the separator
     # otherwise default to the standard path separator (i.e. ":") - it is
     # assumed that no part of a normal pathname contains ";" but that should
     # okay in the real world where ";" in dirpaths is itself problematic.
-    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED -e 's/;/ /g'`
-  else
-    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED  -e "s/$PATH_SEPARATOR/ /g"`
-  fi
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'`
+    ;;
+  *)
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"`
+    ;;
+  esac
   # Ok, now we have the path, separated by spaces, we can step through it
   # and add multilib dir if necessary.
@@ -2068,5 +2196,5 @@
     fi
   done
-  lt_search_path_spec=`$ECHO $lt_tmp_lt_search_path_spec | awk '
+  lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk '
 BEGIN {RS=" "; FS="/|\n";} {
   lt_foo="";
@@ -2088,5 +2216,11 @@
   if (lt_freq[[lt_foo]] == 1) { print lt_foo; }
 }'`
-  sys_lib_search_path_spec=`$ECHO $lt_search_path_spec`
+  # AWK program above erroneously prepends '/' to C:/dos/paths
+  # for these hosts.
+  case $host_os in
+    mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\
+      $SED 's,/\([[A-Za-z]]:\),\1,g'` ;;
+  esac
+  sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP`
 else
   sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
@@ -2114,5 +2248,5 @@
 case $host_os in
 aix3*)
-  version_type=linux
+  version_type=linux # correct to gnu/linux during the next big refactor
   library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
   shlibpath_var=LIBPATH
@@ -2123,5 +2257,5 @@
 
 aix[[4-9]]*)
-  version_type=linux
+  version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
@@ -2176,5 +2310,5 @@
     library_names_spec='$libname.ixlibrary $libname.a'
     # Create ${libname}_ixlibrary.a entries in /sys/libs.
-    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$ECHO "X$lib" | $Xsed -e '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
     ;;
   esac
@@ -2188,5 +2322,5 @@
 
 bsdi[[45]]*)
-  version_type=linux
+  version_type=linux # correct to gnu/linux during the next big refactor
   need_version=no
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
@@ -2207,6 +2341,7 @@
   need_lib_prefix=no
 
-  case $GCC,$host_os in
-  yes,cygwin* | yes,mingw* | yes,pw32* | yes,cegcc*)
+  case $GCC,$cc_basename in
+  yes,*)
+    # gcc
     library_names_spec='$libname.dll.a'
     # DLL is installed to $(libdir)/../bin by postinstall_cmds
@@ -2229,21 +2364,10 @@
       # Cygwin DLLs use 'cyg' prefix rather than 'lib'
       soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-      sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
+m4_if([$1], [],[
+      sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"])
       ;;
     mingw* | cegcc*)
       # MinGW DLLs use traditional 'lib' prefix
       soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-      sys_lib_search_path_spec=`$CC -print-search-dirs | $GREP "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
-      if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then
-        # It is most probably a Windows format PATH printed by
-        # mingw gcc, but we are running on Cygwin. Gcc prints its search
-        # path with ; separators, and with drive letters. We can handle the
-        # drive letters (cygwin fileutils understands them), so leave them,
-        # especially as we might pass files found there to a mingw objdump,
-        # which wouldn't understand a cygwinified path. Ahh.
-        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
-      else
-        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED  -e "s/$PATH_SEPARATOR/ /g"`
-      fi
       ;;
     pw32*)
@@ -2252,11 +2376,69 @@
       ;;
     esac
+    dynamic_linker='Win32 ld.exe'
     ;;
 
+  *,cl*)
+    # Native MSVC
+    libname_spec='$name'
+    soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+    library_names_spec='${libname}.dll.lib'
+
+    case $build_os in
+    mingw*)
+      sys_lib_search_path_spec=
+      lt_save_ifs=$IFS
+      IFS=';'
+      for lt_path in $LIB
+      do
+        IFS=$lt_save_ifs
+        # Let DOS variable expansion print the short 8.3 style file name.
+        lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"`
+        sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path"
+      done
+      IFS=$lt_save_ifs
+      # Convert to MSYS style.
+      sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'`
+      ;;
+    cygwin*)
+      # Convert to unix form, then to dos form, then back to unix form
+      # but this time dos style (no spaces!) so that the unix form looks
+      # like /cygdrive/c/PROGRA~1:/cygdr...
+      sys_lib_search_path_spec=`cygpath --path --unix "$LIB"`
+      sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null`
+      sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      ;;
+    *)
+      sys_lib_search_path_spec="$LIB"
+      if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then
+        # It is most probably a Windows format PATH.
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+      else
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      fi
+      # FIXME: find the short name or the path components, as spaces are
+      # common. (e.g. "Program Files" -> "PROGRA~1")
+      ;;
+    esac
+
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+    dynamic_linker='Win32 link.exe'
+    ;;
+
   *)
+    # Assume MSVC wrapper
     library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
+    dynamic_linker='Win32 ld.exe'
     ;;
   esac
-  dynamic_linker='Win32 ld.exe'
   # FIXME: first we should search . and the directory the executable is in
   shlibpath_var=PATH
@@ -2279,5 +2461,5 @@
 
 dgux*)
-  version_type=linux
+  version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
@@ -2285,8 +2467,4 @@
   soname_spec='${libname}${release}${shared_ext}$major'
   shlibpath_var=LD_LIBRARY_PATH
-  ;;
-
-freebsd1*)
-  dynamic_linker=no
   ;;
 
@@ -2298,5 +2476,5 @@
   else
     case $host_os in
-    freebsd[[123]]*) objformat=aout ;;
+    freebsd[[23]].*) objformat=aout ;;
     *) objformat=elf ;;
     esac
@@ -2316,5 +2494,5 @@
   shlibpath_var=LD_LIBRARY_PATH
   case $host_os in
-  freebsd2*)
+  freebsd2.*)
     shlibpath_overrides_runpath=yes
     ;;
@@ -2336,5 +2514,5 @@
 
 gnu*)
-  version_type=linux
+  version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
@@ -2342,4 +2520,18 @@
   soname_spec='${libname}${release}${shared_ext}$major'
   shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+haiku*)
+  version_type=linux # correct to gnu/linux during the next big refactor
+  need_lib_prefix=no
+  need_version=no
+  dynamic_linker="$host_os runtime_loader"
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
   hardcode_into_libs=yes
   ;;
@@ -2387,10 +2579,12 @@
     ;;
   esac
-  # HP-UX runs *really* slowly unless shared libraries are mode 555.
+  # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
   postinstall_cmds='chmod 555 $lib'
+  # or fails outright, so override atomically:
+  install_override_mode=555
   ;;
 
 interix[[3-9]]*)
-  version_type=linux
+  version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
@@ -2408,5 +2602,5 @@
     *)
 	if test "$lt_cv_prog_gnu_ld" = yes; then
-		version_type=linux
+		version_type=linux # correct to gnu/linux during the next big refactor
 	else
 		version_type=irix
@@ -2445,7 +2639,7 @@
   ;;
 
-# This must be Linux ELF.
-linux* | k*bsd*-gnu)
-  version_type=linux
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
@@ -2455,14 +2649,19 @@
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=no
+
   # Some binutils ld are patched to set DT_RUNPATH
-  save_LDFLAGS=$LDFLAGS
-  save_libdir=$libdir
-  eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \
-       LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\""
-  AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
-    [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null],
-       [shlibpath_overrides_runpath=yes])])
-  LDFLAGS=$save_LDFLAGS
-  libdir=$save_libdir
+  AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath],
+    [lt_cv_shlibpath_overrides_runpath=no
+    save_LDFLAGS=$LDFLAGS
+    save_libdir=$libdir
+    eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \
+	 LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\""
+    AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+      [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null],
+	 [lt_cv_shlibpath_overrides_runpath=yes])])
+    LDFLAGS=$save_LDFLAGS
+    libdir=$save_libdir
+    ])
+  shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath
 
   # This implies no fast_install, which is unacceptable.
@@ -2473,5 +2672,5 @@
   # Append ld.so.conf contents to the search path
   if test -f /etc/ld.so.conf; then
-    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
     sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
   fi
@@ -2505,5 +2704,5 @@
 
 newsos6)
-  version_type=linux
+  version_type=linux # correct to gnu/linux during the next big refactor
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
   shlibpath_var=LD_LIBRARY_PATH
@@ -2574,5 +2773,5 @@
 
 solaris*)
-  version_type=linux
+  version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
@@ -2599,5 +2798,5 @@
 
 sysv4 | sysv4.3*)
-  version_type=linux
+  version_type=linux # correct to gnu/linux during the next big refactor
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
   soname_spec='${libname}${release}${shared_ext}$major'
@@ -2623,5 +2822,5 @@
 sysv4*MP*)
   if test -d /usr/nec ;then
-    version_type=linux
+    version_type=linux # correct to gnu/linux during the next big refactor
     library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
     soname_spec='$libname${shared_ext}.$major'
@@ -2654,5 +2853,5 @@
 tpf*)
   # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
-  version_type=linux
+  version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
@@ -2664,5 +2863,5 @@
 
 uts4*)
-  version_type=linux
+  version_type=linux # correct to gnu/linux during the next big refactor
   library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
   soname_spec='${libname}${release}${shared_ext}$major'
@@ -2706,4 +2905,6 @@
 _LT_DECL([], [soname_spec], [1],
     [[The coded name of the library, if different from the real name]])
+_LT_DECL([], [install_override_mode], [1],
+    [Permission mode override for installation of shared libraries])
 _LT_DECL([], [postinstall_cmds], [2],
     [Command to use after installation of a shared archive])
@@ -2818,4 +3019,5 @@
 m4_require([_LT_DECL_SED])dnl
 m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_PROG_ECHO_BACKSLASH])dnl
 
 AC_ARG_WITH([gnu-ld],
@@ -2939,4 +3141,9 @@
 reload_cmds='$LD$reload_flag -o $output$reload_objs'
 case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    if test "$GCC" != yes; then
+      reload_cmds=false
+    fi
+    ;;
   darwin*)
     if test "$GCC" = yes; then
@@ -2947,6 +3154,6 @@
     ;;
 esac
-_LT_DECL([], [reload_flag], [1], [How to create reloadable object files])dnl
-_LT_DECL([], [reload_cmds], [2])dnl
+_LT_TAGDECL([], [reload_flag], [1], [How to create reloadable object files])dnl
+_LT_TAGDECL([], [reload_cmds], [2])dnl
 ])# _LT_CMD_RELOAD
 
@@ -3000,14 +3207,16 @@
   # func_win32_libid shell function, so use a weaker test based on 'objdump',
   # unless we find 'file', for example because we are cross-compiling.
-  if ( file / ) >/dev/null 2>&1; then
+  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
+  if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then
     lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
     lt_cv_file_magic_cmd='func_win32_libid'
   else
-    lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?'
+    # Keep this pattern in sync with the one in func_win32_libid.
+    lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)'
     lt_cv_file_magic_cmd='$OBJDUMP -f'
   fi
   ;;
 
-cegcc)
+cegcc*)
   # use the weaker test based on 'objdump'. See mingw*.
   lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
@@ -3039,4 +3248,8 @@
   ;;
 
+haiku*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
 hpux10.20* | hpux11*)
   lt_cv_file_magic_cmd=/usr/bin/file
@@ -3047,9 +3260,9 @@
     ;;
   hppa*64*)
-    [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]']
+    [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]']
     lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
     ;;
   *)
-    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]].[[0-9]]) shared library'
+    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library'
     lt_cv_file_magic_test_file=/usr/lib/libc.sl
     ;;
@@ -3072,6 +3285,6 @@
   ;;
 
-# This must be Linux ELF.
-linux* | k*bsd*-gnu)
+# This must be glibc/ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
   lt_cv_deplibs_check_method=pass_all
   ;;
@@ -3151,4 +3364,19 @@
 esac
 ])
+
+file_magic_glob=
+want_nocaseglob=no
+if test "$build" = "$host"; then
+  case $host_os in
+  mingw* | pw32*)
+    if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then
+      want_nocaseglob=yes
+    else
+      file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"`
+    fi
+    ;;
+  esac
+fi
+
 file_magic_cmd=$lt_cv_file_magic_cmd
 deplibs_check_method=$lt_cv_deplibs_check_method
@@ -3158,5 +3386,9 @@
     [Method to check whether dependent libraries are shared objects])
 _LT_DECL([], [file_magic_cmd], [1],
-    [Command to use when deplibs_check_method == "file_magic"])
+    [Command to use when deplibs_check_method = "file_magic"])
+_LT_DECL([], [file_magic_glob], [1],
+    [How to find potential files when deplibs_check_method = "file_magic"])
+_LT_DECL([], [want_nocaseglob], [1],
+    [Find potential files using nocaseglob when deplibs_check_method = "file_magic"])
 ])# _LT_CHECK_MAGIC_METHOD
 
@@ -3215,5 +3447,17 @@
 else
   # Didn't find any BSD compatible name lister, look for dumpbin.
-  AC_CHECK_TOOLS(DUMPBIN, ["dumpbin -symbols" "link -dump -symbols"], :)
+  if test -n "$DUMPBIN"; then :
+    # Let the user override the test.
+  else
+    AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :)
+    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
+    *COFF*)
+      DUMPBIN="$DUMPBIN -symbols"
+      ;;
+    *)
+      DUMPBIN=:
+      ;;
+    esac
+  fi
   AC_SUBST([DUMPBIN])
   if test "$DUMPBIN" != ":"; then
@@ -3228,11 +3472,11 @@
   [lt_cv_nm_interface="BSD nm"
   echo "int some_variable = 0;" > conftest.$ac_ext
-  (eval echo "\"\$as_me:__oline__: $ac_compile\"" >&AS_MESSAGE_LOG_FD)
+  (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD)
   (eval "$ac_compile" 2>conftest.err)
   cat conftest.err >&AS_MESSAGE_LOG_FD
-  (eval echo "\"\$as_me:__oline__: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD)
+  (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD)
   (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
   cat conftest.err >&AS_MESSAGE_LOG_FD
-  (eval echo "\"\$as_me:__oline__: output\"" >&AS_MESSAGE_LOG_FD)
+  (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD)
   cat conftest.out >&AS_MESSAGE_LOG_FD
   if $GREP 'External.*some_variable' conftest.out > /dev/null; then
@@ -3248,4 +3492,65 @@
 dnl AC_DEFUN([AM_PROG_NM], [])
 dnl AC_DEFUN([AC_PROG_NM], [])
+
+# _LT_CHECK_SHAREDLIB_FROM_LINKLIB
+# --------------------------------
+# how to determine the name of the shared library
+# associated with a specific link library.
+#  -- PORTME fill in with the dynamic library characteristics
+m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB],
+[m4_require([_LT_DECL_EGREP])
+m4_require([_LT_DECL_OBJDUMP])
+m4_require([_LT_DECL_DLLTOOL])
+AC_CACHE_CHECK([how to associate runtime and link libraries],
+lt_cv_sharedlib_from_linklib_cmd,
+[lt_cv_sharedlib_from_linklib_cmd='unknown'
+
+case $host_os in
+cygwin* | mingw* | pw32* | cegcc*)
+  # two different shell functions defined in ltmain.sh
+  # decide which to use based on capabilities of $DLLTOOL
+  case `$DLLTOOL --help 2>&1` in
+  *--identify-strict*)
+    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib
+    ;;
+  *)
+    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback
+    ;;
+  esac
+  ;;
+*)
+  # fallback: assume linklib IS sharedlib
+  lt_cv_sharedlib_from_linklib_cmd="$ECHO"
+  ;;
+esac
+])
+sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd
+test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO
+
+_LT_DECL([], [sharedlib_from_linklib_cmd], [1],
+    [Command to associate shared and link libraries])
+])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB
+
+
+# _LT_PATH_MANIFEST_TOOL
+# ----------------------
+# locate the manifest tool
+m4_defun([_LT_PATH_MANIFEST_TOOL],
+[AC_CHECK_TOOL(MANIFEST_TOOL, mt, :)
+test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt
+AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool],
+  [lt_cv_path_mainfest_tool=no
+  echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD
+  $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  if $GREP 'Manifest Tool' conftest.out > /dev/null; then
+    lt_cv_path_mainfest_tool=yes
+  fi
+  rm -f conftest*])
+if test "x$lt_cv_path_mainfest_tool" != xyes; then
+  MANIFEST_TOOL=:
+fi
+_LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl
+])# _LT_PATH_MANIFEST_TOOL
 
 
@@ -3257,5 +3562,5 @@
 LIBM=
 case $host in
-*-*-beos* | *-*-cygwin* | *-*-pw32* | *-*-darwin*)
+*-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*)
   # These system don't have libm, or don't need it
   ;;
@@ -3285,5 +3590,10 @@
 
 if test "$GCC" = yes; then
-  _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
+  case $cc_basename in
+  nvcc*)
+    _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;;
+  *)
+    _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;;
+  esac
 
   _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions],
@@ -3302,4 +3612,5 @@
 [AC_REQUIRE([AC_CANONICAL_HOST])dnl
 AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_PROG_AWK])dnl
 AC_REQUIRE([LT_PATH_NM])dnl
 AC_REQUIRE([LT_PATH_LD])dnl
@@ -3369,6 +3680,6 @@
 
 # Transform an extracted symbol line into symbol name and symbol address
-lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p'"
-lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\) $/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
+lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p'"
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
 
 # Handle CRLF in mingw tool chain
@@ -3394,4 +3705,5 @@
     lt_cv_sys_global_symbol_pipe="$AWK ['"\
 "     {last_section=section; section=\$ 3};"\
+"     /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\
 "     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
 "     \$ 0!~/External *\|/{next};"\
@@ -3406,4 +3718,5 @@
     lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[	 ]]\($symcode$symcode*\)[[	 ]][[	 ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
   fi
+  lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'"
 
   # Check to see that the pipe works correctly.
@@ -3427,5 +3740,5 @@
     # Now try to grab the symbols.
     nlist=conftest.nm
-    if AC_TRY_EVAL(NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) && test -s "$nlist"; then
+    if AC_TRY_EVAL(NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) && test -s "$nlist"; then
       # Try sorting and uniquifying the output.
       if sort "$nlist" | uniq > "$nlist"T; then
@@ -3439,4 +3752,16 @@
 	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
 	  cat <<_LT_EOF > conftest.$ac_ext
+/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+/* DATA imports from DLLs on WIN32 con't be const, because runtime
+   relocations are performed -- see ld's documentation on pseudo-relocs.  */
+# define LT@&t@_DLSYM_CONST
+#elif defined(__osf__)
+/* This system does not cope well with relocations in const data.  */
+# define LT@&t@_DLSYM_CONST
+#else
+# define LT@&t@_DLSYM_CONST const
+#endif
+
 #ifdef __cplusplus
 extern "C" {
@@ -3450,5 +3775,5 @@
 
 /* The mapping between symbol names and symbols.  */
-const struct {
+LT@&t@_DLSYM_CONST struct {
   const char *name;
   void       *address;
@@ -3476,6 +3801,6 @@
 	  # Now try linking the two files.
 	  mv conftest.$ac_objext conftstm.$ac_objext
-	  lt_save_LIBS="$LIBS"
-	  lt_save_CFLAGS="$CFLAGS"
+	  lt_globsym_save_LIBS=$LIBS
+	  lt_globsym_save_CFLAGS=$CFLAGS
 	  LIBS="conftstm.$ac_objext"
 	  CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
@@ -3483,6 +3808,6 @@
 	    pipe_works=yes
 	  fi
-	  LIBS="$lt_save_LIBS"
-	  CFLAGS="$lt_save_CFLAGS"
+	  LIBS=$lt_globsym_save_LIBS
+	  CFLAGS=$lt_globsym_save_CFLAGS
 	else
 	  echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
@@ -3517,4 +3842,11 @@
 fi
 
+# Response file support.
+if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+  nm_file_list_spec='@'
+elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then
+  nm_file_list_spec='@'
+fi
+
 _LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1],
     [Take the output of nm and produce a listing of raw symbols and C names])
@@ -3527,4 +3859,6 @@
     [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1],
     [Transform the output of nm in a C name address pair when lib prefix is needed])
+_LT_DECL([], [nm_file_list_spec], [1],
+    [Specify filename containing input files for $NM])
 ]) # _LT_CMD_GLOBAL_SYMBOLS
 
@@ -3538,5 +3872,4 @@
 _LT_TAGVAR(lt_prog_compiler_static, $1)=
 
-AC_MSG_CHECKING([for $compiler option to produce PIC])
 m4_if([$1], [CXX], [
   # C++ specific cases for pic, static, wl, etc.
@@ -3588,4 +3921,9 @@
       # DJGPP does not support shared libraries at all
       _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+      ;;
+    haiku*)
+      # PIC is the default for Haiku.
+      # The "-static" flag exists, but is broken.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)=
       ;;
     interix[[3-9]]*)
@@ -3637,4 +3975,10 @@
 	  ;;
 	esac
+	;;
+      mingw* | cygwin* | os2* | pw32* | cegcc*)
+	# This hack is so that the source file can tell whether it is being
+	# built for inclusion in a dll (and should export symbols for example).
+	m4_if([$1], [GCJ], [],
+	  [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
 	;;
       dgux*)
@@ -3694,5 +4038,5 @@
 	esac
 	;;
-      linux* | k*bsd*-gnu)
+      linux* | k*bsd*-gnu | kopensolaris*-gnu)
 	case $cc_basename in
 	  KCC*)
@@ -3727,6 +4071,6 @@
 	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
 	    ;;
-	  xlc* | xlC*)
-	    # IBM XL 8.0 on PPC
+	  xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*)
+	    # IBM XL 8.0, 9.0 on PPC and BlueGene
 	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
 	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
@@ -3790,5 +4134,5 @@
       solaris*)
 	case $cc_basename in
-	  CC*)
+	  CC* | sunCC*)
 	    # Sun C++ 4.2, 5.x and Centerline C++
 	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
@@ -3894,4 +4238,10 @@
       ;;
 
+    haiku*)
+      # PIC is the default for Haiku.
+      # The "-static" flag exists, but is broken.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)=
+      ;;
+
     hpux*)
       # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
@@ -3934,4 +4284,13 @@
     *)
       _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+      ;;
+    esac
+
+    case $cc_basename in
+    nvcc*) # Cuda Compiler Driver 2.2
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker '
+      if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
+        _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)"
+      fi
       ;;
     esac
@@ -3978,5 +4337,5 @@
       ;;
 
-    linux* | k*bsd*-gnu)
+    linux* | k*bsd*-gnu | kopensolaris*-gnu)
       case $cc_basename in
       # old Intel for x86_64 which still supported -KPIC.
@@ -3999,5 +4358,11 @@
 	_LT_TAGVAR(lt_prog_compiler_static, $1)='--static'
 	;;
-      pgcc* | pgf77* | pgf90* | pgf95*)
+      nagfor*)
+	# NAG Fortran compiler
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	;;
+      pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*)
         # Portland Group compilers (*not* the Pentium gcc compiler,
 	# which looks to be a dead project)
@@ -4011,6 +4376,6 @@
         _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
         ;;
-      xl*)
-	# IBM XL C 8.0/Fortran 10.1 on PPC
+      xl* | bgxl* | bgf* | mpixl*)
+	# IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene
 	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
 	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
@@ -4019,4 +4384,15 @@
       *)
 	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*)
+	  # Sun Fortran 8.3 passes all unrecognized flags to the linker
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)=''
+	  ;;
+	*Sun\ F* | *Sun*Fortran*)
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+	  ;;
 	*Sun\ C*)
 	  # Sun C 5.9
@@ -4025,9 +4401,13 @@
 	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
 	  ;;
-	*Sun\ F*)
-	  # Sun Fortran 8.3 passes all unrecognized flags to the linker
-	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+        *Intel*\ [[CF]]*Compiler*)
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	  ;;
+	*Portland\ Group*)
+	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
 	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	  _LT_TAGVAR(lt_prog_compiler_wl, $1)=''
 	  ;;
 	esac
@@ -4061,5 +4441,5 @@
       _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
       case $cc_basename in
-      f77* | f90* | f95*)
+      f77* | f90* | f95* | sunf77* | sunf90* | sunf95*)
 	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
       *)
@@ -4118,7 +4498,9 @@
     ;;
 esac
-AC_MSG_RESULT([$_LT_TAGVAR(lt_prog_compiler_pic, $1)])
-_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1],
-	[How to pass a linker flag through the compiler])
+
+AC_CACHE_CHECK([for $compiler option to produce PIC],
+  [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)],
+  [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)])
+_LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)
 
 #
@@ -4139,4 +4521,6 @@
 	[Additional compiler flags for building library objects])
 
+_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1],
+	[How to pass a linker flag through the compiler])
 #
 # Check to make sure the static flag actually works.
@@ -4159,4 +4543,5 @@
 [AC_REQUIRE([LT_PATH_LD])dnl
 AC_REQUIRE([LT_PATH_NM])dnl
+m4_require([_LT_PATH_MANIFEST_TOOL])dnl
 m4_require([_LT_FILEUTILS_DEFAULTS])dnl
 m4_require([_LT_DECL_EGREP])dnl
@@ -4167,10 +4552,13 @@
 m4_if([$1], [CXX], [
   _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
   case $host_os in
   aix[[4-9]]*)
     # If we're using GNU nm, then we don't want the "-C" option.
     # -C means demangle to AIX nm, but means don't demangle with GNU nm
+    # Also, AIX nm treats weak defined symbols like other global defined
+    # symbols, whereas GNU nm marks them as "W".
     if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
-      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
     else
       _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
@@ -4179,13 +4567,20 @@
   pw32*)
     _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds"
-  ;;
+    ;;
   cygwin* | mingw* | cegcc*)
-    _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;/^.*[[ ]]__nm__/s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
-  ;;
+    case $cc_basename in
+    cl*)
+      _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
+      ;;
+    *)
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
+      _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
+      ;;
+    esac
+    ;;
   *)
     _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  ;;
+    ;;
   esac
-  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
 ], [
   runpath_var=
@@ -4202,5 +4597,4 @@
   _LT_TAGVAR(hardcode_direct_absolute, $1)=no
   _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-  _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
   _LT_TAGVAR(hardcode_libdir_separator, $1)=
   _LT_TAGVAR(hardcode_minus_L, $1)=no
@@ -4250,5 +4644,31 @@
 
   _LT_TAGVAR(ld_shlibs, $1)=yes
+
+  # On some targets, GNU ld is compatible enough with the native linker
+  # that we're better off using the native interface for both.
+  lt_use_gnu_ld_interface=no
   if test "$with_gnu_ld" = yes; then
+    case $host_os in
+      aix*)
+	# The AIX port of GNU ld has always aspired to compatibility
+	# with the native linker.  However, as the warning in the GNU ld
+	# block says, versions before 2.19.5* couldn't really create working
+	# shared libraries, regardless of the interface used.
+	case `$LD -v 2>&1` in
+	  *\ \(GNU\ Binutils\)\ 2.19.5*) ;;
+	  *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;;
+	  *\ \(GNU\ Binutils\)\ [[3-9]]*) ;;
+	  *)
+	    lt_use_gnu_ld_interface=yes
+	    ;;
+	esac
+	;;
+      *)
+	lt_use_gnu_ld_interface=yes
+	;;
+    esac
+  fi
+
+  if test "$lt_use_gnu_ld_interface" = yes; then
     # If archive_cmds runs LD, not CC, wlarc should be empty
     wlarc='${wl}'
@@ -4268,4 +4688,5 @@
     supports_anon_versioning=no
     case `$LD -v 2>&1` in
+      *GNU\ gold*) supports_anon_versioning=yes ;;
       *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
       *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
@@ -4283,9 +4704,10 @@
 	cat <<_LT_EOF 1>&2
 
-*** Warning: the GNU linker, at least up to release 2.9.1, is reported
+*** Warning: the GNU linker, at least up to release 2.19, is reported
 *** to be unable to reliably create shared libraries on AIX.
 *** Therefore, libtool is disabling shared libraries support.  If you
-*** really care for shared libraries, you may want to modify your PATH
-*** so that a non-GNU linker is found, and then restart.
+*** really care for shared libraries, you may want to install binutils
+*** 2.20 or above, or modify your PATH so that a non-GNU linker is found.
+*** You will then need to restart the configuration process.
 
 _LT_EOF
@@ -4323,8 +4745,10 @@
       # as there is no search path for DLLs.
       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
       _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
       _LT_TAGVAR(always_export_symbols, $1)=no
       _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
-      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols'
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
+      _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
@@ -4344,4 +4768,9 @@
       ;;
 
+    haiku*)
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
     interix[[3-9]]*)
       _LT_TAGVAR(hardcode_direct, $1)=no
@@ -4359,5 +4788,5 @@
       ;;
 
-    gnu* | linux* | tpf* | k*bsd*-gnu)
+    gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
       tmp_diet=no
       if test "$host_os" = linux-dietlibc; then
@@ -4369,13 +4798,14 @@
 	 && test "$tmp_diet" = no
       then
-	tmp_addflag=
+	tmp_addflag=' $pic_flag'
 	tmp_sharedflag='-shared'
 	case $cc_basename,$host_cpu in
         pgcc*)				# Portland Group C compiler
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
 	  tmp_addflag=' $pic_flag'
 	  ;;
-	pgf77* | pgf90* | pgf95*)	# Portland Group f77 and f90 compilers
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+	pgf77* | pgf90* | pgf95* | pgfortran*)
+					# Portland Group f77 and f90 compilers
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
 	  tmp_addflag=' $pic_flag -Mnomain' ;;
 	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
@@ -4388,11 +4818,15 @@
 	  _LT_TAGVAR(whole_archive_flag_spec, $1)=
 	  tmp_sharedflag='--shared' ;;
-	xl[[cC]]*)			# IBM XL C 8.0 on PPC (deal with xlf below)
+	xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below)
 	  tmp_sharedflag='-qmkshrobj'
 	  tmp_addflag= ;;
+	nvcc*)	# Cuda Compiler Driver 2.2
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(compiler_needs_object, $1)=yes
+	  ;;
 	esac
 	case `$CC -V 2>&1 | sed 5q` in
 	*Sun\ C*)			# Sun C 5.9
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
 	  _LT_TAGVAR(compiler_needs_object, $1)=yes
 	  tmp_sharedflag='-G' ;;
@@ -4410,15 +4844,14 @@
 
 	case $cc_basename in
-	xlf*)
+	xlf* | bgf* | bgxlf* | mpixlf*)
 	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
 	  _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive'
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-	  _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='-rpath $libdir'
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $compiler_flags -soname $soname -o $lib'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib'
 	  if test "x$supports_anon_versioning" = xyes; then
 	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
 	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
 	      echo "local: *; };" >> $output_objdir/$libname.ver~
-	      $LD -shared $libobjs $deplibs $compiler_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
+	      $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
 	  fi
 	  ;;
@@ -4434,6 +4867,6 @@
 	wlarc=
       else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
       fi
       ;;
@@ -4453,6 +4886,6 @@
 _LT_EOF
       elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
       else
 	_LT_TAGVAR(ld_shlibs, $1)=no
@@ -4500,6 +4933,6 @@
     *)
       if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
       else
 	_LT_TAGVAR(ld_shlibs, $1)=no
@@ -4541,6 +4974,8 @@
 	# If we're using GNU nm, then we don't want the "-C" option.
 	# -C means demangle to AIX nm, but means don't demangle with GNU nm
+	# Also, AIX nm treats weak defined symbols like other global
+	# defined symbols, whereas GNU nm marks them as "W".
 	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
-	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
 	else
 	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
@@ -4629,7 +5064,7 @@
         # Determine the default libpath from the value encoded in an
         # empty executable.
-        _LT_SYS_MODULE_PATH_AIX
+        _LT_SYS_MODULE_PATH_AIX([$1])
         _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
       else
 	if test "$host_cpu" = ia64; then
@@ -4640,5 +5075,5 @@
 	 # Determine the default libpath from the value encoded in an
 	 # empty executable.
-	 _LT_SYS_MODULE_PATH_AIX
+	 _LT_SYS_MODULE_PATH_AIX([$1])
 	 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
 	  # Warning - without using the other run time loading flags,
@@ -4646,6 +5081,11 @@
 	  _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
 	  _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
-	  # Exported symbols can be pulled into shared objects from archives
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	  if test "$with_gnu_ld" = yes; then
+	    # We only use this code for GNU lds that support --whole-archive.
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	  else
+	    # Exported symbols can be pulled into shared objects from archives
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	  fi
 	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
 	  # This is similar to how AIX traditionally builds its shared libraries.
@@ -4679,18 +5119,62 @@
       # hardcode_libdir_flag_spec is actually meaningless, as there is
       # no search path for DLLs.
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
-      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-      # Tell ltmain to make .lib files, not .a files.
-      libext=lib
-      # Tell ltmain to make .dll files, not .so files.
-      shrext_cmds=".dll"
-      # FIXME: Setting linknames here is a bad hack.
-      _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `$ECHO "X$deplibs" | $Xsed -e '\''s/ -lc$//'\''` -link -dll~linknames='
-      # The linker will automatically build a .lib file if we build a DLL.
-      _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
-      # FIXME: Should let the user specify the lib program.
-      _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs'
-      _LT_TAGVAR(fix_srcfile_path, $1)='`cygpath -w "$srcfile"`'
-      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+      case $cc_basename in
+      cl*)
+	# Native MSVC
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	_LT_TAGVAR(always_export_symbols, $1)=yes
+	_LT_TAGVAR(file_list_spec, $1)='@'
+	# Tell ltmain to make .lib files, not .a files.
+	libext=lib
+	# Tell ltmain to make .dll files, not .so files.
+	shrext_cmds=".dll"
+	# FIXME: Setting linknames here is a bad hack.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
+	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	    sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
+	  else
+	    sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
+	  fi~
+	  $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+	  linknames='
+	# The linker will not automatically build a static lib if we build a DLL.
+	# _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	_LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
+	_LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols'
+	# Don't use ranlib
+	_LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
+	_LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
+	  lt_tool_outputfile="@TOOL_OUTPUT@"~
+	  case $lt_outputfile in
+	    *.exe|*.EXE) ;;
+	    *)
+	      lt_outputfile="$lt_outputfile.exe"
+	      lt_tool_outputfile="$lt_tool_outputfile.exe"
+	      ;;
+	  esac~
+	  if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
+	    $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+	    $RM "$lt_outputfile.manifest";
+	  fi'
+	;;
+      *)
+	# Assume MSVC wrapper
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	# Tell ltmain to make .lib files, not .a files.
+	libext=lib
+	# Tell ltmain to make .dll files, not .so files.
+	shrext_cmds=".dll"
+	# FIXME: Setting linknames here is a bad hack.
+	_LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames='
+	# The linker will automatically build a .lib file if we build a DLL.
+	_LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+	# FIXME: Should let the user specify the lib program.
+	_LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs'
+	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	;;
+      esac
       ;;
 
@@ -4703,8 +5187,4 @@
       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
       _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    freebsd1*)
-      _LT_TAGVAR(ld_shlibs, $1)=no
       ;;
 
@@ -4721,5 +5201,5 @@
 
     # Unfortunately, older versions of FreeBSD 2 do not have this feature.
-    freebsd2*)
+    freebsd2.*)
       _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
       _LT_TAGVAR(hardcode_direct, $1)=yes
@@ -4730,5 +5210,5 @@
     # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
     freebsd* | dragonfly*)
-      _LT_TAGVAR(archive_cmds, $1)='$CC -shared -o $lib $libobjs $deplibs $compiler_flags'
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
       _LT_TAGVAR(hardcode_direct, $1)=yes
@@ -4738,5 +5218,5 @@
     hpux9*)
       if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
       else
 	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
@@ -4753,6 +5233,6 @@
 
     hpux10*)
-      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
       else
 	_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
@@ -4760,5 +5240,4 @@
       if test "$with_gnu_ld" = no; then
 	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-	_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir'
 	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
 	_LT_TAGVAR(hardcode_direct, $1)=yes
@@ -4772,5 +5251,5 @@
 
     hpux11*)
-      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
 	case $host_cpu in
 	hppa*64*)
@@ -4778,8 +5257,8 @@
 	  ;;
 	ia64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	esac
@@ -4793,5 +5272,12 @@
 	  ;;
 	*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	m4_if($1, [], [
+	  # Older versions of the 11.00 compiler do not understand -b yet
+	  # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does)
+	  _LT_LINKER_OPTION([if $CC understands -b],
+	    _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b],
+	    [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'],
+	    [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])],
+	  [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'])
 	  ;;
 	esac
@@ -4821,17 +5307,32 @@
     irix5* | irix6* | nonstopux*)
       if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
 	# Try to use the -exported_symbol ld option, if it does not
 	# work, assume that -exports_file does not work either and
 	# implicitly export all symbols.
-        save_LDFLAGS="$LDFLAGS"
-        LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
-        AC_LINK_IFELSE(int foo(void) {},
-          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
-        )
-        LDFLAGS="$save_LDFLAGS"
+	# This should be the same for all languages, so no per-tag cache variable.
+	AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol],
+	  [lt_cv_irix_exported_symbol],
+	  [save_LDFLAGS="$LDFLAGS"
+	   LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
+	   AC_LINK_IFELSE(
+	     [AC_LANG_SOURCE(
+	        [AC_LANG_CASE([C], [[int foo (void) { return 0; }]],
+			      [C++], [[int foo (void) { return 0; }]],
+			      [Fortran 77], [[
+      subroutine foo
+      end]],
+			      [Fortran], [[
+      subroutine foo
+      end]])])],
+	      [lt_cv_irix_exported_symbol=yes],
+	      [lt_cv_irix_exported_symbol=no])
+           LDFLAGS="$save_LDFLAGS"])
+	if test "$lt_cv_irix_exported_symbol" = yes; then
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
+	fi
       else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
       fi
       _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
@@ -4895,5 +5396,5 @@
       _LT_TAGVAR(hardcode_minus_L, $1)=yes
       _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$ECHO DATA >> $output_objdir/$libname.def~$ECHO " SINGLE NONSHARED" >> $output_objdir/$libname.def~$ECHO EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
       _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
       ;;
@@ -4902,8 +5403,8 @@
       if test "$GCC" = yes; then
 	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
       else
 	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
       fi
       _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
@@ -4915,11 +5416,11 @@
       if test "$GCC" = yes; then
 	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
 	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
       else
 	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
 	_LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
-	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
+	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
 
 	# Both c and cxx compiler support -rpath directly
@@ -4934,7 +5435,7 @@
       if test "$GCC" = yes; then
 	wlarc='${wl}'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
 	_LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $CC -shared ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+	  $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
       else
 	case `$CC -V 2>&1` in
@@ -5112,34 +5613,36 @@
       # systems, -lgcc has to come before -lc. If gcc already passes -lc
       # to ld, don't add -lc before -lgcc.
-      AC_MSG_CHECKING([whether -lc should be explicitly linked in])
-      $RM conftest*
-      echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-      if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
-        soname=conftest
-        lib=conftest
-        libobjs=conftest.$ac_objext
-        deplibs=
-        wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1)
-	pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1)
-        compiler_flags=-v
-        linker_flags=-v
-        verstring=
-        output_objdir=.
-        libname=conftest
-        lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1)
-        _LT_TAGVAR(allow_undefined_flag, $1)=
-        if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1)
-        then
-	  _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-        else
-	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-        fi
-        _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag
-      else
-        cat conftest.err 1>&5
-      fi
-      $RM conftest*
-      AC_MSG_RESULT([$_LT_TAGVAR(archive_cmds_need_lc, $1)])
+      AC_CACHE_CHECK([whether -lc should be explicitly linked in],
+	[lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1),
+	[$RM conftest*
+	echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+	if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
+	  soname=conftest
+	  lib=conftest
+	  libobjs=conftest.$ac_objext
+	  deplibs=
+	  wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1)
+	  pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1)
+	  compiler_flags=-v
+	  linker_flags=-v
+	  verstring=
+	  output_objdir=.
+	  libname=conftest
+	  lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1)
+	  _LT_TAGVAR(allow_undefined_flag, $1)=
+	  if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1)
+	  then
+	    lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+	  else
+	    lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+	  fi
+	  _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag
+	else
+	  cat conftest.err 1>&5
+	fi
+	$RM conftest*
+	])
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)
       ;;
     esac
@@ -5178,7 +5681,4 @@
     [Flag to hardcode $libdir into a binary during linking.
     This must work even if $libdir does not exist])
-_LT_TAGDECL([], [hardcode_libdir_flag_spec_ld], [1],
-    [[If ld is used when linking, flag to hardcode $libdir into a binary
-    during linking.  This must work even if $libdir does not exist]])
 _LT_TAGDECL([], [hardcode_libdir_separator], [1],
     [Whether we need a single "-rpath" flag with a separated argument])
@@ -5206,6 +5706,4 @@
 _LT_TAGDECL([], [link_all_deplibs], [0],
     [Whether libtool must link a program against all its dependency libraries])
-_LT_TAGDECL([], [fix_srcfile_path], [1],
-    [Fix the shell variable $srcfile for the compiler])
 _LT_TAGDECL([], [always_export_symbols], [0],
     [Set to "yes" if exported symbols are required])
@@ -5218,4 +5716,6 @@
 _LT_TAGDECL([], [prelink_cmds], [2],
     [Commands necessary for linking programs (against libraries) with templates])
+_LT_TAGDECL([], [postlink_cmds], [2],
+    [Commands necessary for finishing linking programs])
 _LT_TAGDECL([], [file_list_spec], [1],
     [Specify filename containing input files])
@@ -5311,12 +5811,13 @@
 
 
-# _LT_PROG_CXX
-# ------------
-# Since AC_PROG_CXX is broken, in that it returns g++ if there is no c++
-# compiler, we have our own version here.
-m4_defun([_LT_PROG_CXX],
-[
-pushdef([AC_MSG_ERROR], [_lt_caught_CXX_error=yes])
-AC_PROG_CXX
+# _LT_LANG_CXX_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for a C++ compiler are suitably
+# defined.  These variables are subsequently used by _LT_CONFIG to write
+# the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_CXX_CONFIG],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_PATH_MANIFEST_TOOL])dnl
 if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
     ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
@@ -5326,20 +5827,4 @@
   _lt_caught_CXX_error=yes
 fi
-popdef([AC_MSG_ERROR])
-])# _LT_PROG_CXX
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([_LT_PROG_CXX], [])
-
-
-# _LT_LANG_CXX_CONFIG([TAG])
-# --------------------------
-# Ensure that the configuration variables for a C++ compiler are suitably
-# defined.  These variables are subsequently used by _LT_CONFIG to write
-# the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_CXX_CONFIG],
-[AC_REQUIRE([_LT_PROG_CXX])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_EGREP])dnl
 
 AC_LANG_PUSH(C++)
@@ -5353,5 +5838,4 @@
 _LT_TAGVAR(hardcode_direct_absolute, $1)=no
 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
 _LT_TAGVAR(hardcode_libdir_separator, $1)=
 _LT_TAGVAR(hardcode_minus_L, $1)=no
@@ -5363,4 +5847,6 @@
 _LT_TAGVAR(link_all_deplibs, $1)=unknown
 _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
 _LT_TAGVAR(no_undefined_flag, $1)=
 _LT_TAGVAR(whole_archive_flag_spec, $1)=
@@ -5394,4 +5880,5 @@
   # Allow CC to be a program name with arguments.
   lt_save_CC=$CC
+  lt_save_CFLAGS=$CFLAGS
   lt_save_LD=$LD
   lt_save_GCC=$GCC
@@ -5411,4 +5898,5 @@
   test -z "${LDCXX+set}" || LD=$LDCXX
   CC=${CXX-"c++"}
+  CFLAGS=$CXXFLAGS
   compiler=$CC
   _LT_TAGVAR(compiler, $1)=$CC
@@ -5432,6 +5920,6 @@
       # archiving commands below assume that GNU ld is being used.
       if test "$with_gnu_ld" = yes; then
-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+        _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
 
         _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
@@ -5465,5 +5953,5 @@
       # what "hidden" libraries, object files and flags are used when
       # linking a shared library.
-      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
+      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
 
     else
@@ -5574,8 +6062,8 @@
           # Determine the default libpath from the value encoded in an empty
           # executable.
-          _LT_SYS_MODULE_PATH_AIX
+          _LT_SYS_MODULE_PATH_AIX([$1])
           _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
 
-          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
         else
           if test "$host_cpu" = ia64; then
@@ -5586,5 +6074,5 @@
 	    # Determine the default libpath from the value encoded in an
 	    # empty executable.
-	    _LT_SYS_MODULE_PATH_AIX
+	    _LT_SYS_MODULE_PATH_AIX([$1])
 	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
 	    # Warning - without using the other run time loading flags,
@@ -5592,6 +6080,11 @@
 	    _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
 	    _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
-	    # Exported symbols can be pulled into shared objects from archives
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	    if test "$with_gnu_ld" = yes; then
+	      # We only use this code for GNU lds that support --whole-archive.
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    else
+	      # Exported symbols can be pulled into shared objects from archives
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+	    fi
 	    _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
 	    # This is similar to how AIX traditionally builds its shared
@@ -5623,26 +6116,73 @@
 
       cygwin* | mingw* | pw32* | cegcc*)
-        # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
-        # as there is no search path for DLLs.
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-        _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-        _LT_TAGVAR(always_export_symbols, $1)=no
-        _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'
-          # 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
-	    cp $export_symbols $output_objdir/$soname.def;
-          else
-	    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'
-        else
-          _LT_TAGVAR(ld_shlibs, $1)=no
-        fi
-        ;;
+	case $GXX,$cc_basename in
+	,cl* | no,cl*)
+	  # Native MSVC
+	  # hardcode_libdir_flag_spec is actually meaningless, as there is
+	  # no search path for DLLs.
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	  _LT_TAGVAR(always_export_symbols, $1)=yes
+	  _LT_TAGVAR(file_list_spec, $1)='@'
+	  # Tell ltmain to make .lib files, not .a files.
+	  libext=lib
+	  # Tell ltmain to make .dll files, not .so files.
+	  shrext_cmds=".dll"
+	  # FIXME: Setting linknames here is a bad hack.
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+	      $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
+	    else
+	      $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
+	    fi~
+	    $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+	    linknames='
+	  # The linker will not automatically build a static lib if we build a DLL.
+	  # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	  # Don't use ranlib
+	  _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
+	  _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
+	    lt_tool_outputfile="@TOOL_OUTPUT@"~
+	    case $lt_outputfile in
+	      *.exe|*.EXE) ;;
+	      *)
+		lt_outputfile="$lt_outputfile.exe"
+		lt_tool_outputfile="$lt_tool_outputfile.exe"
+		;;
+	    esac~
+	    func_to_tool_file "$lt_outputfile"~
+	    if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
+	      $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+	      $RM "$lt_outputfile.manifest";
+	    fi'
+	  ;;
+	*)
+	  # g++
+	  # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+	  # as there is no search path for DLLs.
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
+	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	  _LT_TAGVAR(always_export_symbols, $1)=no
+	  _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'
+	    # 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
+	      cp $export_symbols $output_objdir/$soname.def;
+	    else
+	      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'
+	  else
+	    _LT_TAGVAR(ld_shlibs, $1)=no
+	  fi
+	  ;;
+	esac
+	;;
       darwin* | rhapsody*)
         _LT_DARWIN_LINKER_FEATURES($1)
@@ -5667,5 +6207,5 @@
         ;;
 
-      freebsd[[12]]*)
+      freebsd2.*)
         # C++ shared libraries reported to be fairly broken before
 	# switch to ELF
@@ -5684,4 +6224,9 @@
 
       gnu*)
+        ;;
+
+      haiku*)
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        _LT_TAGVAR(link_all_deplibs, $1)=yes
         ;;
 
@@ -5710,9 +6255,9 @@
             # from the output so that they don't get included in the library
             # dependencies.
-            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
             ;;
           *)
             if test "$GXX" = yes; then
-              _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+              _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
             else
               # FIXME: insert proper C++ library support
@@ -5775,5 +6320,5 @@
 	    # from the output so that they don't get included in the library
 	    # dependencies.
-	    output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+	    output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
 	    ;;
           *)
@@ -5785,8 +6330,8 @@
 	            ;;
 	          ia64*)
-	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
 	            ;;
 	          *)
-	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
 	            ;;
 	        esac
@@ -5818,5 +6363,5 @@
           CC*)
 	    # SGI C++
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
 
 	    # Archives containing C++ object files must be created using
@@ -5829,7 +6374,7 @@
 	    if test "$GXX" = yes; then
 	      if test "$with_gnu_ld" = no; then
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
 	      else
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` -o $lib'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib'
 	      fi
 	    fi
@@ -5842,5 +6387,5 @@
         ;;
 
-      linux* | k*bsd*-gnu)
+      linux* | k*bsd*-gnu | kopensolaris*-gnu)
         case $cc_basename in
           KCC*)
@@ -5860,5 +6405,5 @@
 	    # from the output so that they don't get included in the library
 	    # dependencies.
-	    output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+	    output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
 
 	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
@@ -5897,24 +6442,24 @@
             # Portland Group C++ compiler
 	    case `$CC -V` in
-	    *pgCC\ [[1-5]]* | *pgcpp\ [[1-5]]*)
+	    *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*)
 	      _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~
 		rm -rf $tpldir~
 		$CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~
-		compile_command="$compile_command `find $tpldir -name \*.o | $NL2SP`"'
+		compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"'
 	      _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~
 		rm -rf $tpldir~
 		$CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~
-		$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | $NL2SP`~
+		$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~
 		$RANLIB $oldlib'
 	      _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~
 		rm -rf $tpldir~
 		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
-		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
 	      _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~
 		rm -rf $tpldir~
 		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
-		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
 	      ;;
-	    *) # Version 6 will use weak symbols
+	    *) # Version 6 and above use weak symbols
 	      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
 	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
@@ -5924,5 +6469,5 @@
 	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
 	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
             ;;
 	  cxx*)
@@ -5943,7 +6488,7 @@
 	    # from the output so that they don't get included in the library
 	    # dependencies.
-	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`$ECHO "X$templist" | $Xsed -e "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed'
 	    ;;
-	  xl*)
+	  xl* | mpixl* | bgxl*)
 	    # IBM XL 8.0 on PPC, with GNU ld
 	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
@@ -5965,5 +6510,5 @@
 	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols'
 	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
 	      _LT_TAGVAR(compiler_needs_object, $1)=yes
 
@@ -5971,5 +6516,5 @@
 	      # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1
 	      # would be better.
-	      output_verbose_link_cmd='echo'
+	      output_verbose_link_cmd='func_echo_all'
 
 	      # Archives containing C++ object files must be created using
@@ -6040,5 +6585,5 @@
 	    _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
 	  fi
-	  output_verbose_link_cmd=echo
+	  output_verbose_link_cmd=func_echo_all
 	else
 	  _LT_TAGVAR(ld_shlibs, $1)=no
@@ -6075,13 +6620,13 @@
 	      osf3*)
 	        _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && $ECHO "X${wl}-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
 	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
 		;;
 	      *)
 	        _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
 	        _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
 	          echo "-hidden">> $lib.exp~
-	          $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp  `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~
+	          $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp  `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~
 	          $RM $lib.exp'
 	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
@@ -6099,5 +6644,5 @@
 	    # from the output so that they don't get included in the library
 	    # dependencies.
-	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`$ECHO "X$templist" | $Xsed -e "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
 	    ;;
 	  *)
@@ -6106,8 +6651,8 @@
 	      case $host in
 	        osf3*)
-	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
 		  ;;
 	        *)
-	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
 		  ;;
 	      esac
@@ -6119,5 +6664,5 @@
 	      # what "hidden" libraries, object files and flags are used when
 	      # linking a shared library.
-	      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
+	      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
 
 	    else
@@ -6155,5 +6700,5 @@
       solaris*)
         case $cc_basename in
-          CC*)
+          CC* | sunCC*)
 	    # Sun C++ 4.2, 5.x and Centerline C++
             _LT_TAGVAR(archive_cmds_need_lc,$1)=yes
@@ -6176,5 +6721,5 @@
 	    _LT_TAGVAR(link_all_deplibs, $1)=yes
 
-	    output_verbose_link_cmd='echo'
+	    output_verbose_link_cmd='func_echo_all'
 
 	    # Archives containing C++ object files must be created using
@@ -6196,12 +6741,12 @@
 	      _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs'
 	      if $CC --version | $GREP -v '^2\.7' > /dev/null; then
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
 	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-		  $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+		  $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
 
 	        # Commands to make compiler produce verbose output that lists
 	        # what "hidden" libraries, object files and flags are used when
 	        # linking a shared library.
-	        output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
+	        output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
 	      else
 	        # g++ 2.7 appears to require `-G' NOT `-shared' on this
@@ -6214,5 +6759,5 @@
 	        # what "hidden" libraries, object files and flags are used when
 	        # linking a shared library.
-	        output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
+	        output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
 	      fi
 
@@ -6268,4 +6813,8 @@
 	    _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
 	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~
+	      '"$_LT_TAGVAR(old_archive_cmds, $1)"
+	    _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~
+	      '"$_LT_TAGVAR(reload_cmds, $1)"
 	    ;;
 	  *)
@@ -6323,4 +6872,5 @@
 
   CC=$lt_save_CC
+  CFLAGS=$lt_save_CFLAGS
   LDCXX=$LD
   LD=$lt_save_LD
@@ -6337,4 +6887,27 @@
 
 
+# _LT_FUNC_STRIPNAME_CNF
+# ----------------------
+# func_stripname_cnf prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+#
+# This function is identical to the (non-XSI) version of func_stripname,
+# except this one can be used by m4 code that may be executed by configure,
+# rather than the libtool script.
+m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl
+AC_REQUIRE([_LT_DECL_SED])
+AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])
+func_stripname_cnf ()
+{
+  case ${2} in
+  .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
+  *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
+  esac
+} # func_stripname_cnf
+])# _LT_FUNC_STRIPNAME_CNF
+
 # _LT_SYS_HIDDEN_LIBDEPS([TAGNAME])
 # ---------------------------------
@@ -6345,4 +6918,5 @@
 m4_defun([_LT_SYS_HIDDEN_LIBDEPS],
 [m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl
 # Dependencies to place before and after the object being linked:
 _LT_TAGVAR(predep_objects, $1)=
@@ -6394,5 +6968,18 @@
 };
 _LT_EOF
+], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF
+package foo
+func foo() {
+}
+_LT_EOF
 ])
+
+_lt_libdeps_save_CFLAGS=$CFLAGS
+case "$CC $CFLAGS " in #(
+*\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;;
+*\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;;
+*\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;;
+esac
+
 dnl Parse the compiler output and extract the necessary
 dnl objects, libraries and library flags.
@@ -6406,5 +6993,5 @@
 
   for p in `eval "$output_verbose_link_cmd"`; do
-    case $p in
+    case ${prev}${p} in
 
     -L* | -R* | -l*)
@@ -6415,11 +7002,20 @@
 	 prev=$p
 	 continue
-       else
-	 prev=
        fi
 
+       # Expand the sysroot to ease extracting the directories later.
+       if test -z "$prev"; then
+         case $p in
+         -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;;
+         -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;;
+         -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;;
+         esac
+       fi
+       case $p in
+       =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;;
+       esac
        if test "$pre_test_object_deps_done" = no; then
-	 case $p in
-	 -L* | -R*)
+	 case ${prev} in
+	 -L | -R)
 	   # Internal compiler library paths should come after those
 	   # provided the user.  The postdeps already come after the
@@ -6441,6 +7037,8 @@
 	 fi
        fi
+       prev=
        ;;
 
+    *.lto.$objext) ;; # Ignore GCC LTO objects
     *.$objext)
        # This assumes that the test object file only shows up
@@ -6478,4 +7076,5 @@
 
 $RM -f confest.$objext
+CFLAGS=$_lt_libdeps_save_CFLAGS
 
 # PORTME: override above test on systems where it is broken
@@ -6514,5 +7113,5 @@
 solaris*)
   case $cc_basename in
-  CC*)
+  CC* | sunCC*)
     # The more standards-conforming stlport4 library is
     # incompatible with the Cstd library. Avoid specifying
@@ -6558,22 +7157,4 @@
 
 
-# _LT_PROG_F77
-# ------------
-# Since AC_PROG_F77 is broken, in that it returns the empty string
-# if there is no fortran compiler, we have our own version here.
-m4_defun([_LT_PROG_F77],
-[
-pushdef([AC_MSG_ERROR], [_lt_disable_F77=yes])
-AC_PROG_F77
-if test -z "$F77" || test "X$F77" = "Xno"; then
-  _lt_disable_F77=yes
-fi
-popdef([AC_MSG_ERROR])
-])# _LT_PROG_F77
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([_LT_PROG_F77], [])
-
-
 # _LT_LANG_F77_CONFIG([TAG])
 # --------------------------
@@ -6582,6 +7163,8 @@
 # to write the compiler configuration to `libtool'.
 m4_defun([_LT_LANG_F77_CONFIG],
-[AC_REQUIRE([_LT_PROG_F77])dnl
-AC_LANG_PUSH(Fortran 77)
+[AC_LANG_PUSH(Fortran 77)
+if test -z "$F77" || test "X$F77" = "Xno"; then
+  _lt_disable_F77=yes
+fi
 
 _LT_TAGVAR(archive_cmds_need_lc, $1)=no
@@ -6593,5 +7176,4 @@
 _LT_TAGVAR(hardcode_direct_absolute, $1)=no
 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
 _LT_TAGVAR(hardcode_libdir_separator, $1)=
 _LT_TAGVAR(hardcode_minus_L, $1)=no
@@ -6602,4 +7184,6 @@
 _LT_TAGVAR(link_all_deplibs, $1)=unknown
 _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
 _LT_TAGVAR(no_undefined_flag, $1)=
 _LT_TAGVAR(whole_archive_flag_spec, $1)=
@@ -6641,5 +7225,7 @@
   lt_save_CC="$CC"
   lt_save_GCC=$GCC
+  lt_save_CFLAGS=$CFLAGS
   CC=${F77-"f77"}
+  CFLAGS=$FFLAGS
   compiler=$CC
   _LT_TAGVAR(compiler, $1)=$CC
@@ -6695,26 +7281,9 @@
   GCC=$lt_save_GCC
   CC="$lt_save_CC"
+  CFLAGS="$lt_save_CFLAGS"
 fi # test "$_lt_disable_F77" != yes
 
 AC_LANG_POP
 ])# _LT_LANG_F77_CONFIG
-
-
-# _LT_PROG_FC
-# -----------
-# Since AC_PROG_FC is broken, in that it returns the empty string
-# if there is no fortran compiler, we have our own version here.
-m4_defun([_LT_PROG_FC],
-[
-pushdef([AC_MSG_ERROR], [_lt_disable_FC=yes])
-AC_PROG_FC
-if test -z "$FC" || test "X$FC" = "Xno"; then
-  _lt_disable_FC=yes
-fi
-popdef([AC_MSG_ERROR])
-])# _LT_PROG_FC
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([_LT_PROG_FC], [])
 
 
@@ -6725,6 +7294,9 @@
 # to write the compiler configuration to `libtool'.
 m4_defun([_LT_LANG_FC_CONFIG],
-[AC_REQUIRE([_LT_PROG_FC])dnl
-AC_LANG_PUSH(Fortran)
+[AC_LANG_PUSH(Fortran)
+
+if test -z "$FC" || test "X$FC" = "Xno"; then
+  _lt_disable_FC=yes
+fi
 
 _LT_TAGVAR(archive_cmds_need_lc, $1)=no
@@ -6736,5 +7308,4 @@
 _LT_TAGVAR(hardcode_direct_absolute, $1)=no
 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
 _LT_TAGVAR(hardcode_libdir_separator, $1)=
 _LT_TAGVAR(hardcode_minus_L, $1)=no
@@ -6745,4 +7316,6 @@
 _LT_TAGVAR(link_all_deplibs, $1)=unknown
 _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
 _LT_TAGVAR(no_undefined_flag, $1)=
 _LT_TAGVAR(whole_archive_flag_spec, $1)=
@@ -6784,5 +7357,7 @@
   lt_save_CC="$CC"
   lt_save_GCC=$GCC
+  lt_save_CFLAGS=$CFLAGS
   CC=${FC-"f95"}
+  CFLAGS=$FCFLAGS
   compiler=$CC
   GCC=$ac_cv_fc_compiler_gnu
@@ -6840,5 +7415,6 @@
 
   GCC=$lt_save_GCC
-  CC="$lt_save_CC"
+  CC=$lt_save_CC
+  CFLAGS=$lt_save_CFLAGS
 fi # test "$_lt_disable_FC" != yes
 
@@ -6877,8 +7453,10 @@
 
 # Allow CC to be a program name with arguments.
-lt_save_CC="$CC"
+lt_save_CC=$CC
+lt_save_CFLAGS=$CFLAGS
 lt_save_GCC=$GCC
 GCC=yes
 CC=${GCJ-"gcj"}
+CFLAGS=$GCJFLAGS
 compiler=$CC
 _LT_TAGVAR(compiler, $1)=$CC
@@ -6890,4 +7468,6 @@
 
 _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
 
 ## CAVEAT EMPTOR:
@@ -6909,6 +7489,78 @@
 
 GCC=$lt_save_GCC
-CC="$lt_save_CC"
+CC=$lt_save_CC
+CFLAGS=$lt_save_CFLAGS
 ])# _LT_LANG_GCJ_CONFIG
+
+
+# _LT_LANG_GO_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for the GNU Go compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_GO_CONFIG],
+[AC_REQUIRE([LT_PROG_GO])dnl
+AC_LANG_SAVE
+
+# Source file extension for Go test sources.
+ac_ext=go
+
+# Object file extension for compiled Go test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="package main; func main() { }"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='package main; func main() { }'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC=$CC
+lt_save_CFLAGS=$CFLAGS
+lt_save_GCC=$GCC
+GCC=yes
+CC=${GOC-"gccgo"}
+CFLAGS=$GOFLAGS
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_TAGVAR(LD, $1)="$LD"
+_LT_CC_BASENAME([$compiler])
+
+# Go did not exist at the time GCC didn't implicitly link libc in.
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(reload_flag, $1)=$reload_flag
+_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+
+  _LT_CONFIG($1)
+fi
+
+AC_LANG_RESTORE
+
+GCC=$lt_save_GCC
+CC=$lt_save_CC
+CFLAGS=$lt_save_CFLAGS
+])# _LT_LANG_GO_CONFIG
 
 
@@ -6944,7 +7596,9 @@
 # Allow CC to be a program name with arguments.
 lt_save_CC="$CC"
+lt_save_CFLAGS=$CFLAGS
 lt_save_GCC=$GCC
 GCC=
 CC=${RC-"windres"}
+CFLAGS=
 compiler=$CC
 _LT_TAGVAR(compiler, $1)=$CC
@@ -6959,5 +7613,6 @@
 GCC=$lt_save_GCC
 AC_LANG_RESTORE
-CC="$lt_save_CC"
+CC=$lt_save_CC
+CFLAGS=$lt_save_CFLAGS
 ])# _LT_LANG_RC_CONFIG
 
@@ -6977,4 +7632,11 @@
 dnl aclocal-1.4 backwards compatibility:
 dnl AC_DEFUN([LT_AC_PROG_GCJ], [])
+
+
+# LT_PROG_GO
+# ----------
+AC_DEFUN([LT_PROG_GO],
+[AC_CHECK_TOOL(GOC, gccgo,)
+])
 
 
@@ -7018,4 +7680,13 @@
 ])
 
+# _LT_DECL_DLLTOOL
+# ----------------
+# Ensure DLLTOOL variable is set.
+m4_defun([_LT_DECL_DLLTOOL],
+[AC_CHECK_TOOL(DLLTOOL, dlltool, false)
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+_LT_DECL([], [DLLTOOL], [1], [DLL creation program])
+AC_SUBST([DLLTOOL])
+])
 
 # _LT_DECL_SED
@@ -7111,6 +7782,6 @@
 xsi_shell=no
 ( _lt_dummy="a/b/c"
-  test "${_lt_dummy##*/},${_lt_dummy%/*},"${_lt_dummy%"$_lt_dummy"}, \
-      = c,a/b,, \
+  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \
+      = c,a/b,b/c, \
     && eval 'test $(( 1 + 1 )) -eq 2 \
     && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
@@ -7151,207 +7822,161 @@
 
 
-# _LT_PROG_XSI_SHELLFNS
-# ---------------------
-# Bourne and XSI compatible variants of some useful shell functions.
-m4_defun([_LT_PROG_XSI_SHELLFNS],
-[case $xsi_shell in
-  yes)
-    cat << \_LT_EOF >> "$cfgfile"
-
-# func_dirname file append nondir_replacement
-# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
-# otherwise set result to NONDIR_REPLACEMENT.
-func_dirname ()
-{
-  case ${1} in
-    */*) func_dirname_result="${1%/*}${2}" ;;
-    *  ) func_dirname_result="${3}" ;;
-  esac
-}
-
-# func_basename file
-func_basename ()
-{
-  func_basename_result="${1##*/}"
-}
-
-# func_dirname_and_basename file append nondir_replacement
-# perform func_basename and func_dirname in a single function
-# call:
-#   dirname:  Compute the dirname of FILE.  If nonempty,
-#             add APPEND to the result, otherwise set result
-#             to NONDIR_REPLACEMENT.
-#             value returned in "$func_dirname_result"
-#   basename: Compute filename of FILE.
-#             value retuned in "$func_basename_result"
-# Implementation must be kept synchronized with func_dirname
-# and func_basename. For efficiency, we do not delegate to
-# those functions but instead duplicate the functionality here.
-func_dirname_and_basename ()
-{
-  case ${1} in
-    */*) func_dirname_result="${1%/*}${2}" ;;
-    *  ) func_dirname_result="${3}" ;;
-  esac
-  func_basename_result="${1##*/}"
-}
-
-# func_stripname prefix suffix name
-# strip PREFIX and SUFFIX off of NAME.
-# PREFIX and SUFFIX must not contain globbing or regex special
-# characters, hashes, percent signs, but SUFFIX may contain a leading
-# dot (in which case that matches only a dot).
-func_stripname ()
-{
-  # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are
-  # positional parameters, so assign one to ordinary parameter first.
-  func_stripname_result=${3}
-  func_stripname_result=${func_stripname_result#"${1}"}
-  func_stripname_result=${func_stripname_result%"${2}"}
-}
-
-# func_opt_split
-func_opt_split ()
-{
-  func_opt_split_opt=${1%%=*}
-  func_opt_split_arg=${1#*=}
-}
-
-# func_lo2o object
-func_lo2o ()
-{
-  case ${1} in
-    *.lo) func_lo2o_result=${1%.lo}.${objext} ;;
-    *)    func_lo2o_result=${1} ;;
-  esac
-}
-
-# func_xform libobj-or-source
-func_xform ()
-{
-  func_xform_result=${1%.*}.lo
-}
-
-# func_arith arithmetic-term...
-func_arith ()
-{
-  func_arith_result=$(( $[*] ))
-}
-
-# func_len string
-# STRING may not start with a hyphen.
-func_len ()
-{
-  func_len_result=${#1}
-}
-
-_LT_EOF
+# _LT_PROG_FUNCTION_REPLACE (FUNCNAME, REPLACEMENT-BODY)
+# ------------------------------------------------------
+# In `$cfgfile', look for function FUNCNAME delimited by `^FUNCNAME ()$' and
+# '^} FUNCNAME ', and replace its body with REPLACEMENT-BODY.
+m4_defun([_LT_PROG_FUNCTION_REPLACE],
+[dnl {
+sed -e '/^$1 ()$/,/^} # $1 /c\
+$1 ()\
+{\
+m4_bpatsubsts([$2], [$], [\\], [^\([	 ]\)], [\\\1])
+} # Extended-shell $1 implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+test 0 -eq $? || _lt_function_replace_fail=:
+])
+
+
+# _LT_PROG_REPLACE_SHELLFNS
+# -------------------------
+# Replace existing portable implementations of several shell functions with
+# equivalent extended shell implementations where those features are available..
+m4_defun([_LT_PROG_REPLACE_SHELLFNS],
+[if test x"$xsi_shell" = xyes; then
+  _LT_PROG_FUNCTION_REPLACE([func_dirname], [dnl
+    case ${1} in
+      */*) func_dirname_result="${1%/*}${2}" ;;
+      *  ) func_dirname_result="${3}" ;;
+    esac])
+
+  _LT_PROG_FUNCTION_REPLACE([func_basename], [dnl
+    func_basename_result="${1##*/}"])
+
+  _LT_PROG_FUNCTION_REPLACE([func_dirname_and_basename], [dnl
+    case ${1} in
+      */*) func_dirname_result="${1%/*}${2}" ;;
+      *  ) func_dirname_result="${3}" ;;
+    esac
+    func_basename_result="${1##*/}"])
+
+  _LT_PROG_FUNCTION_REPLACE([func_stripname], [dnl
+    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are
+    # positional parameters, so assign one to ordinary parameter first.
+    func_stripname_result=${3}
+    func_stripname_result=${func_stripname_result#"${1}"}
+    func_stripname_result=${func_stripname_result%"${2}"}])
+
+  _LT_PROG_FUNCTION_REPLACE([func_split_long_opt], [dnl
+    func_split_long_opt_name=${1%%=*}
+    func_split_long_opt_arg=${1#*=}])
+
+  _LT_PROG_FUNCTION_REPLACE([func_split_short_opt], [dnl
+    func_split_short_opt_arg=${1#??}
+    func_split_short_opt_name=${1%"$func_split_short_opt_arg"}])
+
+  _LT_PROG_FUNCTION_REPLACE([func_lo2o], [dnl
+    case ${1} in
+      *.lo) func_lo2o_result=${1%.lo}.${objext} ;;
+      *)    func_lo2o_result=${1} ;;
+    esac])
+
+  _LT_PROG_FUNCTION_REPLACE([func_xform], [    func_xform_result=${1%.*}.lo])
+
+  _LT_PROG_FUNCTION_REPLACE([func_arith], [    func_arith_result=$(( $[*] ))])
+
+  _LT_PROG_FUNCTION_REPLACE([func_len], [    func_len_result=${#1}])
+fi
+
+if test x"$lt_shell_append" = xyes; then
+  _LT_PROG_FUNCTION_REPLACE([func_append], [    eval "${1}+=\\${2}"])
+
+  _LT_PROG_FUNCTION_REPLACE([func_append_quoted], [dnl
+    func_quote_for_eval "${2}"
+dnl m4 expansion turns \\\\ into \\, and then the shell eval turns that into \
+    eval "${1}+=\\\\ \\$func_quote_for_eval_result"])
+
+  # Save a `func_append' function call where possible by direct use of '+='
+  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \
+    && mv -f "$cfgfile.tmp" "$cfgfile" \
+      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+  test 0 -eq $? || _lt_function_replace_fail=:
+else
+  # Save a `func_append' function call even when '+=' is not available
+  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \
+    && mv -f "$cfgfile.tmp" "$cfgfile" \
+      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
+  test 0 -eq $? || _lt_function_replace_fail=:
+fi
+
+if test x"$_lt_function_replace_fail" = x":"; then
+  AC_MSG_WARN([Unable to substitute extended shell functions in $ofile])
+fi
+])
+
+# _LT_PATH_CONVERSION_FUNCTIONS
+# -----------------------------
+# Determine which file name conversion functions should be used by
+# func_to_host_file (and, implicitly, by func_to_host_path).  These are needed
+# for certain cross-compile configurations and native mingw.
+m4_defun([_LT_PATH_CONVERSION_FUNCTIONS],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+AC_MSG_CHECKING([how to convert $build file names to $host format])
+AC_CACHE_VAL(lt_cv_to_host_file_cmd,
+[case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32
+        ;;
+    esac
     ;;
-  *) # Bourne compatible functions.
-    cat << \_LT_EOF >> "$cfgfile"
-
-# func_dirname file append nondir_replacement
-# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
-# otherwise set result to NONDIR_REPLACEMENT.
-func_dirname ()
-{
-  # Extract subdirectory from the argument.
-  func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"`
-  if test "X$func_dirname_result" = "X${1}"; then
-    func_dirname_result="${3}"
-  else
-    func_dirname_result="$func_dirname_result${2}"
-  fi
-}
-
-# func_basename file
-func_basename ()
-{
-  func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"`
-}
-
-dnl func_dirname_and_basename
-dnl A portable version of this function is already defined in general.m4sh
-dnl so there is no need for it here.
-
-# func_stripname prefix suffix name
-# strip PREFIX and SUFFIX off of NAME.
-# PREFIX and SUFFIX must not contain globbing or regex special
-# characters, hashes, percent signs, but SUFFIX may contain a leading
-# dot (in which case that matches only a dot).
-# func_strip_suffix prefix name
-func_stripname ()
-{
-  case ${2} in
-    .*) func_stripname_result=`$ECHO "X${3}" \
-           | $Xsed -e "s%^${1}%%" -e "s%\\\\${2}\$%%"`;;
-    *)  func_stripname_result=`$ECHO "X${3}" \
-           | $Xsed -e "s%^${1}%%" -e "s%${2}\$%%"`;;
-  esac
-}
-
-# sed scripts:
-my_sed_long_opt='1s/^\(-[[^=]]*\)=.*/\1/;q'
-my_sed_long_arg='1s/^-[[^=]]*=//'
-
-# func_opt_split
-func_opt_split ()
-{
-  func_opt_split_opt=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_opt"`
-  func_opt_split_arg=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_arg"`
-}
-
-# func_lo2o object
-func_lo2o ()
-{
-  func_lo2o_result=`$ECHO "X${1}" | $Xsed -e "$lo2o"`
-}
-
-# func_xform libobj-or-source
-func_xform ()
-{
-  func_xform_result=`$ECHO "X${1}" | $Xsed -e 's/\.[[^.]]*$/.lo/'`
-}
-
-# func_arith arithmetic-term...
-func_arith ()
-{
-  func_arith_result=`expr "$[@]"`
-}
-
-# func_len string
-# STRING may not start with a hyphen.
-func_len ()
-{
-  func_len_result=`expr "$[1]" : ".*" 2>/dev/null || echo $max_cmd_len`
-}
-
-_LT_EOF
+  *-*-cygwin* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=func_convert_file_noop
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin
+        ;;
+    esac
+    ;;
+  * ) # unhandled hosts (and "normal" native builds)
+    lt_cv_to_host_file_cmd=func_convert_file_noop
+    ;;
 esac
-
-case $lt_shell_append in
-  yes)
-    cat << \_LT_EOF >> "$cfgfile"
-
-# func_append var value
-# Append VALUE to the end of shell variable VAR.
-func_append ()
-{
-  eval "$[1]+=\$[2]"
-}
-_LT_EOF
+])
+to_host_file_cmd=$lt_cv_to_host_file_cmd
+AC_MSG_RESULT([$lt_cv_to_host_file_cmd])
+_LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd],
+         [0], [convert $build file names to $host format])dnl
+
+AC_MSG_CHECKING([how to convert $build file names to toolchain format])
+AC_CACHE_VAL(lt_cv_to_tool_file_cmd,
+[#assume ordinary cross tools, or native build.
+lt_cv_to_tool_file_cmd=func_convert_file_noop
+case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32
+        ;;
+    esac
     ;;
-  *)
-    cat << \_LT_EOF >> "$cfgfile"
-
-# func_append var value
-# Append VALUE to the end of shell variable VAR.
-func_append ()
-{
-  eval "$[1]=\$$[1]\$[2]"
-}
-
-_LT_EOF
-    ;;
-  esac
+esac
 ])
+to_tool_file_cmd=$lt_cv_to_tool_file_cmd
+AC_MSG_RESULT([$lt_cv_to_tool_file_cmd])
+_LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd],
+         [0], [convert $build files to toolchain format])dnl
+])# _LT_PATH_CONVERSION_FUNCTIONS
Index: /issm/branches/trunk-jpl-damage/m4/ltoptions.m4
===================================================================
--- /issm/branches/trunk-jpl-damage/m4/ltoptions.m4	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/m4/ltoptions.m4	(revision 12878)
@@ -1,5 +1,6 @@
 # Helper functions for option handling.                    -*- Autoconf -*-
 #
-#   Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
+#   Copyright (C) 2004, 2005, 2007, 2008, 2009 Free Software Foundation,
+#   Inc.
 #   Written by Gary V. Vaughan, 2004
 #
@@ -8,5 +9,5 @@
 # modifications, as long as this notice is preserved.
 
-# serial 6 ltoptions.m4
+# serial 7 ltoptions.m4
 
 # This is to help aclocal find these macros, as it can't see m4_define.
@@ -126,5 +127,5 @@
 
 case $host in
-*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-cegcc*)
+*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
   AC_CHECK_TOOL(AS, as, false)
   AC_CHECK_TOOL(DLLTOOL, dlltool, false)
@@ -134,11 +135,11 @@
 
 test -z "$AS" && AS=as
-_LT_DECL([], [AS],      [0], [Assembler program])dnl
+_LT_DECL([], [AS],      [1], [Assembler program])dnl
 
 test -z "$DLLTOOL" && DLLTOOL=dlltool
-_LT_DECL([], [DLLTOOL], [0], [DLL creation program])dnl
+_LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl
 
 test -z "$OBJDUMP" && OBJDUMP=objdump
-_LT_DECL([], [OBJDUMP], [0], [Object dumper program])dnl
+_LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl
 ])# win32-dll
 
@@ -326,7 +327,22 @@
 m4_define([_LT_WITH_PIC],
 [AC_ARG_WITH([pic],
-    [AS_HELP_STRING([--with-pic],
+    [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@],
 	[try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
-    [pic_mode="$withval"],
+    [lt_p=${PACKAGE-default}
+    case $withval in
+    yes|no) pic_mode=$withval ;;
+    *)
+      pic_mode=default
+      # Look at the argument we got.  We use all the common list separators.
+      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      for lt_pkg in $withval; do
+	IFS="$lt_save_ifs"
+	if test "X$lt_pkg" = "X$lt_p"; then
+	  pic_mode=yes
+	fi
+      done
+      IFS="$lt_save_ifs"
+      ;;
+    esac],
     [pic_mode=default])
 
Index: /issm/branches/trunk-jpl-damage/m4/ltversion.m4
===================================================================
--- /issm/branches/trunk-jpl-damage/m4/ltversion.m4	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/m4/ltversion.m4	(revision 12878)
@@ -8,15 +8,15 @@
 # modifications, as long as this notice is preserved.
 
-# Generated from ltversion.in.
+# @configure_input@
 
-# serial 3017 ltversion.m4
+# serial 3337 ltversion.m4
 # This file is part of GNU Libtool
 
-m4_define([LT_PACKAGE_VERSION], [2.2.6b])
-m4_define([LT_PACKAGE_REVISION], [1.3017])
+m4_define([LT_PACKAGE_VERSION], [2.4.2])
+m4_define([LT_PACKAGE_REVISION], [1.3337])
 
 AC_DEFUN([LTVERSION_VERSION],
-[macro_version='2.2.6b'
-macro_revision='1.3017'
+[macro_version='2.4.2'
+macro_revision='1.3337'
 _LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
 _LT_DECL(, macro_revision, 0)
Index: /issm/branches/trunk-jpl-damage/m4/lt~obsolete.m4
===================================================================
--- /issm/branches/trunk-jpl-damage/m4/lt~obsolete.m4	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/m4/lt~obsolete.m4	(revision 12878)
@@ -1,5 +1,5 @@
 # lt~obsolete.m4 -- aclocal satisfying obsolete definitions.    -*-Autoconf-*-
 #
-#   Copyright (C) 2004, 2005, 2007 Free Software Foundation, Inc.
+#   Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc.
 #   Written by Scott James Remnant, 2004.
 #
@@ -8,5 +8,5 @@
 # modifications, as long as this notice is preserved.
 
-# serial 4 lt~obsolete.m4
+# serial 5 lt~obsolete.m4
 
 # These exist entirely to fool aclocal when bootstrapping libtool.
@@ -78,5 +78,4 @@
 m4_ifndef([_LT_AC_LANG_F77],		[AC_DEFUN([_LT_AC_LANG_F77])])
 m4_ifndef([_LT_AC_LANG_GCJ],		[AC_DEFUN([_LT_AC_LANG_GCJ])])
-m4_ifndef([AC_LIBTOOL_RC],		[AC_DEFUN([AC_LIBTOOL_RC])])
 m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])])
 m4_ifndef([_LT_AC_LANG_C_CONFIG],	[AC_DEFUN([_LT_AC_LANG_C_CONFIG])])
@@ -91,2 +90,9 @@
 m4_ifndef([AC_LIBTOOL_CONFIG],		[AC_DEFUN([AC_LIBTOOL_CONFIG])])
 m4_ifndef([_LT_AC_FILE_LTDLL_C],	[AC_DEFUN([_LT_AC_FILE_LTDLL_C])])
+m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS],	[AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])])
+m4_ifndef([_LT_AC_PROG_CXXCPP],		[AC_DEFUN([_LT_AC_PROG_CXXCPP])])
+m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS],	[AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])])
+m4_ifndef([_LT_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])])
+m4_ifndef([_LT_PROG_F77],		[AC_DEFUN([_LT_PROG_F77])])
+m4_ifndef([_LT_PROG_FC],		[AC_DEFUN([_LT_PROG_FC])])
+m4_ifndef([_LT_PROG_CXX],		[AC_DEFUN([_LT_PROG_CXX])])
Index: /issm/branches/trunk-jpl-damage/scripts/DownloadExternalPackage.py
===================================================================
--- /issm/branches/trunk-jpl-damage/scripts/DownloadExternalPackage.py	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/scripts/DownloadExternalPackage.py	(revision 12878)
@@ -2,36 +2,60 @@
 # -*- coding: ISO-8859-1 -*-
 
-import os,sys
+import os,sys,re
 import urllib
+from HTMLParser import HTMLParser
+from urllib import FancyURLopener
 
-#Check inputs
-if(len(sys.argv)!=3): raise NameError('usage: ./DownloadExternalPackage.py URL localfile')
+# Start class myHTMLParser
+class MyHTMLParser(HTMLParser):
 
-url=sys.argv[1];
+    def __init__(self, pattern):
+        HTMLParser.__init__(self)
+        self.matcher = re.compile(pattern) 
+        self.targets = []
+
+    def handle_starttag(self, tag, attrs):
+        for i in attrs:
+            if "href" == i[0] and str(self.matcher.match(i[1])) != "None":
+                self.targets.append(i[1])
+# End class myHTMLParser
+
+pivot = sys.argv[1].rfind("/")
+url = (sys.argv[1])[:pivot]
 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()
+pivot += 1;
+find = (sys.argv[1])[pivot:];
+print "Looking for " + find
+pattern = find + "[\w.-]*(\.tar\.gz|tar\.gz2|tgz|zip|exe)?"
+parser = MyHTMLParser(pattern)
 
-#Try to download from url
-httpfail=-1
-try:
-	print "Fetching %s" % localFile
-	urllib.urlretrieve(url,localFile)
-	httpfail=0
-except Exception, e:
-	httpfail=1
+urlObject = FancyURLopener()
+obj = urlObject.open(url)
+parser.feed(obj.read())
 
-#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)
+if len(parser.targets) > 1:
+    print "Could not resolve your download due to the number of hits."
+    print "Refine your search."
+    for i in parser.targets:
+        print i
+
+elif len(parser.targets) == 1:
+    url += "/" + parser.targets[0]
+    if os.path.exists(localFile): 
+        print "File "+ localFile +" already exists and will not be downloaded..."
+    elif parser.targets[0] == localFile:
+        urllib.urlretrieve(url, localFile)
+        print "Found: " + parser.targets[0]
+    elif parser.matcher.match(localFile) != "None":
+        urllib.urlretrieve(url,parser.targets[0]);
+        print "Found: " + parser.targets[0]
+    else:
+        urllib.urlretrieve(url, parser.targets[0]);
+        print "WARNING: the file found \'" + parser.targets[0] + "\' does not match \'" + localFile + "\'"
+        print "Ensure the downloaded version is suitable."
+
+else:
+    print "No matches found!"
+
+obj.close()
Index: /issm/branches/trunk-jpl-damage/scripts/automakererun.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/scripts/automakererun.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/scripts/automakererun.sh	(revision 12878)
@@ -3,39 +3,9 @@
 #  archive.
 
+# As it turns out, the autoreconf script provided by Autotools
+# encompasses the functionality of this script. As such, the 
+# following two lines will replace the remainder of the script.
+# If all goes well, then the script will be shortened in the future.
 
- ACLOCAL="$ISSM_DIR/externalpackages/automake/install/bin/aclocal"
-AUTOCONF="$ISSM_DIR/externalpackages/autoconf/install/bin/autoconf"
-AUTOHEAD="$ISSM_DIR/externalpackages/autoconf/install/bin/autoheader"
-AUTOMAKE="$ISSM_DIR/externalpackages/automake/install/bin/automake"
-
-echo "removing config.cach"
-rm -rf config.cach
-rm -rf aclocal.m4
-
-if [ ! -f "$ACLOCAL" ]
-then echo "issm aclocal not found, calling default aclocal" 
-	aclocal -I m4
-else echo "Calling aclocal" 
-	$ACLOCAL -I m4
-fi
-
-if [ ! -f "$AUTOCONF" ]
-then echo "issm autoconf not found, calling default aclocal" 
-	autoconf
-else echo "Calling autoconf" 
-	$AUTOCONF
-fi
-
-if [ ! -f "$AUTOHEAD" ]
-then echo "issm autoheader not found, calling default aclocal" 
-	autoheader
-else echo "Calling autoheader" 
-	$AUTOHEAD
-fi
-
-if [ ! -f "$AUTOMAKE" ]
-then echo "issm automake  not found, calling default aclocal" 
-	automake
-else echo "Calling automake " 
-	$AUTOMAKE -a
-fi
+cd $ISSM_DIR
+autoreconf -iv -I m4
Index: /issm/branches/trunk-jpl-damage/scripts/getloc.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/scripts/getloc.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/scripts/getloc.sh	(revision 12878)
@@ -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-ext=exp --exclude-lang=make --out=temp
+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
 cat temp
 ./cloc2html.py
Index: /issm/branches/trunk-jpl-damage/scripts/report.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/scripts/report.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/scripts/report.sh	(revision 12878)
@@ -19,4 +19,5 @@
 #Process matlab_log.log
 cat matlab_log.log        | egrep 'ERROR|SUCCESS|FAILURE' | grep -v "PETSC" | sed -e "s/>/\&gt;/g" | sed -e "s/</\&lt;/g" > matlab.log
+cat matlab.log        | grep -v "SUCCESS" > matlab_short.log
 cat matlab_log.log        | grep "PETSC" | sed -e "s/>/\&gt;/g" | sed -e "s/</\&lt;/g" > petscerror.log
 NUM_TOT=`wc -l matlab.log | awk '{print $1}'`
@@ -48,10 +49,19 @@
 BODY_FONTL=`echo $BODY_FONT | sed -e "s/style=\"/style=\"text-align:left; /g"`
 
-#create some variables
-if [ $(ls -1 $ISSM_DIR/bin | wc -l) -le 20 ];
-then
+#Did installation work?
+if [ $(ls -1 $ISSM_DIR/bin | wc -l) -le 20 ]; then
 	IS_INSTALL=0
 else
 	IS_INSTALL=1
+fi
+
+#display table ONLY if installation worked and there has been at leat one FAILURE or ERROR
+IS_TABLE=0
+if [ $IS_INSTALL -eq 1 ]; then
+	if [ $NUM_TOT -gt 1 ]; then
+		if [ $NUM_SUC -ne $NUM_TOT  ]; then
+			IS_TABLE=1
+		fi
+	fi
 fi
 
@@ -96,7 +106,7 @@
 
 #update status
-if [ $IS_INSTALL -eq 1 ]
-then
-	if [ $CRASH -eq 0 ]
+if [ $IS_INSTALL -eq 1 ];
+then
+	if [ $CRASH -eq 0 ];
 	then
 		cat summary.html | sed -e "s/STATUS/<span style=\"color:#008000\">all test desks have been run<\/span>/g" > summary2.html
@@ -110,5 +120,5 @@
 
 #report table
-if [ $IS_INSTALL -eq 1 ];
+if [ $IS_TABLE -eq 1 ];
 then
 	cat << END > content.html
@@ -122,5 +132,5 @@
 <th $(echo $BODY_FONT)>Field checked</th>
 </tr>
-$(cat matlab.log | while read line
+$(cat matlab_short.log | while read line
   do
 	  echo "<tr>"
@@ -137,7 +147,7 @@
 		  echo $line | awk -v FONTC="$FONTC" -v FONTL="$FONTL" '
 		  { printf("<td %s id=FAILURE>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n\n",FONTL,$1,FONTC,$3,FONTC,$6,FONTL,$9,FONTL,$11);}
-			  '; 
-
-		  else
+		  '; 
+
+	  else
 
 		  #SUCCESS
@@ -146,18 +156,16 @@
 			  FONTC=$(echo "$BODY_FONTC bgcolor=#ddffdd")
 			  FONTL=$(echo "$BODY_FONTL bgcolor=#ddffdd")
+			  #do not write anything
 		  #ERROR
 		  else
 			  FONTC=$(echo "$BODY_FONTC bgcolor=#ffdddd id=ERROR")
 			  FONTL=$(echo "$BODY_FONTL bgcolor=#ffdddd")
+			  echo $line | awk -v FONTC="$FONTC" -v FONTL="$FONTL" '
+			  { printf("<td %s>%s</td>\n<td %s>%s%s%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n\n",FONTL,$1,FONTL,$3,$4,$5,FONTC,$8,FONTL,$11,FONTL,$13);}
+			  '; 
 		  fi
 
-
-		  echo $line | awk -v FONTC="$FONTC" -v FONTL="$FONTL" '
-		  { printf("<td %s>%s</td>\n<td %s>%s%s%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n<td %s>%s</td>\n\n",FONTL,$1,FONTL,$3,$4,$5,FONTC,$8,FONTL,$11,FONTL,$13);}
-			  '; 
 	  fi
-
 	  echo "</tr>"
-
   done
 	  )
Index: /issm/branches/trunk-jpl-damage/src/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-damage/src/Makefile.am	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/Makefile.am	(revision 12878)
@@ -1,2 +1,2 @@
-EXTRA_DIST =  perl  pro 
-SUBDIRS = c modules m  py
+EXTRA_DIST =  perl  pro  py
+SUBDIRS = c modules m
Index: /issm/branches/trunk-jpl-damage/src/ad/todo
===================================================================
--- /issm/branches/trunk-jpl-damage/src/ad/todo	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/ad/todo	(revision 12878)
@@ -29,2 +29,16 @@
 amatrix will be used in adolc. pmatrix will be used in Petsc routines. Matrix will 
 have routines to map one into the other.
+
+
+Ad: 
+Eric: 
+Create ISSM namespace.
+Make Matrix Assembly one homogeneous block.
+Make Validation suite for Jean for his prognostic capabilities.
+Jean: 
+typedef all double to ISSM_DOUBLE 
+
+Create an alloc layer with template functions for new and delete.
+Check that the new code  is modular --without-kml, options are up to date.
+
+Replace memcpy, realloc with x layers.  Replace all calls to malloc and free in the code.
Index: /issm/branches/trunk-jpl-damage/src/android/ISSM_App/.classpath
===================================================================
--- /issm/branches/trunk-jpl-damage/src/android/ISSM_App/.classpath	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/android/ISSM_App/.classpath	(revision 12878)
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="src" path="gen"/>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+	<classpathentry kind="output" path="bin/classes"/>
+</classpath>
Index: /issm/branches/trunk-jpl-damage/src/android/ISSM_App/.project
===================================================================
--- /issm/branches/trunk-jpl-damage/src/android/ISSM_App/.project	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/android/ISSM_App/.project	(revision 12878)
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>ISSM_App</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ApkBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>
Index: /issm/branches/trunk-jpl-damage/src/android/ISSM_App/AndroidManifest.xml
===================================================================
--- /issm/branches/trunk-jpl-damage/src/android/ISSM_App/AndroidManifest.xml	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/android/ISSM_App/AndroidManifest.xml	(revision 12878)
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="issm.app"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk android:minSdkVersion="14" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name" >
+        <activity
+            android:name=".ISSM_AppActivity"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/branches/trunk-jpl-damage/src/android/ISSM_App/gen/issm/app/BuildConfig.java
===================================================================
--- /issm/branches/trunk-jpl-damage/src/android/ISSM_App/gen/issm/app/BuildConfig.java	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/android/ISSM_App/gen/issm/app/BuildConfig.java	(revision 12878)
@@ -0,0 +1,6 @@
+/** Automatically generated file. DO NOT MODIFY */
+package issm.app;
+
+public final class BuildConfig {
+    public final static boolean DEBUG = true;
+}
Index: /issm/branches/trunk-jpl-damage/src/android/ISSM_App/gen/issm/app/R.java
===================================================================
--- /issm/branches/trunk-jpl-damage/src/android/ISSM_App/gen/issm/app/R.java	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/android/ISSM_App/gen/issm/app/R.java	(revision 12878)
@@ -0,0 +1,27 @@
+/* AUTO-GENERATED FILE.  DO NOT MODIFY.
+ *
+ * This class was automatically generated by the
+ * aapt tool from the resource data it found.  It
+ * should not be modified by hand.
+ */
+
+package issm.app;
+
+public final class R {
+    public static final class attr {
+    }
+    public static final class drawable {
+        public static final int ic_launcher=0x7f020000;
+    }
+    public static final class id {
+        public static final int editText2=0x7f050000;
+        public static final int seekBar2=0x7f050001;
+    }
+    public static final class layout {
+        public static final int main=0x7f030000;
+    }
+    public static final class string {
+        public static final int app_name=0x7f040001;
+        public static final int hello=0x7f040000;
+    }
+}
Index: /issm/branches/trunk-jpl-damage/src/android/ISSM_App/proguard-project.txt
===================================================================
--- /issm/branches/trunk-jpl-damage/src/android/ISSM_App/proguard-project.txt	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/android/ISSM_App/proguard-project.txt	(revision 12878)
@@ -0,0 +1,20 @@
+# To enable ProGuard in your project, edit project.properties
+# to define the proguard.config property as described in that file.
+#
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in ${sdk.dir}/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the ProGuard
+# include property in project.properties.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
Index: /issm/branches/trunk-jpl-damage/src/android/ISSM_App/project.properties
===================================================================
--- /issm/branches/trunk-jpl-damage/src/android/ISSM_App/project.properties	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/android/ISSM_App/project.properties	(revision 12878)
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-14
Index: /issm/branches/trunk-jpl-damage/src/android/ISSM_App/res/layout/main.xml
===================================================================
--- /issm/branches/trunk-jpl-damage/src/android/ISSM_App/res/layout/main.xml	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/android/ISSM_App/res/layout/main.xml	(revision 12878)
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="horizontal" >
+
+    <TextView
+        android:id="@+id/editText2"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_weight="1"
+        android:ems="10" android:translationX="0.5in" android:translationY="1in"/>
+    
+    <SeekBar
+        android:id="@+id/seekBar2"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_weight="1"
+        android:clickable="true"
+        android:max="100" android:translationY="2in" android:translationX="-0.5in"/>
+
+</LinearLayout>
Index: /issm/branches/trunk-jpl-damage/src/android/ISSM_App/res/values/strings.xml
===================================================================
--- /issm/branches/trunk-jpl-damage/src/android/ISSM_App/res/values/strings.xml	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/android/ISSM_App/res/values/strings.xml	(revision 12878)
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    <string name="hello">Hello World, ISSM_AppActivity!</string>
+    <string name="app_name">ISSM_App</string>
+
+</resources>
Index: /issm/branches/trunk-jpl-damage/src/android/ISSM_App/src/issm/app/ISSM_AppActivity.java
===================================================================
--- /issm/branches/trunk-jpl-damage/src/android/ISSM_App/src/issm/app/ISSM_AppActivity.java	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/android/ISSM_App/src/issm/app/ISSM_AppActivity.java	(revision 12878)
@@ -0,0 +1,29 @@
+package issm.app;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.TextView;
+import android.widget.SeekBar;
+
+public class ISSM_AppActivity extends Activity implements OnClickListener
+{
+	private SeekBar sb;
+	private TextView tv;
+	
+    public void onCreate(Bundle savedInstanceState) 
+    {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.main);
+        sb = (SeekBar)findViewById(R.id.seekBar2);
+        tv = (TextView)findViewById(R.id.editText2);
+        tv.setText("Current Progress: " + sb.getProgress());
+        sb.setOnClickListener(this);
+    }
+
+	public void onClick(View v)
+	{
+		tv.setText("Current Progress: " + sb.getProgress());
+	}
+}
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Constraints.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Constraints.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Constraints.cpp	(revision 12878)
@@ -4,5 +4,5 @@
  */
 
-/*Headers: {{{1*/
+/*Headers: {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -25,5 +25,5 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Constraints::Constraints(){{{1*/
+/*FUNCTION Constraints::Constraints(){{{*/
 Constraints::Constraints(){
 	enum_type=ConstraintsEnum;
@@ -31,5 +31,5 @@
 }
 /*}}}*/
-/*FUNCTION Constraints::~Constraints(){{{1*/
+/*FUNCTION Constraints::~Constraints(){{{*/
 Constraints::~Constraints(){
 	return;
@@ -38,5 +38,5 @@
 
 /*Numerics: */
-/*FUNCTION Constraints::NumberOfConstraints{{{1*/
+/*FUNCTION Constraints::NumberOfConstraints{{{*/
 int Constraints::NumberOfConstraints(void){
 
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Constraints.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Constraints.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Constraints.h	(revision 12878)
@@ -21,9 +21,9 @@
 	public:
 
-		/*constructors, destructors: {{{1*/
+		/*constructors, destructors: {{{*/
 		Constraints();
 		~Constraints();
 		/*}}}*/
-		/*numerics: {{{1*/
+		/*numerics: {{{*/
 		int   NumberOfConstraints(void);
 		/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Container.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Container.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Container.h	(revision 12878)
@@ -6,4 +6,5 @@
 #define  _CONTAINER_CONTAINER_H_
 
+#include "../include/include.h"
 #include "./DataSet.h"
 #include "./Constraints.h"
@@ -17,4 +18,5 @@
 #include "./Results.h"
 #include "./Vertices.h"
+#include "./Observations.h"
 
 #endif //ifndef _CONTAINER_H_
Index: /issm/branches/trunk-jpl-damage/src/c/Container/DataSet.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/DataSet.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/DataSet.cpp	(revision 12878)
@@ -4,5 +4,5 @@
  */
 
-/*Headers: {{{1*/
+/*Headers: {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -11,4 +11,5 @@
 #endif
 
+#include <cstring>
 #include <vector>
 #include <functional>
@@ -17,5 +18,5 @@
 
 #include "./DataSet.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -27,5 +28,5 @@
 
 /*Constructors/Destructors*/
-/*FUNCTION DataSet::DataSet(){{{1*/
+/*FUNCTION DataSet::DataSet(){{{*/
 DataSet::DataSet(){
 	
@@ -36,5 +37,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::DataSet(int dataset_enum){{{1*/
+/*FUNCTION DataSet::DataSet(int dataset_enum){{{*/
 DataSet::DataSet(int dataset_enum){
 	enum_type=dataset_enum;
@@ -46,5 +47,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::Copy{{{1*/
+/*FUNCTION DataSet::Copy{{{*/
 DataSet*   DataSet::Copy(void){
 
@@ -58,10 +59,10 @@
 	copy->presorted=presorted;
 	if(sorted_ids){
-		copy->sorted_ids=(int*)xmalloc(objects.size()*sizeof(int));
-		memcpy(copy->sorted_ids,sorted_ids,objects.size()*sizeof(int));
+		copy->sorted_ids=xNew<int>(objects.size());
+		xMemCpy<int>(copy->sorted_ids,sorted_ids,objects.size());
 	}
 	if(id_offsets){
-		copy->id_offsets=(int*)xmalloc(objects.size()*sizeof(int));
-		memcpy(copy->id_offsets,id_offsets,objects.size()*sizeof(int));
+		copy->id_offsets=xNew<int>(objects.size());
+		xMemCpy<int>(copy->id_offsets,id_offsets,objects.size());
 	}
 
@@ -76,14 +77,14 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::~DataSet{{{1*/
+/*FUNCTION DataSet::~DataSet{{{*/
 DataSet::~DataSet(){
 	clear();
-	xfree((void**)&sorted_ids);
-	xfree((void**)&id_offsets);
+	xDelete<int>(sorted_ids);
+	xDelete<int>(id_offsets);
 }
 /*}}}*/
 
 /*Specific methods*/
-/*FUNCTION DataSet::AddObject{{{1*/
+/*FUNCTION DataSet::AddObject{{{*/
 int  DataSet::AddObject(Object* object){
 
@@ -93,5 +94,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::clear{{{1*/
+/*FUNCTION DataSet::clear{{{*/
 void  DataSet::clear(){
 
@@ -111,5 +112,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::DeleteObject{{{1*/
+/*FUNCTION DataSet::DeleteObject{{{*/
 int  DataSet::DeleteObject(Object* object){
 
@@ -126,5 +127,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::DeepEcho{{{1*/
+/*FUNCTION DataSet::DeepEcho{{{*/
 void DataSet::DeepEcho(){
 
@@ -132,7 +133,7 @@
 	vector<Object*>::iterator object;
 
-	if(this==NULL)_error_(" trying to echo a NULL dataset");
-
-	_printf_(true,"DataSet echo: %i objects\n",objects.size());
+	if(this==NULL)_error2_("trying to echo a NULL dataset");
+
+	_pprintLine_("DataSet echo: " << objects.size() << " objects");
 
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
@@ -144,12 +145,12 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::Echo{{{1*/
+/*FUNCTION DataSet::Echo{{{*/
 void DataSet::Echo(){
 
 	vector<Object*>::iterator object;
 
-	if(this==NULL)_error_(" trying to echo a NULL dataset");
-
-	_printf_(true,"DataSet echo: %i objects\n",objects.size());
+	if(this==NULL)_error2_("trying to echo a NULL dataset");
+
+	_pprintLine_("DataSet echo: " << objects.size() << " objects");
 
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
@@ -162,10 +163,10 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::GetEnum(){{{1*/
+/*FUNCTION DataSet::GetEnum(){{{*/
 int  DataSet::GetEnum(){
 	return enum_type;
 }
 /*}}}*/
-/*FUNCTION DataSet::GetEnum(int offset){{{1*/
+/*FUNCTION DataSet::GetEnum(int offset){{{*/
 int   DataSet::GetEnum(int offset){
 
@@ -174,5 +175,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::GetObjectByOffset{{{1*/
+/*FUNCTION DataSet::GetObjectByOffset{{{*/
 Object* DataSet::GetObjectByOffset(int offset){
 
@@ -185,5 +186,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::GetObjectById{{{1*/
+/*FUNCTION DataSet::GetObjectById{{{*/
 Object* DataSet::GetObjectById(int* poffset,int eid){
 
@@ -193,9 +194,9 @@
 
 	_assert_(this);
-	if(!sorted)_error_(" trying to binary search on a non-sorted dataset!");
+	if(!sorted)_error2_("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 %i in DataSet %s",eid,EnumToStringx(enum_type));
+		_error2_("could not find object with id " << eid << " in DataSet " << EnumToStringx(enum_type));
 	}
 
@@ -210,5 +211,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::Presort{{{1*/
+/*FUNCTION DataSet::Presort{{{*/
 void DataSet::Presort(){
 
@@ -220,10 +221,10 @@
 
 		/*Delete existing ids*/
-		xfree((void**)&sorted_ids);
-		xfree((void**)&id_offsets);
+		xDelete<int>(sorted_ids);
+		xDelete<int>(id_offsets);
 
 		/*Allocate new ids*/
-		sorted_ids=(int*)xmalloc(objects.size()*sizeof(int));
-		id_offsets=(int*)xmalloc(objects.size()*sizeof(int));
+		sorted_ids=xNew<int>(objects.size());
+		id_offsets=xNew<int>(objects.size());
 
 		/*Build id_offsets and sorted_ids*/
@@ -238,5 +239,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::SetSorting{{{1*/
+/*FUNCTION DataSet::SetSorting{{{*/
 void DataSet::SetSorting(int* in_sorted_ids,int* in_id_offsets){
 
@@ -246,5 +247,5 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::Size{{{1*/
+/*FUNCTION DataSet::Size{{{*/
 int  DataSet::Size(void){
 	_assert_(this!=NULL);
@@ -253,11 +254,11 @@
 }
 /*}}}*/
-/*FUNCTION DataSet::Sort{{{1*/
+/*FUNCTION DataSet::Sort{{{*/
 void DataSet::Sort(){
 
 	/*Only sort if we are not already sorted: */
 	if(!sorted){
-		_error_(" not implemented yet!");
-	}
-}
-/*}}}*/
+		_error2_("not implemented yet!");
+	}
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/Container/DataSet.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/DataSet.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/DataSet.h	(revision 12878)
@@ -7,10 +7,9 @@
 
 #include <vector>
-#include "../objects/Object.h"
+#include "../classes/objects/Object.h"
 #include "../toolkits/toolkits.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
 
 /*forward declarations */
-
 class Elements;
 class Loads;
@@ -39,10 +38,10 @@
 		int*            id_offsets;
 
-		/*constructors, destructors: {{{1*/
+		/*constructors, destructors: {{{*/
 		DataSet();
 		DataSet(int enum_type);
 		~DataSet();
 		/*}}}*/
-		/*management: {{{1*/
+		/*management: {{{*/
 		int   GetEnum();
 		int   GetEnum(int offset);
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Elements.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Elements.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Elements.cpp	(revision 12878)
@@ -4,5 +4,5 @@
  */
 
-/*Headers: {{{1*/
+/*Headers: {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -25,5 +25,5 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Elements::Elements(){{{1*/
+/*FUNCTION Elements::Elements(){{{*/
 Elements::Elements(){
 	enum_type=MeshElementsEnum;
@@ -31,5 +31,5 @@
 }
 /*}}}*/
-/*FUNCTION Elements::~Elements(){{{1*/
+/*FUNCTION Elements::~Elements(){{{*/
 Elements::~Elements(){
 	return;
@@ -38,5 +38,5 @@
 
 /*Object management*/
-/*FUNCTION Elements::Configure{{{1*/
+/*FUNCTION Elements::Configure{{{*/
 void Elements::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
 
@@ -53,5 +53,5 @@
 }
 /*}}}*/
-/*FUNCTION Elements::ProcessResultsUnits{{{1*/
+/*FUNCTION Elements::ProcessResultsUnits{{{*/
 void Elements::ProcessResultsUnits(void){
 
@@ -63,5 +63,5 @@
 }
 /*}}}*/
-/*FUNCTION Elements::DeleteResults{{{1*/
+/*FUNCTION Elements::DeleteResults{{{*/
 void Elements::DeleteResults(void){
 	
@@ -72,5 +72,5 @@
 }
 /*}}}*/
-/*FUNCTION Elements::ResultsToPatch{{{1*/
+/*FUNCTION Elements::ResultsToPatch{{{*/
 Patch* Elements::ResultsToPatch(void){ 
 
@@ -148,5 +148,5 @@
 }
 /*}}}*/
-/*FUNCTION Elements::SetCurrentConfiguration{{{1*/
+/*FUNCTION Elements::SetCurrentConfiguration{{{*/
 void Elements::SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
 
@@ -163,5 +163,5 @@
 }
 /*}}}*/
-/*FUNCTION Elements::ToResults{{{1*/
+/*FUNCTION Elements::ToResults{{{*/
 void Elements::ToResults(Results* results,Parameters* parameters){
 
@@ -173,6 +173,6 @@
 	int    *resultssizes  = NULL;
 	int    *resultssteps  = NULL;
-	double *resultstimes = NULL;
-	double *vector_serial= NULL;
+	IssmDouble *resultstimes = NULL;
+	IssmDouble *vector_serial= NULL;
 	Vector*     vector       = NULL;
 	bool   io_gather;
@@ -203,5 +203,5 @@
 		/*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??");
+			if(this->Size()==0) _error2_("Cannot write results because there is no element??");
 			Element* element=(Element*)this->GetObjectByOffset(0);
 			element->ListResultsInfo(&resultsenums,&resultssizes,&resultstimes,&resultssteps,&numberofresults);
@@ -215,8 +215,8 @@
 		#ifdef _HAVE_MPI_
 		if(my_rank!=minrank){
-			resultsenums=(int*)xmalloc(numberofresults*sizeof(int));
-			resultssizes=(int*)xmalloc(numberofresults*sizeof(int));
-			resultstimes=(double*)xmalloc(numberofresults*sizeof(double));
-			resultssteps=(int*)xmalloc(numberofresults*sizeof(int));
+			resultsenums=xNew<int>(numberofresults);
+			resultssizes=xNew<int>(numberofresults);
+			resultstimes=xNew<IssmDouble>(numberofresults);
+			resultssteps=xNew<int>(numberofresults);
 		}
 		MPI_Bcast(resultsenums,numberofresults,MPI_INT,minrank,MPI_COMM_WORLD);
@@ -232,10 +232,10 @@
 			if(resultssizes[i]==P1Enum)      vectorsize=numberofvertices;
 			else if(resultssizes[i]==P0Enum) vectorsize=numberofelements;
-			else _error_("Unkown result size: %s",EnumToStringx(resultssizes[i]));
+			else _error2_("Unkown result size: " << EnumToStringx(resultssizes[i]));
 			vector=new Vector(vectorsize);
 
 			for(int j=0;j<this->Size();j++){
 				Element* element=(Element*)this->GetObjectByOffset(j);
-				element->GetVectorFromResults(vector,i,resultssizes[i]);
+				element->GetVectorFromResults(vector,i,resultsenums[i],resultssizes[i]);
 			}
 			vector->Assemble();
@@ -250,5 +250,5 @@
 			/*clean up*/
 			xdelete(&vector);
-			xfree((void**)&vector_serial);
+			xDelete<IssmDouble>(vector_serial);
 		}
 	}
@@ -269,12 +269,12 @@
 
 	/*Free ressources:*/
-	xfree((void**)&resultsenums);
-	xfree((void**)&resultssizes);
-	xfree((void**)&resultstimes);
-	xfree((void**)&resultssteps);
+	xDelete<int>(resultsenums);
+	xDelete<int>(resultssizes);
+	xDelete<int>(resultssteps);
+	xDelete<IssmDouble>(resultstimes);
 	delete patch;
 }
 /*}}}*/
-/*FUNCTION Elements::NumberOfElements{{{1*/
+/*FUNCTION Elements::NumberOfElements{{{*/
 int Elements::NumberOfElements(void){
 
@@ -292,5 +292,5 @@
 }
 /*}}}*/
-/*FUNCTION Elements::InputCopy{{{1*/
+/*FUNCTION Elements::InputCopy{{{*/
 void Elements::InputDuplicate(int input_enum,int output_enum){
 
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Elements.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Elements.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Elements.h	(revision 12878)
@@ -16,14 +16,13 @@
 class Inputs;
 
-
 class Elements: public DataSet{
 
 	public:
 
-		/*constructors, destructors: {{{1*/
+		/*constructors, destructors: {{{*/
 		Elements();
 		~Elements();
 		/*}}}*/
-		/*numerics: {{{1*/
+		/*numerics: {{{*/
 		void Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
 		void DeleteResults(void);
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Inputs.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Inputs.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Inputs.cpp	(revision 12878)
@@ -4,5 +4,5 @@
  */
 
-/*Headers: {{{1*/
+/*Headers: {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -25,10 +25,10 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Inputs::Inputs(){{{1*/
+/*FUNCTION Inputs::Inputs(){{{*/
 Inputs::Inputs(){
 	return;
 }
 /*}}}*/
-/*FUNCTION Inputs::~Inputs(){{{1*/
+/*FUNCTION Inputs::~Inputs(){{{*/
 Inputs::~Inputs(){
 	return;
@@ -37,5 +37,5 @@
 
 /*Object management*/
-/*FUNCTION Inputs::GetInputValue(bool* pvalue,int enum-type){{{1*/
+/*FUNCTION Inputs::GetInputValue(bool* pvalue,int enum-type){{{*/
 void Inputs::GetInputValue(bool* pvalue,int enum_type){
 
@@ -57,5 +57,5 @@
 		/*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 %i (%s)",enum_type,EnumToStringx(enum_type));
+		_error2_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 	}
 
@@ -65,5 +65,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::GetInputValue(int* pvalue,int enum-type){{{1*/
+/*FUNCTION Inputs::GetInputValue(int* pvalue,int enum-type){{{*/
 void Inputs::GetInputValue(int* pvalue,int enum_type){
 
@@ -85,5 +85,5 @@
 		/*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 %i (%s)",enum_type,EnumToStringx(enum_type));
+		_error2_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 	}
 
@@ -93,6 +93,6 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::GetInputValue(double* pvalue,int enum-type){{{1*/
-void Inputs::GetInputValue(double* pvalue,int enum_type){
+/*FUNCTION Inputs::GetInputValue(IssmDouble* pvalue,int enum-type){{{*/
+void Inputs::GetInputValue(IssmDouble* pvalue,int enum_type){
 
 	vector<Object*>::iterator object;
@@ -113,5 +113,5 @@
 		/*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 %i (%s)",enum_type,EnumToStringx(enum_type));
+		_error2_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 	}
 
@@ -121,6 +121,6 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::GetInputAverage{{{1*/
-void Inputs::GetInputAverage(double* pvalue,int enum_type){
+/*FUNCTION Inputs::GetInputAverage{{{*/
+void Inputs::GetInputAverage(IssmDouble* pvalue,int enum_type){
 
 	vector<Object*>::iterator object;
@@ -141,5 +141,5 @@
 		/*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 %i (%s)",enum_type,EnumToStringx(enum_type));
+		_error2_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 	}
 
@@ -149,5 +149,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::AddInput{{{1*/
+/*FUNCTION Inputs::AddInput{{{*/
 int  Inputs::AddInput(Input* in_input){
 
@@ -175,5 +175,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::ChangeEnum{{{1*/
+/*FUNCTION Inputs::ChangeEnum{{{*/
 void  Inputs::ChangeEnum(int oldenumtype,int newenumtype){
 
@@ -205,6 +205,6 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::ConstrainMin{{{1*/
-void  Inputs::ConstrainMin(int constrain_enum, double minimum){
+/*FUNCTION Inputs::ConstrainMin{{{*/
+void  Inputs::ConstrainMin(int constrain_enum, IssmDouble minimum){
 	   
 	Input* constrain_input=NULL; 
@@ -213,5 +213,5 @@
 
 	/*some checks: */
-	if(!constrain_input) _error_(" input %s could not be found!",EnumToStringx(constrain_enum));
+	if(!constrain_input) _error2_("input " << EnumToStringx(constrain_enum) << " could not be found!");
 
 	/*Apply ContrainMin: */
@@ -219,9 +219,9 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::InfinityNorm{{{1*/
-double Inputs::InfinityNorm(int enumtype){
-
-	/*Output*/
-	double norm;
+/*FUNCTION Inputs::InfinityNorm{{{*/
+IssmDouble Inputs::InfinityNorm(int enumtype){
+
+	/*Output*/
+	IssmDouble norm;
 
 	/*Get input*/
@@ -240,9 +240,9 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::Max{{{1*/
-double Inputs::Max(int enumtype){
-
-	/*Output*/
-	double max;
+/*FUNCTION Inputs::Max{{{*/
+IssmDouble Inputs::Max(int enumtype){
+
+	/*Output*/
+	IssmDouble max;
 
 	/*Get input*/
@@ -254,5 +254,5 @@
 	}
 	else{
-		_error_("Input %s not found",EnumToStringx(enumtype));
+		_error2_("Input " << EnumToStringx(enumtype) << " not found");
 	}
 
@@ -261,9 +261,9 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::MaxAbs{{{1*/
-double Inputs::MaxAbs(int enumtype){
-
-	/*Output*/
-	double max;
+/*FUNCTION Inputs::MaxAbs{{{*/
+IssmDouble Inputs::MaxAbs(int enumtype){
+
+	/*Output*/
+	IssmDouble max;
 
 	/*Get input*/
@@ -275,5 +275,5 @@
 	}
 	else{
-		_error_("Input %s not found",EnumToStringx(enumtype));
+		_error2_("Input " << EnumToStringx(enumtype) << " not found");
 	}
 
@@ -282,9 +282,9 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::Min{{{1*/
-double Inputs::Min(int enumtype){
-
-	/*Output*/
-	double min;
+/*FUNCTION Inputs::Min{{{*/
+IssmDouble Inputs::Min(int enumtype){
+
+	/*Output*/
+	IssmDouble min;
 
 	/*Get input*/
@@ -296,5 +296,5 @@
 	}
 	else{
-		_error_("Input %s not found",EnumToStringx(enumtype));
+		_error2_("Input " << EnumToStringx(enumtype) << " not found");
 	}
 
@@ -303,9 +303,9 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::MinAbs{{{1*/
-double Inputs::MinAbs(int enumtype){
-
-	/*Output*/
-	double min;
+/*FUNCTION Inputs::MinAbs{{{*/
+IssmDouble Inputs::MinAbs(int enumtype){
+
+	/*Output*/
+	IssmDouble min;
 
 	/*Get input*/
@@ -317,5 +317,5 @@
 	}
 	else{
-		_error_("Input %s not found",EnumToStringx(enumtype));
+		_error2_("Input " << EnumToStringx(enumtype) << " not found");
 	}
 
@@ -324,5 +324,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::GetInput{{{1*/
+/*FUNCTION Inputs::GetInput{{{*/
 Input* Inputs::GetInput(int enum_name){
 
@@ -341,5 +341,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::DeleteInput{{{1*/
+/*FUNCTION Inputs::DeleteInput{{{*/
 int  Inputs::DeleteInput(int enum_type){
 
@@ -361,5 +361,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::DuplicateInput{{{1*/
+/*FUNCTION Inputs::DuplicateInput{{{*/
 void  Inputs::DuplicateInput(int original_enum,int new_enum){
 
@@ -369,5 +369,5 @@
 	/*Make a copy of the original input: */
 	original=(Input*)this->GetInput(original_enum);
-	if(!original)_error_("could not find input with enum: %s",EnumToStringx(original_enum)); 
+	if(!original)_error2_("could not find input with enum: " << EnumToStringx(original_enum)); 
 	copy=(Input*)original->copy();
 
@@ -379,5 +379,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::SpawnTriaInputs{{{1*/
+/*FUNCTION Inputs::SpawnTriaInputs{{{*/
 Inputs* Inputs::SpawnTriaInputs(int* indices){
 
@@ -405,6 +405,6 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::AXPY{{{1*/
-void  Inputs::AXPY(int MeshYEnum, double scalar, int MeshXEnum){
+/*FUNCTION Inputs::AXPY{{{*/
+void  Inputs::AXPY(int MeshYEnum, IssmDouble scalar, int MeshXEnum){
 	   
 	Input* xinput=NULL;
@@ -416,6 +416,6 @@
 
 	/*some checks: */
-	if(!xinput) _error_(" input %s could not be found!",EnumToStringx(MeshXEnum));
-	if(!yinput) _error_(" input %s could not be found!",EnumToStringx(MeshYEnum));
+	if(!xinput) _error2_("input " << EnumToStringx(MeshXEnum) << " could not be found!");
+	if(!yinput) _error2_("input " << EnumToStringx(MeshYEnum) << " could not be found!");
 
 	/*Apply AXPY: */
@@ -423,5 +423,5 @@
 }
 /*}}}*/
-/*FUNCTION Inputs::Configure{{{1*/
+/*FUNCTION Inputs::Configure{{{*/
 void Inputs::Configure(Parameters* parameters){
 
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Inputs.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Inputs.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Inputs.h	(revision 12878)
@@ -23,28 +23,28 @@
 	public:
 
-		/*constructors, destructors: {{{1*/
+		/*constructors, destructors: {{{*/
 		Inputs();
 		~Inputs();
 
 		/*}}}*/
-		/*numerics: {{{1*/
+		/*numerics: {{{*/
 		int     AddInput(Input* in_input);
 		void    ChangeEnum(int enumtype,int new_enumtype);
-		void    ConstrainMin(int constrain_enum, double minimum);
+		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, double scalar, int MeshXEnum);
-		double  InfinityNorm(int enumtype);
-		double  Max(int enumtype);
-		double  MaxAbs(int enumtype);
-		double  Min(int enumtype);
-		double  MinAbs(int enumtype);
+		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(double* pvalue, int enum_type);
+		void GetInputAverage(IssmDouble* pvalue, int enum_type);
 		void GetInputValue(bool* pvalue,int enum_type);
 		void GetInputValue(int* pvalue,int enum_type);
-		void GetInputValue(double* pvalue,int enum_type);
+		void GetInputValue(IssmDouble* pvalue,int enum_type);
 
 		void Configure(Parameters* parameters);
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Loads.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Loads.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Loads.cpp	(revision 12878)
@@ -4,5 +4,5 @@
  */
 
-/*Headers: {{{1*/
+/*Headers: {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -25,5 +25,5 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Loads::Loads(){{{1*/
+/*FUNCTION Loads::Loads(){{{*/
 Loads::Loads(){
 	enum_type=LoadsEnum;
@@ -31,5 +31,5 @@
 }
 /*}}}*/
-/*FUNCTION Loads::~Loads(){{{1*/
+/*FUNCTION Loads::~Loads(){{{*/
 Loads::~Loads(){
 	return;
@@ -38,5 +38,5 @@
 
 /*Numerics:*/
-/*FUNCTION Loads::Configure{{{1*/
+/*FUNCTION Loads::Configure{{{*/
 void Loads::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
 
@@ -53,5 +53,5 @@
 }
 /*}}}*/
-/*FUNCTION Loads::NumberOfLoads{{{1*/
+/*FUNCTION Loads::NumberOfLoads{{{*/
 int Loads::NumberOfLoads(void){
 
@@ -74,5 +74,5 @@
 }
 /*}}}*/
-/*FUNCTION Loads::SetCurrentConfiguration{{{1*/
+/*FUNCTION Loads::SetCurrentConfiguration{{{*/
 void Loads::SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
 
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Loads.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Loads.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Loads.h	(revision 12878)
@@ -20,9 +20,9 @@
 	public:
 
-		/*constructors, destructors: {{{1*/
+		/*constructors, destructors: {{{*/
 		Loads();
 		~Loads();
 		/*}}}*/
-		/*numerics: {{{1*/
+		/*numerics: {{{*/
 		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
 		int   NumberOfLoads(void);
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Materials.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Materials.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Materials.cpp	(revision 12878)
@@ -4,5 +4,5 @@
  */
 
-/*Headers: {{{1*/
+/*Headers: {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -25,5 +25,5 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Materials::Materials(){{{1*/
+/*FUNCTION Materials::Materials(){{{*/
 Materials::Materials(){
 	enum_type=MaterialsEnum;
@@ -31,5 +31,5 @@
 }
 /*}}}*/
-/*FUNCTION Materials::~Materials(){{{1*/
+/*FUNCTION Materials::~Materials(){{{*/
 Materials::~Materials(){
 	return;
@@ -38,5 +38,5 @@
 
 /*Object management*/
-/*FUNCTION Materials::Configure{{{1*/
+/*FUNCTION Materials::Configure{{{*/
 void Materials::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
 
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Materials.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Materials.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Materials.h	(revision 12878)
@@ -19,9 +19,9 @@
 	public:
 
-		/*constructors, destructors: {{{1*/
+		/*constructors, destructors: {{{*/
 		Materials();
 		~Materials();
 		/*}}}*/
-		/*numerics: {{{1*/
+		/*numerics: {{{*/
 		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
 		/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Nodes.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Nodes.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Nodes.cpp	(revision 12878)
@@ -4,5 +4,5 @@
  */
 
-/*Headers: {{{1*/
+/*Headers: {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -25,5 +25,5 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Nodes::Nodes(){{{1*/
+/*FUNCTION Nodes::Nodes(){{{*/
 Nodes::Nodes(){
 	enum_type=NodesEnum;
@@ -31,5 +31,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::~Nodes(){{{1*/
+/*FUNCTION Nodes::~Nodes(){{{*/
 Nodes::~Nodes(){
 	return;
@@ -38,5 +38,5 @@
 
 /*Numerics*/
-/*FUNCTION Nodes::Configure{{{1*/
+/*FUNCTION Nodes::Configure{{{*/
 void Nodes::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
 
@@ -53,5 +53,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::DistributeDofs{{{1*/
+/*FUNCTION Nodes::DistributeDofs{{{*/
 void  Nodes::DistributeDofs(int analysis_type,int setenum){
 
@@ -84,5 +84,5 @@
 	 * cpus by the total last dofs of the previus cpu, starting from 0.
 	 * First: get number of dofs for each cpu*/
-	alldofcount=(int*)xmalloc(num_procs*sizeof(int));
+	alldofcount=xNew<int>(num_procs);
 	#ifdef _HAVE_MPI_
 	MPI_Gather(&dofcount,1,MPI_INT,alldofcount,1,MPI_INT,0,MPI_COMM_WORLD);
@@ -113,6 +113,6 @@
 	numnodes=this->NumberOfNodes(analysis_type);
 	if(numnodes*maxdofspernode){
-		truedofs=   (int*)xcalloc(numnodes*maxdofspernode,sizeof(int)); //initialize to 0, so that we can pick up the max
-		alltruedofs=(int*)xcalloc(numnodes*maxdofspernode,sizeof(int));
+		truedofs=   xNewZeroInit<int>(numnodes*maxdofspernode); //initialize to 0, so that we can pick up the max
+		alltruedofs=xNewZeroInit<int>(numnodes*maxdofspernode);
 	}
 
@@ -139,10 +139,10 @@
 
 	/* Free ressources: */
-	xfree((void**)&alldofcount);
-	xfree((void**)&truedofs);
-	xfree((void**)&alltruedofs);
-}
-/*}}}*/
-/*FUNCTION Nodes::FlagClones{{{1*/
+	xDelete<int>(alldofcount);
+	xDelete<int>(truedofs);
+	xDelete<int>(alltruedofs);
+}
+/*}}}*/
+/*FUNCTION Nodes::FlagClones{{{*/
 void  Nodes::FlagClones(int analysis_type){
 
@@ -158,6 +158,6 @@
 
 	/*Allocate ranks: */
-	ranks=(int*)xmalloc(numnodes*sizeof(int));
-	minranks=(int*)xmalloc(numnodes*sizeof(int));
+	ranks=xNew<int>(numnodes);
+	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.
@@ -190,10 +190,10 @@
 
 	/*Free ressources: */
-	xfree((void**)&ranks); 
-	xfree((void**)&minranks);
-
-}
-/*}}}*/
-/*FUNCTION Nodes::MaxNumDofs{{{1*/
+	xDelete<int>(ranks); 
+	xDelete<int>(minranks);
+
+}
+/*}}}*/
+/*FUNCTION Nodes::MaxNumDofs{{{*/
 int   Nodes::MaxNumDofs(int analysis_type,int setenum){
 
@@ -225,5 +225,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::NumberOfDofs{{{1*/
+/*FUNCTION Nodes::NumberOfDofs{{{*/
 int   Nodes::NumberOfDofs(int analysis_type,int setenum){
 
@@ -259,5 +259,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::NumberOfNodes(){{{1*/
+/*FUNCTION Nodes::NumberOfNodes(){{{*/
 int Nodes::NumberOfNodes(void){
 
@@ -287,5 +287,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::NumberOfNodes(analysis){{{1*/
+/*FUNCTION Nodes::NumberOfNodes(analysis){{{*/
 int Nodes::NumberOfNodes(int analysis_type){
 
@@ -326,5 +326,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::Ranks{{{1*/
+/*FUNCTION Nodes::Ranks{{{*/
 void   Nodes::Ranks(int* ranks,int analysis_type){
 
@@ -352,5 +352,5 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::SetCurrentConfiguration{{{1*/
+/*FUNCTION Nodes::SetCurrentConfiguration{{{*/
 void Nodes::SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
 
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Nodes.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Nodes.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Nodes.h	(revision 12878)
@@ -13,9 +13,9 @@
 	public:
 
-		/*constructors, destructors: {{{1*/
+		/*constructors, destructors: {{{*/
 		Nodes();
 		~Nodes();
 		/*}}}*/
-		/*numerics: {{{1*/
+		/*numerics: {{{*/
 		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
 		void  DistributeDofs(int analysis_type,int SETENUM);
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Observations.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Observations.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Observations.cpp	(revision 12878)
@@ -20,5 +20,7 @@
 #include "../shared/shared.h"
 #include "../include/include.h"
+#include "../modules/modules.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
+#include "../io/io.h"
 
 using namespace std;
@@ -32,12 +34,12 @@
 }
 /*}}}*/
-/*FUNCTION Observations::Observations(double* observations_list,double* x,double* y,int n,Options* options){{{*/
-Observations::Observations(double* observations_list,double* x,double* y,int n,Options* options){
+/*FUNCTION Observations::Observations(IssmDouble* observations_list,IssmDouble* x,IssmDouble* y,int n,Options* options){{{*/
+Observations::Observations(IssmDouble* observations_list,IssmDouble* x,IssmDouble* y,int n,Options* options){
 
 	/*Intermediaries*/
-	int          i,maxdepth,level,counter;
+	int          i,j,maxdepth,level,counter,index;
 	int          xi,yi;
-	double       xmin,xmax,ymin,ymax;
-	double       offset,minlength;
+	IssmDouble       xmin,xmax,ymin,ymax;
+	IssmDouble       offset,minlength,minspacing,mintrimming,maxtrimming;
 	Observation *observation = NULL;
 
@@ -52,17 +54,23 @@
 	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) _error2_("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");
+		if(minlength<=0)_error2_("boxlength should be a positive number");
 		maxdepth=int(log(max(xmax-xmin,ymax-ymin)/minlength +1)/log(2.0));
 	}
 	else{
 		maxdepth = 30;
-		minlength=max(xmax-xmin,ymax-ymin)/double((1L<<maxdepth)-1);
+		minlength=max(xmax-xmin,ymax-ymin)/IssmDouble((1L<<maxdepth)-1);
 	}
 
 	/*Initialize Quadtree*/
-	printf("Generating quadtree with a maximum box size %g (depth=%i)... ",minlength,maxdepth);
+	_pprintString_("Generating quadtree with a maximum box size " << minlength << " (depth=" << maxdepth << ")... ");
 	this->quadtree = new Quadtree(xmin,xmax,ymin,ymax,maxdepth);
 
@@ -70,4 +78,16 @@
 	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=(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);
@@ -82,5 +102,7 @@
 		}
 	}
-	printf("done\n");
+	_pprintLine_("done");
+	_pprintLine_("Initial number of observations: " << n);
+	_pprintLine_("  Final number of observations: " << this->quadtree->NbObs);
 }
 /*}}}*/
@@ -93,35 +115,121 @@
 
 /*Methods*/
-/*FUNCTION Observations::ObservationList{{{*/
-void Observations::ObservationList(double **px,double **py,double **pobs,int* pnobs,double x_interp,double y_interp,double range){
+/*FUNCTION Observations::ClosestObservation{{{*/
+void Observations::ClosestObservation(IssmDouble *px,IssmDouble *py,IssmDouble *pobs,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius){
 
 	/*Output and Intermediaries*/
+	bool         stop;
 	int          nobs,i,index;
-	double      *x            = NULL;
-	double      *y            = NULL;
-	double      *obs          = NULL;
+	IssmDouble       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;
+
+	/*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=(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 = i;
+		}
+		else{
+			if(h2<hmin2){
+				hmin2 = h2;
+				index = i;
+			}
+		}
+	}  
+
+	/*Assign output pointer*/
+	if(!nobs){
+		*px=UNDEF;
+		*py=UNDEF;
+		*pobs=UNDEF;
+	}
+	else{
+		observation=(Observation*)this->GetObjectByOffset(indices[index]);
+		*px=observation->x;
+		*py=observation->y;
+		*pobs=observation->value;
+	}
+	xDelete<int>(indices);
+
+}/*}}}*/
+/*FUNCTION Observations::ObservationList(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int maxdata){{{*/
+void Observations::ObservationList(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int maxdata){
+
+	/*Output and Intermediaries*/
+	bool         stop;
+	int          nobs,tempnobs,i,j,k,n,counter;
+	IssmDouble       h2,radius2;
 	int         *indices      = NULL;
-
-	/*Treat range*/
-	if(range==0){
-		range=this->quadtree->root->length;
-	}
-
-	/*Find all observations that are in range*/
-	this->quadtree->RangeSearch(&indices,&nobs,x_interp,y_interp,range);
-
-	if(nobs==0){
-		/*No observation found, double range*/
-		//printf("No observation found within range, doubling range\n");
-		xfree((void**)&indices);
-		this->ObservationList(&x,&y,&obs,&nobs,x_interp,y_interp,range*2);
-	}
-	else{
-		//if(nobs>1000) printf("Taking more than 1000 observations\n");
+	int         *tempindices  = NULL;
+	IssmDouble      *dists        = NULL;
+	IssmDouble      *x            = NULL;
+	IssmDouble      *y            = NULL;
+	IssmDouble      *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<IssmDouble>(tempnobs);
+	}
+	nobs = 0;
+	for (i=0;i<tempnobs;i++){
+		observation=(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<IssmDouble>(dists);
+	xDelete<int>(tempindices);
+
+	if(nobs){
 		/*Allocate vectors*/
-		x   = (double*)xmalloc(nobs*sizeof(double));
-		y   = (double*)xmalloc(nobs*sizeof(double));
-		obs = (double*)xmalloc(nobs*sizeof(double));
+		x   = xNew<IssmDouble>(nobs);
+		y   = xNew<IssmDouble>(nobs);
+		obs = xNew<IssmDouble>(nobs);
 
 		/*Loop over all observations and fill in x, y and obs*/
@@ -133,5 +241,5 @@
 
 	/*Assign output pointer*/
-	xfree((void**)&indices);
+	xDelete<int>(indices);
 	*px=x;
 	*py=y;
@@ -139,6 +247,182 @@
 	*pnobs=nobs;
 }/*}}}*/
+/*FUNCTION Observations::ObservationList(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs){{{*/
+void Observations::ObservationList(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs){
+
+	/*Output and Intermediaries*/
+	int          nobs;
+	IssmDouble      *x            = NULL;
+	IssmDouble      *y            = NULL;
+	IssmDouble      *obs          = NULL;
+	Observation *observation  = NULL;
+
+	nobs = this->Size();
+
+	if(nobs){
+		x   = xNew<IssmDouble>(nobs);
+		y   = xNew<IssmDouble>(nobs);
+		obs = xNew<IssmDouble>(nobs);
+		for(int i=0;i<this->Size();i++){
+			observation=(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(IssmDouble *pprediction,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int mindata,int maxdata,IssmDouble power){
+
+	/*Intermediaries*/
+	int    i,n_obs;
+	IssmDouble prediction;
+	IssmDouble numerator,denominator,h,weight;
+	IssmDouble *x   = NULL;
+	IssmDouble *y   = NULL;
+	IssmDouble *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<IssmDouble>(x);
+	xDelete<IssmDouble>(y);
+	xDelete<IssmDouble>(obs);
+}/*}}}*/
+/*FUNCTION Observations::InterpolationKriging{{{*/
+void Observations::InterpolationKriging(IssmDouble *pprediction,IssmDouble *perror,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int mindata,int maxdata,Variogram* variogram){
+
+	/*Intermediaries*/
+	int           i,j,n_obs;
+	IssmDouble        prediction,error;
+	IssmDouble        numerator,denominator,ratio;
+	IssmDouble       *x            = NULL;
+	IssmDouble       *y            = NULL;
+	IssmDouble       *obs          = NULL;
+	IssmDouble       *Gamma        = NULL;
+	IssmDouble       *GinvG0       = NULL;
+	IssmDouble       *Ginv1        = NULL;
+	IssmDouble       *GinvZ        = NULL;
+	IssmDouble       *gamma0       = NULL;
+	IssmDouble       *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<IssmDouble>(n_obs*n_obs);
+	gamma0 = xNew<IssmDouble>(n_obs);
+	ones   = xNew<IssmDouble>(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_
+	SolverxGsl(&GinvG0,Gamma,gamma0,n_obs); // Gamma^-1 gamma0
+	SolverxGsl(&Ginv1, Gamma,ones,n_obs);   // Gamma^-1 ones
+	SolverxGsl(&GinvZ, Gamma,obs,n_obs);    // Gamma^-1 Z
+#else
+	_error2_("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<IssmDouble>(x);
+	xDelete<IssmDouble>(y);
+	xDelete<IssmDouble>(obs);
+	xDelete<IssmDouble>(Gamma);
+	xDelete<IssmDouble>(gamma0);
+	xDelete<IssmDouble>(ones);
+	xDelete<IssmDouble>(GinvG0);
+	xDelete<IssmDouble>(Ginv1);
+	xDelete<IssmDouble>(GinvZ);
+
+}/*}}}*/
+/*FUNCTION Observations::InterpolationNearestNeighbor{{{*/
+void Observations::InterpolationNearestNeighbor(IssmDouble *pprediction,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius){
+
+	/*Intermediaries*/
+	IssmDouble        x,y,obs;
+
+	/*Get clostest observation*/
+	this->ClosestObservation(&x,&y,&obs,x_interp,y_interp,radius);
+
+	/*Assign output pointer*/
+	*pprediction = obs;
+}/*}}}*/
 /*FUNCTION Observations::QuadtreeColoring{{{*/
-void Observations::QuadtreeColoring(double* A,double *x,double *y,int n){
+void Observations::QuadtreeColoring(IssmDouble* A,IssmDouble *x,IssmDouble *y,int n){
 
 	int xi,yi,level;
@@ -147,20 +431,19 @@
 		this->quadtree->IntergerCoordinates(&xi,&yi,x[i],y[i]);
 		this->quadtree->QuadtreeDepth(&level,xi,yi);
-		A[i]=(double)level;
+		A[i]=(IssmDouble)level;
 	}
 
 }/*}}}*/
 /*FUNCTION Observations::Variomap{{{*/
-void Observations::Variomap(double* gamma,double *x,int n){
+void Observations::Variomap(IssmDouble* gamma,IssmDouble *x,int n){
 
 	/*Output and Intermediaries*/
-	int          nobs,i,j,k;
-	double       range;
+	int          i,j,k;
+	IssmDouble       distance;
 	Observation *observation1 = NULL;
 	Observation *observation2 = NULL;
-	int         *indices      = NULL;
-
-	int *counter= (int*)xmalloc(n*sizeof(int));
-	for(j=0;j<n;j++) counter[j] = 0;
+
+	IssmDouble *counter = xNew<IssmDouble>(n);
+	for(j=0;j<n;j++) counter[j] = 0.0;
 	for(j=0;j<n;j++) gamma[j]   = 0.0;
 
@@ -168,26 +451,26 @@
 		observation1=(Observation*)this->GetObjectByOffset(i);
 
-		for(j=0;j<n;j++){
-			range=x[j]; _assert_(range>=0.);
-
-			/*Find all observations that are in range*/
-			this->quadtree->RangeSearch(&indices,&nobs,observation1->x,observation1->y,range);
-
-			for (k=0;k<nobs;k++){
-				observation2 = (Observation*)this->GetObjectByOffset(indices[k]);
-				gamma[j]    += 1./2.*pow(observation1->value - observation2->value,2.);
-			}
-
-			counter[j] += nobs;
-			xfree((void**)&indices);
+		for(j=i+1;j<this->Size();j++){
+			observation2=(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*/
-	for(j=0;j<n;j++){
-		if(counter[j]) gamma[j] = gamma[j]/double(counter[j]);
+	gamma[0]=0.;
+	for(k=0;k<n;k++){
+		if(counter[k]) gamma[k] = gamma[k]/counter[k];
 	}
 
 	/*Assign output pointer*/
-	xfree((void**)&counter);
-}/*}}}*/
+	xDelete<IssmDouble>(counter);
+}/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Observations.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Observations.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Observations.h	(revision 12878)
@@ -6,6 +6,8 @@
 #define  _CONTAINER_OBSERVATIONS_H_
 
-class Obsevration;
+#include "../include/include.h"
+
 class Quadtree;
+class Variogram;
 class Options;
 
@@ -19,11 +21,16 @@
 		/*constructors, destructors*/
 		Observations();
-		Observations(double* observations_list,double* x,double* y,int n,Options* options);
+		Observations(IssmDouble* observations_list,IssmDouble* x,IssmDouble* y,int n,Options* options);
 		~Observations();
 
 		/*Methods*/
-		void ObservationList(double **px,double **py,double **pobs,int* pnobs,double x_interp,double y_interp,double range);
-		void QuadtreeColoring(double* A,double *x,double *y,int n);
-		void Variomap(double* gamma,double *x,int n);
+		void ClosestObservation(IssmDouble *px,IssmDouble *py,IssmDouble *pobs,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius);
+		void InterpolationIDW(IssmDouble *pprediction,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int mindata,int maxdata,IssmDouble power);
+		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);
 
 };
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Options.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Options.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Options.cpp	(revision 12878)
@@ -4,5 +4,5 @@
  */
 
-/*Headers: {{{1*/
+/*Headers: {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -13,4 +13,5 @@
 #include <vector>
 #include <algorithm>
+#include <cstring>
 
 #include "./DataSet.h"
@@ -24,10 +25,10 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Options::Options(){{{1*/
+/*FUNCTION Options::Options(){{{*/
 Options::Options(){
 	return;
 }
 /*}}}*/
-/*FUNCTION Options::~Options(){{{1*/
+/*FUNCTION Options::~Options(){{{*/
 Options::~Options(){
 	return;
@@ -36,5 +37,5 @@
 
 /*Object management*/
-/*FUNCTION Options::AddOption{{{1*/
+/*FUNCTION Options::AddOption{{{*/
 int  Options::AddOption(Option* in_option){
 
@@ -46,8 +47,8 @@
 
 	/*Also, check the option name*/
-	if(!in_option->name) _error_("input option has an empty name");
-	if(strchr(in_option->name,'.')) _error_("Option \"%s\" has a protected character \".\"",in_option->name);
-	if(strchr(in_option->name,'[')) _error_("Option \"%s\" has a protected character \"[\"",in_option->name);
-	if(strchr(in_option->name,']')) _error_("Option \"%s\" has a protected character \"]\"",in_option->name);
+	if(!in_option->name) _error2_("input option has an empty name");
+	if(strchr(in_option->name,'.')) _error2_("Option \"" << in_option->name << "\" has a protected character \".\"");
+	if(strchr(in_option->name,'[')) _error2_("Option \"" << in_option->name << "\" has a protected character \"[\"");
+	if(strchr(in_option->name,']')) _error2_("Option \"" << in_option->name << "\" has a protected character \"]\"");
 
 	/*Finally, check that no option of the same name already exists in the dataset*/
@@ -56,5 +57,5 @@
 		option=(Option*)(*object); 
 		if (!strcmp(option->name,in_option->name)){
-			_error_("Options \"%s\" found multiple times",in_option->name);
+			_error2_("Options \"" << in_option->name << "\" found multiple times");
 			break;
 		}
@@ -67,25 +68,25 @@
 }
 /*}}}*/
-/*FUNCTION Options::Get(double* pvalue, char* name){{{1*/
-void Options::Get(double* pvalue,const char* name){
-
-	vector<Object*>::iterator object;
-	Option* option=NULL;
-
-	/*Get option*/
-	option=GetOption(name);
-
-	/*If the pointer is not NULL, the option has been found*/
-	if(option){
-		option->Get(pvalue);
-	}
-	/*Else, the Option does not exist, no default provided*/
-	else{
-		_error_("option of name \"%s\" not found, and no default value has been provided",name);
-	}
-}
-/*}}}*/
-/*FUNCTION Options::Get(double* pvalue, char* name,double default_value){{{1*/
-void Options::Get(double* pvalue,const char* name,double default_value){
+/*FUNCTION Options::Get(int* pvalue, char* name){{{*/
+void Options::Get(int* pvalue,const char* name){
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+
+	/*Get option*/
+	option=GetOption(name);
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(option){
+		option->Get(pvalue);
+	}
+	/*Else, the Option does not exist, no default provided*/
+	else{
+		_error2_("option of name \"" << name << "\" not found, and no default value has been provided");
+	}
+}
+/*}}}*/
+/*FUNCTION Options::Get(int* pvalue, char* name,int default_value){{{*/
+void Options::Get(int* pvalue,const char* name,int default_value){
 
 	vector<Object*>::iterator object;
@@ -105,5 +106,43 @@
 }
 /*}}}*/
-/*FUNCTION Options::Get(bool* pvalue, char* name){{{1*/
+/*FUNCTION Options::Get(IssmDouble* pvalue, char* name){{{*/
+void Options::Get(IssmDouble* pvalue,const char* name){
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+
+	/*Get option*/
+	option=GetOption(name);
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(option){
+		option->Get(pvalue);
+	}
+	/*Else, the Option does not exist, no default provided*/
+	else{
+		_error2_("option of name \"" << name << "\" not found, and no default value has been provided");
+	}
+}
+/*}}}*/
+/*FUNCTION Options::Get(IssmDouble* pvalue, char* name,IssmDouble default_value){{{*/
+void Options::Get(IssmDouble* pvalue,const char* name,IssmDouble default_value){
+
+	vector<Object*>::iterator object;
+	Option* option=NULL;
+
+	/*Get option*/
+	option=GetOption(name);
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(option){
+		option->Get(pvalue);
+	}
+	/*Else, the Option does not exist, a default is provided here*/
+	else{
+		*pvalue=default_value;
+	}
+}
+/*}}}*/
+/*FUNCTION Options::Get(bool* pvalue, char* name){{{*/
 void Options::Get(bool* pvalue,const char* name){
 
@@ -120,9 +159,9 @@
 	/*Else, the Option does not exist, no default provided*/
 	else{
-		_error_("option of name \"%s\" not found, and no default value has been provided",name);
-	}
-}
-/*}}}*/
-/*FUNCTION Options::Get(bool* pvalue, char* name,bool default_value){{{1*/
+		_error2_("option of name \"" << name << "\" not found, and no default value has been provided");
+	}
+}
+/*}}}*/
+/*FUNCTION Options::Get(bool* pvalue, char* name,bool default_value){{{*/
 void Options::Get(bool* pvalue,const char* name,bool default_value){
 
@@ -143,5 +182,5 @@
 }
 /*}}}*/
-/*FUNCTION Options::Get(char** pvalue, char* name){{{1*/
+/*FUNCTION Options::Get(char** pvalue, char* name){{{*/
 void Options::Get(char** pvalue,const char* name){
 
@@ -160,10 +199,10 @@
 	/*Else, the Option does not exist, no default provided*/
 	else{
-		_error_("option of name \"%s\" not found, and no default value has been provided",name);
-	}
-
-}
-/*}}}*/
-/*FUNCTION Options::Get(char** pvalue, char* name,char* default_value){{{1*/
+		_error2_("option of name \"" << name << "\" not found, and no default value has been provided");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Options::Get(char** pvalue, char* name,char* default_value){{{*/
 void Options::Get(char** pvalue,const char* name,const char* default_value){
 
@@ -183,6 +222,6 @@
 	else{
 		stringsize=strlen(default_value)+1;
-		outstring=(char*)xmalloc(stringsize*sizeof(char));
-		memcpy(outstring,default_value,stringsize*sizeof(char));
+		outstring=xNew<char>(stringsize);
+		xMemCpy<char>(outstring,default_value,stringsize);
 		*pvalue=outstring;
 	}
@@ -190,5 +229,5 @@
 }
 /*}}}*/
-/*FUNCTION Options::Get(char*** ppvalue,int* numel,char* name){{{1*/
+/*FUNCTION Options::Get(char*** ppvalue,int* numel,char* name){{{*/
 void Options::Get(char*** ppvalue,int* numel,const char* name){
 
@@ -207,5 +246,5 @@
 		if(option->ObjectEnum()==OptionCellEnum){
 			if (option->NumEl()) {
-				*ppvalue=(char **) xmalloc(option->NumEl()*sizeof(char *));
+				*ppvalue=xNew<char*>(option->NumEl());
 				if (numel) *numel=option->NumEl();
 				option->Get(&options);
@@ -225,5 +264,5 @@
 		/*Else: not supported*/
 		else{
-			_error_("Cannot recover field \"%s\" for an option of type %s",name,EnumToStringx(option->ObjectEnum()));
+			_error2_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
 		}
 	}
@@ -236,6 +275,6 @@
 }
 /*}}}*/
-/*FUNCTION Options::Get(double** pvalue,int* numel,const char* name){{{1*/
-void Options::Get(double** pvalue,int* numel,const char* name){
+/*FUNCTION Options::Get(IssmDouble** pvalue,int* numel,const char* name){{{*/
+void Options::Get(IssmDouble** pvalue,int* numel,const char* name){
 
 	vector<Object*>::iterator object;
@@ -251,9 +290,9 @@
 	/*Else, the Option does not exist, no default provided*/
 	else{
-		_error_("option of name \"%s\" not found, and no default value has been provided",name);
-	}
-}
-/*}}}*/
-/*FUNCTION Options::GetOption{{{1*/
+		_error2_("option of name \"" << name << "\" not found, and no default value has been provided");
+	}
+}
+/*}}}*/
+/*FUNCTION Options::GetOption{{{*/
 Option* Options::GetOption(const char* name){
 
@@ -285,5 +324,5 @@
 				/*Else: not supported*/
 				else{
-					_error_("Cannot recover field \"%s\" for an option of type %s",name,EnumToStringx(option->ObjectEnum()));
+					_error2_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
 				}
 			}
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Options.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Options.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Options.h	(revision 12878)
@@ -20,6 +20,8 @@
 		int  AddOption(Option* in_oobject);
 		Option* GetOption(const char* name);
-		void Get(double*  pvalue,const char* name);
-		void Get(double*  pvalue,const char* name,double default_value);
+		void Get(IssmDouble*  pvalue,const char* name);
+		void Get(IssmDouble*  pvalue,const char* name,IssmDouble default_value);
+		void Get(int*  pvalue,const char* name);
+		void Get(int*  pvalue,const char* name,int default_value);
 		void Get(bool*    pvalue,const char* name);
 		void Get(bool*    pvalue,const char* name,bool default_value);
@@ -27,5 +29,5 @@
 		void Get(char**   pvalue,const char* name,const char* default_value);
 		void Get(char***  pvalue,int* numel,const char* name);
-		void Get(double** pvalue,int* numel,const char* name);
+		void Get(IssmDouble** pvalue,int* numel,const char* name);
 };
 
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Parameters.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Parameters.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Parameters.cpp	(revision 12878)
@@ -4,5 +4,5 @@
  */
 
-/*Headers: {{{1*/
+/*Headers: {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -25,5 +25,5 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Parameters::Parameters(){{{1*/
+/*FUNCTION Parameters::Parameters(){{{*/
 Parameters::Parameters(){
 	enum_type=ParametersEnum;
@@ -31,5 +31,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::~Parameters(){{{1*/
+/*FUNCTION Parameters::~Parameters(){{{*/
 Parameters::~Parameters(){
 	return;
@@ -38,5 +38,5 @@
 
 /*Object management*/
-/*FUNCTION Parameters::Exist{{{1*/
+/*FUNCTION Parameters::Exist{{{*/
 bool Parameters::Exist(int enum_type){
 
@@ -51,5 +51,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::FindParam(bool* pbool,int enum_type){{{1*/
+/*FUNCTION Parameters::FindParam(bool* pbool,int enum_type){{{*/
 void Parameters::FindParam(bool* pbool,int enum_type){ _assert_(this);
 	
@@ -65,8 +65,8 @@
 		}
 	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(int* pinteger,int enum_type){{{1*/
+	_error2_("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);
 	
@@ -82,9 +82,9 @@
 		}
 	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(double* pscalar, int enum_type){{{1*/
-void Parameters::FindParam(double* pscalar, int enum_type){ _assert_(this);
+	_error2_("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;
@@ -99,8 +99,25 @@
 		}
 	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(char** pstring,int enum_type){{{1*/
+	_error2_("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=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pscalar,time);
+			return;
+		}
+	}
+	_error2_("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);
 	
@@ -116,9 +133,9 @@
 		}
 	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){{{1*/
+	_error2_("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);
 	
@@ -134,9 +151,9 @@
 		}
 	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(int** pintarray,int* pM,int enum_type){{{1*/
+	_error2_("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);
 
@@ -152,9 +169,9 @@
 		}
 	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(int** pintarray,int* pM,int* pN,int enum_type){{{1*/
+	_error2_("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);
 
@@ -170,46 +187,46 @@
 		}
 	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(double** pdoublearray,int* pM,int enum_type){{{1*/
-void Parameters::FindParam(double** pdoublearray,int* pM, int enum_type){ _assert_(this);
-
-	vector<Object*>::iterator object;
-	Param* param=NULL;
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		param=(Param*)(*object);
-		if(param->InstanceEnum()==enum_type){
-			param->GetParameterValue(pdoublearray,pM);
-			return;
-		}
-	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(double** pdoublearray,int* pM, int* pN,int enum_type){{{1*/
-void Parameters::FindParam(double** pdoublearray,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=(Param*)(*object);
-		if(param->InstanceEnum()==enum_type){
-			param->GetParameterValue(pdoublearray,pM,pN);
-			return;
-		}
-	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(double*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){{{1*/
-void Parameters::FindParam(double*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){ _assert_(this);
+	_error2_("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=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pIssmDoublearray,pM);
+			return;
+		}
+	}
+	_error2_("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=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pIssmDoublearray,pM,pN);
+			return;
+		}
+	}
+	_error2_("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;
@@ -224,8 +241,8 @@
 		}
 	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(Vector** pvec,int enum_type){{{1*/
+	_error2_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(Vector** pvec,int enum_type){{{*/
 void Parameters::FindParam(Vector** pvec,int enum_type){ _assert_(this);
 	
@@ -241,9 +258,9 @@
 		}
 	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(Matrix** pmat,int enum_type){{{1*/
+	_error2_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(Matrix** pmat,int enum_type){{{*/
 void Parameters::FindParam(Matrix** pmat,int enum_type){ _assert_(this);
 	
@@ -259,9 +276,9 @@
 		}
 	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-
-}
-/*}}}*/
-/*FUNCTION Parameters::FindParam(FILE** pfid,int enum_type){{{1*/
+	_error2_("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);
 
@@ -277,9 +294,9 @@
 		}
 	}
-	_error_("could not find parameter %s",EnumToStringx(enum_type));
-}
-/*}}}*/
-
-/*FUNCTION Parameters::SetParam(bool boolean,int enum_type);{{{1*/
+	_error2_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+
+/*FUNCTION Parameters::SetParam(bool boolean,int enum_type);{{{*/
 void   Parameters::SetParam(bool boolean,int enum_type){
 
@@ -293,5 +310,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(int integer,int enum_type);{{{1*/
+/*FUNCTION Parameters::SetParam(int integer,int enum_type);{{{*/
 void   Parameters::SetParam(int integer,int enum_type){
 
@@ -305,6 +322,6 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(double scalar,int enum_type);{{{1*/
-void   Parameters::SetParam(double scalar,int enum_type){
+/*FUNCTION Parameters::SetParam(IssmDouble scalar,int enum_type);{{{*/
+void   Parameters::SetParam(IssmDouble scalar,int enum_type){
 
 	Param* param=NULL;
@@ -317,5 +334,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(char* string,int enum_type);{{{1*/
+/*FUNCTION Parameters::SetParam(char* string,int enum_type);{{{*/
 void   Parameters::SetParam(char* string,int enum_type){
 
@@ -329,5 +346,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(char** stringarray,int M, int enum_type);{{{1*/
+/*FUNCTION Parameters::SetParam(char** stringarray,int M, int enum_type);{{{*/
 void   Parameters::SetParam(char** stringarray,int M, int enum_type){
 
@@ -341,29 +358,29 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(double* doublearray,int M,int enum_type);{{{1*/
-void   Parameters::SetParam(double* doublearray,int M, int enum_type){
-
-	Param* param=NULL;
-	
-	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
-
-	if(param) param->SetValue(doublearray,M); //already exists, just set it.
-	else this->AddObject(new DoubleVecParam(enum_type,doublearray,M)); //just add the new parameter.
-}
-/*}}}*/
-/*FUNCTION Parameters::SetParam(double* doublearray,int M,int N, int enum_type);{{{1*/
-void   Parameters::SetParam(double* doublearray,int M, int N, int enum_type){
-
-	Param* param=NULL;
-	
-	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
-
-	if(param) param->SetValue(doublearray,M,N); //already exists, just set it.
-	else this->AddObject(new DoubleMatParam(enum_type,doublearray,M,N)); //just add the new parameter.
-}
-/*}}}*/
-/*FUNCTION Parameters::SetParam(int* intarray,int M,int enum_type);{{{1*/
+/*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=(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=(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){
 
@@ -377,5 +394,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(int* intarray,int M,int N, int enum_type);{{{1*/
+/*FUNCTION Parameters::SetParam(int* intarray,int M,int N, int enum_type);{{{*/
 void   Parameters::SetParam(int* intarray,int M, int N, int enum_type){
 
@@ -389,5 +406,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(Vector* vector,int enum_type);{{{1*/
+/*FUNCTION Parameters::SetParam(Vector* vector,int enum_type);{{{*/
 void   Parameters::SetParam(Vector* vector,int enum_type){
 
@@ -401,5 +418,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(Matrix* matrix,int enum_type);{{{1*/
+/*FUNCTION Parameters::SetParam(Matrix* matrix,int enum_type);{{{*/
 void   Parameters::SetParam(Matrix* matrix,int enum_type){
 
@@ -413,5 +430,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(FILE* fid,int enum_type);{{{1*/
+/*FUNCTION Parameters::SetParam(FILE* fid,int enum_type);{{{*/
 void   Parameters::SetParam(FILE* fid,int enum_type){
 
@@ -425,5 +442,5 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::UnitConversion(int direction_enum);{{{1*/
+/*FUNCTION Parameters::UnitConversion(int direction_enum);{{{*/
 void   Parameters::UnitConversion(int direction_enum){
 
@@ -439,5 +456,5 @@
 /*}}}*/
 
-/*FUNCTION Parameters::FindParamObject{{{1*/
+/*FUNCTION Parameters::FindParamObject{{{*/
 Object* Parameters::FindParamObject(int enum_type){
 
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Parameters.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Parameters.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Parameters.h	(revision 12878)
@@ -23,21 +23,22 @@
 	public:
 
-		/*constructors, destructors: {{{1*/
+		/*constructors, destructors*/ 
 		Parameters();
 		~Parameters();
-		/*}}}*/
-		/*numerics: {{{1*/
+
+		/*numerics*/
 		bool  Exist(int enum_type);
 
 		void  FindParam(bool* pinteger,int enum_type);
 		void  FindParam(int* pinteger,int enum_type);
-		void  FindParam(double* pscalar, 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(double** pdoublearray,int* pM,int enum_type);
-		void  FindParam(double** pdoublearray,int* pM,int* pN,int enum_type);
-		void  FindParam(double*** parray,int* pM, int** pmdims_array,int** pndims_array,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** pvec,int enum_type);
 		void  FindParam(Matrix** pmat,int enum_type);
@@ -46,9 +47,9 @@
 		void  SetParam(bool boolean,int enum_type);
 		void  SetParam(int integer,int enum_type);
-		void  SetParam(double scalar, 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(double* doublearray,int M,int enum_type);
-		void  SetParam(double* doublearray,int M,int N,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);
@@ -59,5 +60,4 @@
 
 		Object* FindParamObject(int enum_type);
-		/*}}}*/
 
 };
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Results.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Results.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Results.cpp	(revision 12878)
@@ -4,5 +4,5 @@
  */
 
-/*Headers: {{{1*/
+/*Headers: {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -25,5 +25,5 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Results::Results(){{{1*/
+/*FUNCTION Results::Results(){{{*/
 Results::Results(){
 	enum_type=ResultsEnum;
@@ -31,5 +31,5 @@
 }
 /*}}}*/
-/*FUNCTION Results::~Results(){{{1*/
+/*FUNCTION Results::~Results(){{{*/
 Results::~Results(){
 	return;
@@ -38,5 +38,5 @@
 
 /*Object management*/
-/*FUNCTION Results::SpawnTriaResults{{{1*/
+/*FUNCTION Results::SpawnTriaResults{{{*/
 Results* Results::SpawnTriaResults(int* indices){
 
@@ -64,5 +64,5 @@
 }
 /*}}}*/
-/*FUNCTION Results::Write{{{1*/
+/*FUNCTION Results::Write{{{*/
 void Results::Write(Parameters* parameters){
 	
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Results.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Results.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Results.h	(revision 12878)
@@ -20,9 +20,9 @@
 	public:
 
-		/*constructors, destructors: {{{1*/
+		/*constructors, destructors: {{{*/
 		Results();
 		~Results();
 		/*}}}*/
-		/*numerics: {{{1*/
+		/*numerics: {{{*/
 		Results* SpawnTriaResults(int* indices);
 		void Write(Parameters* parameters);
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Vertices.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Vertices.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Vertices.cpp	(revision 12878)
@@ -4,5 +4,5 @@
  */
 
-/*Headers: {{{1*/
+/*Headers: {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -25,5 +25,5 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION Vertices::Vertices(){{{1*/
+/*FUNCTION Vertices::Vertices(){{{*/
 Vertices::Vertices(){
 	enum_type=VerticesEnum;
@@ -31,5 +31,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertices::~Vertices(){{{1*/
+/*FUNCTION Vertices::~Vertices(){{{*/
 Vertices::~Vertices(){
 	return;
@@ -38,5 +38,5 @@
 
 /*Numerics management*/
-/*FUNCTION Vertices::DistributeDofs{{{1*/
+/*FUNCTION Vertices::DistributeDofs{{{*/
 void  Vertices::DistributeDofs(int numberofobjects,int numberofdofsperobject){
 
@@ -60,5 +60,5 @@
 	 * cpus by the total last dofs of the previus cpu, starting from 0.
 	 * First: bet number of dofs for each cpu*/
-	alldofcount=(int*)xmalloc(num_procs*sizeof(int));
+	alldofcount=xNew<int>(num_procs);
 	#ifdef _HAVE_MPI_
 	MPI_Gather(&dofcount,1,MPI_INT,alldofcount,1,MPI_INT,0,MPI_COMM_WORLD);
@@ -83,6 +83,6 @@
 	 * object that is not a clone, tell them to show their dofs, so that later on, they can get picked 
 	 * up by their clones: */
-	truedofs   =(int*)xcalloc(numberofobjects*numberofdofsperobject,sizeof(int));
-	alltruedofs=(int*)xcalloc(numberofobjects*numberofdofsperobject,sizeof(int));
+	truedofs   =xNewZeroInit<int>(numberofobjects*numberofdofsperobject);
+	alltruedofs=xNewZeroInit<int>(numberofobjects*numberofdofsperobject);
 	for (i=0;i<this->Size();i++){
 		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
@@ -102,10 +102,10 @@
 
 	/* Free ressources: */
-	xfree((void**)&alldofcount);
-	xfree((void**)&truedofs);
-	xfree((void**)&alltruedofs);
+	xDelete<int>(alldofcount);
+	xDelete<int>(truedofs);
+	xDelete<int>(alltruedofs);
 }
 /*}}}*/
-/*FUNCTION Vertices::FlagClones{{{1*/
+/*FUNCTION Vertices::FlagClones{{{*/
 void  Vertices::FlagClones(int numberofobjects){
 
@@ -117,6 +117,6 @@
 
 	/*Allocate ranks: */
-	ranks=(int*)xmalloc(numberofobjects*sizeof(int));
-	minranks=(int*)xmalloc(numberofobjects*sizeof(int));
+	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.
@@ -143,10 +143,10 @@
 
 	/*Free ressources: */
-	xfree((void**)&ranks); 
-	xfree((void**)&minranks);
+	xDelete<int>(ranks); 
+	xDelete<int>(minranks);
 
 }
 /*}}}*/
-/*FUNCTION Vertices::NumberOfVertices{{{1*/
+/*FUNCTION Vertices::NumberOfVertices{{{*/
 int Vertices::NumberOfVertices(void){
 
@@ -174,5 +174,5 @@
 }
 /*}}}*/
-/*FUNCTION Vertices::Ranks{{{1*/
+/*FUNCTION Vertices::Ranks{{{*/
 void   Vertices::Ranks(int* ranks){
 
Index: /issm/branches/trunk-jpl-damage/src/c/Container/Vertices.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Container/Vertices.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Container/Vertices.h	(revision 12878)
@@ -19,9 +19,9 @@
 	public:
 
-		/*constructors, destructors: {{{1*/
+		/*constructors, destructors: {{{*/
 		Vertices();
 		~Vertices();
 		/*}}}*/
-		/*numerics: {{{1*/
+		/*numerics: {{{*/
 		void  DistributeDofs(int numberofnodes,int numdofspernode);
 		void  FlagClones(int numberofnodes);
Index: /issm/branches/trunk-jpl-damage/src/c/EnumDefinitions/EnumDefinitions.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/EnumDefinitions/EnumDefinitions.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/EnumDefinitions/EnumDefinitions.h	(revision 12878)
@@ -105,4 +105,5 @@
 	MaterialsRhoIceEnum,
 	MaterialsRhoWaterEnum,
+	MaterialsRhoFreshwaterEnum,
 	MaterialsMuWaterEnum,
 	MaterialsThermalExchangeVelocityEnum,
@@ -150,8 +151,14 @@
 	SettingsResultsAsPatchesEnum,
 	SettingsWaitonlockEnum,
-	DebugPetscProfilingEnum,
-	PetscProfilingCurrentMemEnum,
-	PetscProfilingCurrentFlopsEnum,
-	PetscProfilingSolutionTimeEnum,
+	SurfaceforcingsDelta18oEnum,
+	SurfaceforcingsDelta18oSurfaceEnum,
+	SurfaceforcingsIsdelta18oEnum,
+	SurfaceforcingsPrecipitationsPresentdayEnum,
+	SurfaceforcingsTemperaturesPresentdayEnum,
+	SurfaceforcingsTemperaturesLgmEnum,
+	DebugProfilingEnum,
+	ProfilingCurrentMemEnum,
+	ProfilingCurrentFlopsEnum,
+	ProfilingSolutionTimeEnum,
 	MaxIterationConvergenceFlagEnum,
 	SteadystateMaxiterEnum,
@@ -162,4 +169,14 @@
 	SurfaceforcingsPrecipitationEnum,
 	SurfaceforcingsMassBalanceEnum,
+	SurfaceforcingsIspddEnum,
+	SurfaceforcingsIssmbgradientsEnum,
+	SurfaceforcingsMonthlytemperaturesEnum,
+	SurfaceforcingsHcEnum,
+	SurfaceforcingsSmbPosMaxEnum,
+	SurfaceforcingsSmbPosMinEnum,
+	SurfaceforcingsAPosEnum,
+	SurfaceforcingsBPosEnum,
+	SurfaceforcingsANegEnum,
+	SurfaceforcingsBNegEnum,
 	ThermalMaxiterEnum,
 	ThermalPenaltyFactorEnum,
@@ -261,4 +278,5 @@
 	IntParamEnum,
 	IntVecParamEnum,
+	TransientParamEnum,
 	MacAyeal2dIceFrontEnum,
 	MacAyeal3dIceFrontEnum,
@@ -386,4 +404,5 @@
 	StressTensorzzEnum,
 	IceVolumeEnum,
+	TotalSmbEnum,
 	/*}}}*/
 	/*Element Interpolations{{{1*/
Index: /issm/branches/trunk-jpl-damage/src/c/EnumDefinitions/Synchronize.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/EnumDefinitions/Synchronize.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/EnumDefinitions/Synchronize.sh	(revision 12878)
@@ -2,9 +2,10 @@
 #Synchronize EnumToStringx.cpp and StringToEnumx.cpp and matlab Enums
 
-#Get all lines of EnumDefinitions2.h which hold Enum | remove all comas > put everything in file temp
+#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/modules/EnumToStringx/EnumToStringx.cpp
 rm $ISSM_DIR/src/c/modules/StringToEnumx/StringToEnumx.cpp
@@ -25,4 +26,5 @@
 */
 
+#include <cstring>
 #include "../../shared/shared.h"
 #include "../../include/include.h"
@@ -47,5 +49,5 @@
 
 	len=strlen(EnumToStringx(enum_in));
-	string=(char*)xmalloc((len+1)*sizeof(char));
+	string=xNew<char>(len+1);
 	memcpy(string,EnumToStringx(enum_in),(len+1)*sizeof(char));
 
@@ -55,5 +57,5 @@
 END
 #}}}
-#Build StringToEnumx.cpp {{{1
+#Build StringToEnumx.cpp {{{
 #Header
 cat <<END > $ISSM_DIR/src/c/modules/StringToEnumx/StringToEnumx.cpp
@@ -67,4 +69,5 @@
 */
 
+#include <cstring>
 #include "../../shared/shared.h"
 #include "../../include/include.h"
@@ -95,5 +98,5 @@
 cat <<END >> $ISSM_DIR/src/c/modules/StringToEnumx/StringToEnumx.cpp
 	/*If we reach this point, the string provided has not been found*/
-   _error_("Enum %s not found",name);
+	_error2_("Enum " << name << " not found");
 }
 END
@@ -102,4 +105,17 @@
 # go through the lines of temp
 ENUM=0;
+#Add header to pythonenum file{{{
+cat <<END > $ISSM_DIR/src/m/enum/EnumDefinitions.py
+"""
+
+   WARNING: DO NOT MODIFY THIS FILE
+            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+            Please read src/c/EnumDefinitions/README for more information
+
+"""
+
+END
+#}}}
+
 for NAMEENUM in $(cat temp); do
 
@@ -140,7 +156,21 @@
 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)
+
+	   Usage:
+	      macro=$NAMEENUM()
+	"""
+
+	return StringToEnum('$NAME')
+
+END
+#}}}
 
 done
-#MaximumNumberOfEnums{{{
+#MaximumNumberOfEnums (matlab){{{
 cat <<END > $ISSM_DIR/src/m/enum/MaximumNumberOfEnums.m
 function macro=MaximumNumberOfEnums()
@@ -159,4 +189,20 @@
 END
 #}}}
+#MaximumNumberOfEnums (python){{{
+cat <<END >> $ISSM_DIR/src/m/enum/EnumDefinitions.py
+def MaximumNumberOfEnums():
+	"""
+	$(echo "MaximumNumberOfEnums" | awk {'print toupper($1)'}) - Enum of MaximumNumberOfEnums
+
+	   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{{{
Index: /issm/branches/trunk-jpl-damage/src/c/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/Makefile.am	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/Makefile.am	(revision 12878)
@@ -1,8 +1,12 @@
-INCLUDES = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @MPIINCL@ @MATLABINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @HYPREINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
+INCLUDES = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @MPIINCL@ @MATLABINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
 
 EXEEXT=$(ISSMEXT)
 
-#Library declaration {{{1
-lib_LIBRARIES = libISSMCore.a libISSMModules.a libISSMOverload.a
+#Library declaration {{{
+lib_LIBRARIES = libISSMCore.a libISSMOverload.a
+
+#if SHARED
+#lib_LTLIBRARIES = libISSM.la libISSMCore.la libISSMOverload.la
+#endif
 if PYTHON
 lib_LIBRARIES += libISSMPython.a 
@@ -11,8 +15,11 @@
 lib_LIBRARIES += libISSMMatlab.a 
 endif
+if MODULES
+lib_LIBRARIES += libISSMModules.a 
+endif
 #}}}
 
 #sources
-#Core sources{{{1
+#Core sources{{{
 core_sources = ./issm.h\
 					./issm-binding.h\
@@ -21,130 +28,134 @@
 					./include/types.h\
 					./include/include.h\
-					./objects/objects.h\
-					./objects/Object.h\
-					./objects/Gauss/GaussTria.h\
-					./objects/Gauss/GaussTria.cpp\
-					./objects/Update.h\
-					./objects/Element.h\
-					./objects/FemModel.h\
-					./objects/FemModel.cpp\
-					./objects/Material.h\
-					./objects/Load.h\
-					./objects/Contour.h\
-					./objects/Contour.cpp\
-					./objects/OptArgs.h\
-					./objects/OptPars.h\
-					./objects/Loads/Friction.h\
-					./objects/Loads/Friction.cpp\
-					./objects/Inputs/TransientInput.h\
-					./objects/Inputs/TransientInput.cpp\
-					./objects/Constraints/SpcTransient.cpp\
-					./objects/Constraints/SpcTransient.h\
-					./objects/DofIndexing.h\
-					./objects/DofIndexing.cpp\
-					./objects/IoModel.h\
-					./objects/IoModel.cpp\
-					./objects/Node.h\
-					./objects/Node.cpp\
-					./objects/Segment.h\
-					./objects/Segment.cpp\
-					./objects/Vertex.h\
-					./objects/Vertex.cpp\
-					./objects/Hook.h\
-					./objects/Hook.cpp\
-					./objects/Patch.h\
-					./objects/Patch.cpp\
-					./objects/ElementResults/ElementResultLocal.h\
-					./objects/ElementResults/DoubleElementResult.h\
-					./objects/ElementResults/DoubleElementResult.cpp\
-					./objects/ElementResults/TriaP1ElementResult.h\
-					./objects/ElementResults/TriaP1ElementResult.cpp\
-					./objects/ElementResults/BoolElementResult.h\
-					./objects/ElementResults/BoolElementResult.cpp\
-					./objects/ExternalResults/ExternalResult.h\
-					./objects/ExternalResults/BoolExternalResult.h\
-					./objects/ExternalResults/BoolExternalResult.cpp\
-					./objects/ExternalResults/DoubleExternalResult.h\
-					./objects/ExternalResults/DoubleExternalResult.cpp\
-					./objects/ExternalResults/DoubleVecExternalResult.h\
-					./objects/ExternalResults/DoubleVecExternalResult.cpp\
-					./objects/ExternalResults/DoubleMatExternalResult.h\
-					./objects/ExternalResults/DoubleMatExternalResult.cpp\
-					./objects/ExternalResults/IntExternalResult.h\
-					./objects/ExternalResults/IntExternalResult.cpp\
-					./objects/ExternalResults/StringExternalResult.h\
-					./objects/ExternalResults/StringExternalResult.cpp\
-					./objects/Elements/Tria.h\
-					./objects/Elements/Tria.cpp\
-					./objects/Elements/TriaHook.h\
-					./objects/Elements/TriaHook.cpp\
-					./objects/Elements/TriaRef.h\
-					./objects/Elements/TriaRef.cpp\
-					./objects/Inputs/Input.h\
-					./objects/Inputs/InputLocal.h\
-					./objects/Inputs/TriaP1Input.h\
-					./objects/Inputs/TriaP1Input.cpp\
-					./objects/Inputs/BoolInput.h\
-					./objects/Inputs/BoolInput.cpp\
-					./objects/Inputs/IntInput.h\
-					./objects/Inputs/IntInput.cpp\
-					./objects/Inputs/DoubleInput.h\
-					./objects/Inputs/DoubleInput.cpp\
-					./objects/Inputs/DatasetInput.h\
-					./objects/Inputs/DatasetInput.cpp\
-					./objects/Materials/Matice.h\
-					./objects/Materials/Matice.cpp\
-					./objects/Materials/Matpar.h\
-					./objects/Materials/Matpar.cpp\
-					./objects/Constraints/Constraint.h\
-					./objects/Constraints/SpcStatic.cpp\
-					./objects/Constraints/SpcStatic.h\
-					./objects/Constraints/SpcDynamic.cpp\
-					./objects/Constraints/SpcDynamic.h\
-					./objects/Loads/Penpair.cpp\
-					./objects/Loads/Penpair.h\
-					./objects/Loads/Pengrid.cpp\
-					./objects/Loads/Pengrid.h\
-					./objects/Loads/Icefront.cpp\
-					./objects/Loads/Icefront.h\
-					./objects/Loads/Numericalflux.cpp\
-					./objects/Loads/Numericalflux.h\
-					./objects/Numerics/ElementMatrix.h\
-					./objects/Numerics/ElementMatrix.cpp\
-					./objects/Numerics/ElementVector.h\
-					./objects/Numerics/ElementVector.cpp\
-					./objects/Numerics/Matrix.h\
-					./objects/Numerics/Matrix.cpp\
-					./objects/Numerics/Vector.h\
-					./objects/Numerics/Vector.cpp\
-					./objects/Params/Param.h\
-					./objects/Params/BoolParam.cpp\
-					./objects/Params/BoolParam.h\
-					./objects/Params/IntParam.cpp\
-					./objects/Params/IntParam.h\
-					./objects/Params/IntVecParam.cpp\
-					./objects/Params/IntVecParam.h\
-					./objects/Params/IntMatParam.cpp\
-					./objects/Params/IntMatParam.h\
-					./objects/Params/DoubleParam.cpp\
-					./objects/Params/DoubleParam.h\
-					./objects/Params/FileParam.cpp\
-					./objects/Params/FileParam.h\
-					./objects/Params/StringArrayParam.cpp\
-					./objects/Params/StringArrayParam.h\
-					./objects/Params/DoubleMatParam.cpp\
-					./objects/Params/DoubleMatParam.h\
-					./objects/Params/DoubleTransientMatParam.cpp\
-					./objects/Params/DoubleTransientMatParam.h\
-					./objects/Params/DoubleMatArrayParam.cpp\
-					./objects/Params/DoubleMatArrayParam.h\
-					./objects/Params/DoubleVecParam.cpp\
-					./objects/Params/DoubleVecParam.h\
-					./objects/Params/StringParam.cpp\
-					./objects/Params/StringParam.h\
-					./objects/Params/MatrixParam.h\
-					./objects/Params/MatrixParam.cpp\
-					./objects/Params/VectorParam.h\
-					./objects/Params/VectorParam.cpp\
+					./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/FemModel.h\
+					./classes/FemModel.cpp\
+					./classes/objects/Material.h\
+					./classes/objects/Load.h\
+					./classes/objects/Contour.h\
+					./classes/objects/Contour.cpp\
+					./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/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/Segment.cpp\
+					./classes/objects/Vertex.h\
+					./classes/objects/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/BoolExternalResult.h\
+					./classes/objects/ExternalResults/BoolExternalResult.cpp\
+					./classes/objects/ExternalResults/DoubleExternalResult.h\
+					./classes/objects/ExternalResults/DoubleExternalResult.cpp\
+					./classes/objects/ExternalResults/DoubleVecExternalResult.h\
+					./classes/objects/ExternalResults/DoubleVecExternalResult.cpp\
+					./classes/objects/ExternalResults/DoubleMatExternalResult.h\
+					./classes/objects/ExternalResults/DoubleMatExternalResult.cpp\
+					./classes/objects/ExternalResults/IntExternalResult.h\
+					./classes/objects/ExternalResults/IntExternalResult.cpp\
+					./classes/objects/ExternalResults/StringExternalResult.h\
+					./classes/objects/ExternalResults/StringExternalResult.cpp\
+					./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/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/matrix/matrixobjects.h\
+					./classes/matrix/ElementMatrix.h\
+					./classes/matrix/ElementMatrix.cpp\
+					./classes/matrix/ElementVector.h\
+					./classes/matrix/ElementVector.cpp\
+					./classes/matrix/Matrix.h\
+					./classes/matrix/Matrix.cpp\
+					./classes/matrix/Vector.h\
+					./classes/matrix/Vector.cpp\
+					./classes/objects/Params/Param.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\
 					./Container/Container.h\
 					./Container/Constraints.h\
@@ -173,8 +184,8 @@
 					./shared/Alloc/alloc.h\
 					./shared/Alloc/alloc.cpp\
+					./shared/Alloc/xNewDelete.h\
+					./shared/MemOps/xMemCpy.h\
 					./shared/Matrix/matrix.h\
 					./shared/Matrix/MatrixUtils.cpp\
-					./shared/Dofs/dofs.h\
-					./shared/Dofs/dofsetgen.cpp\
 					./shared/Numerics/numerics.h\
 					./shared/Numerics/Verbosity.h\
@@ -202,8 +213,14 @@
 					./shared/Elements/GetGlobalDofList.cpp\
 					./shared/Elements/GetNumberOfDofs.cpp\
+					./shared/Elements/PrintArrays.cpp\
+					./shared/Elements/PddSurfaceMassBalance.cpp\
+					./shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp\
 					./shared/String/sharedstring.h\
 					./shared/Wrapper/wrappershared.h\
 					./shared/Wrapper/ModuleBoot.cpp\
 					./shared/Wrapper/ModuleEnd.cpp\
+					./shared/Sys/sys.h\
+					./shared/Sys/ProfilingStart.cpp\
+					./shared/Sys/ProfilingEnd.cpp\
 					./toolkits/metis/metisincludes.h\
 					./toolkits/issm/issmtoolkit.h\
@@ -281,4 +298,8 @@
 					./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/UpdateConstraintsx/UpdateConstraintsx.h\
 					./modules/UpdateConstraintsx/UpdateConstraintsx.cpp\
@@ -310,4 +331,5 @@
 					./modules/Solverx/Solverx.cpp\
 					./modules/Solverx/Solverx.h\
+					./modules/Solverx/SolverxSeq.cpp\
 					./modules/VecMergex/VecMergex.cpp\
 					./modules/VecMergex/VecMergex.h\
@@ -326,9 +348,24 @@
 					./solvers/solver_linear.cpp\
 					./solvers/solver_nonlinear.cpp\
-					./solvers/solver_newton.cpp
-#}}}
-#DAKOTA sources  {{{1
-dakota_sources = ./objects/DakotaPlugin.h\
-					  ./objects/DakotaPlugin.cpp\
+					./solvers/solver_newton.cpp\
+					./classes/objects/Options/Option.cpp\
+					./classes/objects/Options/Option.h\
+					./classes/objects/Options/OptionDouble.cpp\
+					./classes/objects/Options/OptionDouble.h\
+					./classes/objects/Options/OptionChar.cpp\
+					./classes/objects/Options/OptionChar.h\
+					./classes/objects/Options/OptionUtilities.cpp\
+					./classes/objects/Options/OptionUtilities.h\
+					./classes/objects/Options/OptionLogical.cpp\
+					./classes/objects/Options/OptionLogical.h\
+					./classes/objects/Options/OptionStruct.cpp\
+					./classes/objects/Options/OptionStruct.h\
+					./classes/objects/Options/OptionCell.cpp\
+					./classes/objects/Options/OptionCell.h
+
+#}}}
+#DAKOTA sources  {{{
+dakota_sources = ./classes/dakota/DakotaPlugin.h\
+					  ./classes/dakota/DakotaPlugin.cpp\
 					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h\
 					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp\
@@ -352,13 +389,13 @@
 					  ./modules/Dakotax/SpawnCoreParallel.cpp
 #}}}
-#Transient sources  {{{1
+#Transient sources  {{{
 transient_sources  = ./modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp \
 					 ./solutions/transient_core.cpp
 #}}}
-#Steadystate sources  {{{1
+#Steadystate sources  {{{
 steadystate_sources = ./solutions/steadystate_core.cpp\
 					  ./solutions/steadystateconvergence.cpp
 #}}}
-#Prognostic sources  {{{1
+#Prognostic sources  {{{
 prognostic_sources = ./modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp\
 					      ./modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp\
@@ -367,5 +404,5 @@
 						  ./solutions/prognostic_core.cpp
 #}}}
-#Thermal sources  {{{1
+#Thermal sources  {{{
 thermal_sources = ./modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp\
 					   ./modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp\
@@ -387,5 +424,5 @@
 					   ./solvers/solver_thermal_nonlinear.cpp
 #}}}
-#Control sources  {{{1
+#Control sources  {{{
 control_sources= ./modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp\
 					  ./modules/ControlInputGetGradientx/ControlInputGetGradientx.h\
@@ -426,6 +463,6 @@
 					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp\
 					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h\
-					  ./objects/Inputs/ControlInput.h\
-					  ./objects/Inputs/ControlInput.cpp\
+					  ./classes/objects/Inputs/ControlInput.h\
+					  ./classes/objects/Inputs/ControlInput.cpp\
 					  ./shared/Numerics/BrentSearch.cpp\
 					  ./shared/Numerics/OptimalSearch.cpp \
@@ -442,5 +479,5 @@
 
 #}}}
-#Hydrology sources  {{{1
+#Hydrology sources  {{{
 hydrology_sources  = ./modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp\
 					      ./modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp\
@@ -450,5 +487,5 @@
 						  ./solutions/hydrology_core_step.cpp 
 #}}}
-#Diagnostic sources  {{{1
+#Diagnostic sources  {{{
 diagnostic_sources = ./modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp\
 					      ./modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp \
@@ -471,5 +508,5 @@
 						  ./solvers/solver_stokescoupling_nonlinear.cpp
 #}}}
-#Balanced sources  {{{1
+#Balanced sources  {{{
 balanced_sources = ./modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp\
 					    ./modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp\
@@ -478,5 +515,5 @@
 						./solutions/balancethickness_core.cpp
 #}}}
-#Responses sources  {{{1
+#Responses sources  {{{
 responses_sources = ./modules/MinVelx/MinVelx.h\
 					     ./modules/MinVelx/MinVelx.cpp\
@@ -501,4 +538,6 @@
 					     ./modules/MinVzx/MinVzx.h\
 					     ./modules/MinVzx/MinVzx.cpp\
+					     ./modules/TotalSmbx/TotalSmbx.h\
+					     ./modules/TotalSmbx/TotalSmbx.cpp\
 					     ./modules/IceVolumex/IceVolumex.h\
 					     ./modules/IceVolumex/IceVolumex.cpp\
@@ -508,5 +547,5 @@
 					     ./modules/MassFluxx/MassFluxx.h
 #}}}
-#Slope sources  {{{1
+#Slope sources  {{{
 slope_sources =  ./modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp\
 					  ./modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp \
@@ -520,77 +559,78 @@
 					  ./solutions/bedslope_core.cpp
 #}}}
-#Groundingline sources  {{{1
+#Groundingline sources  {{{
 groundingline_sources= ./modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp\
 					        ./modules/GroundinglineMigrationx/GroundinglineMigrationx.h
 #}}}
-#Rifts sources  {{{1
-rifts_sources = ./objects/Loads/Riftfront.cpp\
-				    ./objects/Loads/Riftfront.h\
+#Rifts sources  {{{
+rifts_sources = ./classes/objects/Loads/Riftfront.cpp\
+				    ./classes/objects/Loads/Riftfront.h\
 				    ./modules/ConstraintsStatex/RiftConstraintsState.cpp
 #}}}
-#3D sources  {{{1
-threed_sources = ./objects/Gauss/GaussPenta.h\
-				     ./objects/Gauss/GaussPenta.cpp\
-				     ./objects/ElementResults/PentaP1ElementResult.h\
-				     ./objects/ElementResults/PentaP1ElementResult.cpp\
-				     ./objects/Inputs/PentaP1Input.h\
-				     ./objects/Inputs/PentaP1Input.cpp\
-				     ./objects/Elements/Penta.h\
-				     ./objects/Elements/Penta.cpp\
-				     ./objects/Elements/PentaHook.h\
-				     ./objects/Elements/PentaHook.cpp\
-				     ./objects/Elements/PentaRef.h\
-				     ./objects/Elements/PentaRef.cpp
-#}}}
-#Bamg sources  {{{1
-bamg_sources =  ./objects/Bamg/BamgGeom.h\
-				./objects/Bamg/BamgGeom.cpp\
-				./objects/Bamg/BamgMesh.h\
-				./objects/Bamg/BamgMesh.cpp\
-				./objects/Bamg/BamgOpts.h\
-				./objects/Bamg/BamgOpts.cpp\
-				./objects/Bamg/CrackedEdge.h\
-				./objects/Bamg/CrackedEdge.cpp\
-				./objects/Bamg/Curve.h\
-				./objects/Bamg/Curve.cpp\
-				./objects/Bamg/Direction.h\
-				./objects/Bamg/Direction.cpp\
-				./objects/Bamg/DoubleAndInt.h\
-				./objects/Bamg/Edge.h\
-				./objects/Bamg/Edge.cpp\
-				./objects/Bamg/GeomEdge.h\
-				./objects/Bamg/GeomEdge.cpp\
-				./objects/Bamg/GeomSubDomain.h\
-				./objects/Bamg/GeomSubDomain.cpp\
-				./objects/Bamg/GeomVertex.h\
-				./objects/Bamg/GeomVertex.cpp\
-				./objects/Bamg/Geometry.cpp\
-				./objects/Bamg/Geometry.h\
-				./objects/Bamg/ListofIntersectionTriangles.cpp\
-				./objects/Bamg/ListofIntersectionTriangles.h\
-				./objects/Bamg/EigenMetric.cpp\
-				./objects/Bamg/Metric.cpp\
-				./objects/Bamg/Metric.h\
-				./objects/Bamg/BamgQuadtree.cpp\
-				./objects/Bamg/BamgQuadtree.h\
-				./objects/Bamg/R2.h\
-				./objects/Bamg/SetOfE4.cpp\
-				./objects/Bamg/SetOfE4.h\
-				./objects/Bamg/SubDomain.h\
-				./objects/Bamg/SubDomain.cpp\
-				./objects/Bamg/AdjacentTriangle.h\
-				./objects/Bamg/AdjacentTriangle.cpp\
-				./objects/Bamg/Triangle.cpp\
-				./objects/Bamg/Triangle.h\
-				./objects/Bamg/BamgVertex.cpp\
-				./objects/Bamg/BamgVertex.h\
-				./objects/Bamg/VertexOnEdge.h\
-				./objects/Bamg/VertexOnEdge.cpp\
-				./objects/Bamg/VertexOnGeom.h\
-				./objects/Bamg/VertexOnGeom.cpp\
-				./objects/Bamg/VertexOnVertex.h\
-				./objects/Bamg/VertexOnVertex.cpp\
-				./objects/Bamg/Mesh.cpp\
-				./objects/Bamg/Mesh.h\
+#3D sources  {{{
+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
+#}}}
+#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\
 				./shared/Bamg/Abs.h \
 				./shared/Bamg/BigPrimeNumber.h\
@@ -609,25 +649,44 @@
 				./modules/BamgTriangulatex/BamgTriangulatex.h
 #}}}
-#Kriging sources  {{{1
+#Kriging sources  {{{
 kriging_sources = ./Container/Observations.h\
 						./Container/Observations.cpp\
-						./objects/Kriging/Variogram.h \
-						./objects/Kriging/GaussianVariogram.h\
-						./objects/Kriging/GaussianVariogram.cpp\
-						./objects/Kriging/ExponentialVariogram.h\
-						./objects/Kriging/ExponentialVariogram.cpp\
-						./objects/Kriging/SphericalVariogram.h\
-						./objects/Kriging/SphericalVariogram.cpp\
-						./objects/Kriging/PowerVariogram.h\
-						./objects/Kriging/PowerVariogram.cpp\
-						./objects/Kriging/Quadtree.h\
-						./objects/Kriging/Quadtree.cpp\
-						./objects/Kriging/Observation.h\
-						./objects/Kriging/Observation.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
 
-#}}}
-#Kml sources  {{{1
+#For parallel kriging, only difference is ./modules/Krigingx/pKrigingx.cpp with no multithreading
+pkriging_sources = ./Container/Observations.h\
+						./Container/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\
@@ -642,60 +701,60 @@
 			     ./modules/KMLOverlayx/KMLOverlayx.h\
 			     ./modules/KMLOverlayx/KMLOverlayx.cpp\
-			     ./objects/KML/KML_Attribute.cpp\
-			     ./objects/KML/KML_Attribute.h\
-			     ./objects/KML/KML_Comment.cpp\
-			     ./objects/KML/KML_Comment.h\
-			     ./objects/KML/KML_ColorStyle.cpp\
-			     ./objects/KML/KML_ColorStyle.h\
-			     ./objects/KML/KML_Container.cpp\
-			     ./objects/KML/KML_Container.h\
-			     ./objects/KML/KML_Document.cpp\
-			     ./objects/KML/KML_Document.h\
-			     ./objects/KML/KML_Feature.cpp\
-			     ./objects/KML/KML_Feature.h\
-			     ./objects/KML/KML_File.cpp\
-			     ./objects/KML/KML_File.h\
-			     ./objects/KML/KML_Folder.cpp\
-			     ./objects/KML/KML_Folder.h\
-			     ./objects/KML/KML_Geometry.cpp\
-			     ./objects/KML/KML_Geometry.h\
-			     ./objects/KML/KML_GroundOverlay.cpp\
-			     ./objects/KML/KML_GroundOverlay.h\
-			     ./objects/KML/KML_Icon.cpp\
-			     ./objects/KML/KML_Icon.h\
-			     ./objects/KML/KML_LatLonBox.cpp\
-		  	     ./objects/KML/KML_LatLonBox.h\
-			     ./objects/KML/KML_LinearRing.cpp\
-			     ./objects/KML/KML_LinearRing.h\
-			     ./objects/KML/KML_LineString.cpp\
-			     ./objects/KML/KML_LineString.h\
-			     ./objects/KML/KML_LineStyle.cpp\
-			     ./objects/KML/KML_LineStyle.h\
-			     ./objects/KML/KML_MultiGeometry.cpp\
-			     ./objects/KML/KML_MultiGeometry.h\
-			     ./objects/KML/KML_Object.cpp\
-			     ./objects/KML/KML_Object.h\
-			     ./objects/KML/KML_Overlay.cpp\
-			     ./objects/KML/KML_Overlay.h\
-			     ./objects/KML/KML_Point.cpp\
-			     ./objects/KML/KML_Point.h\
-			     ./objects/KML/KML_Placemark.cpp\
-			     ./objects/KML/KML_Placemark.h\
-			     ./objects/KML/KML_Polygon.cpp\
-			     ./objects/KML/KML_Polygon.h\
-			     ./objects/KML/KML_PolyStyle.cpp\
-			     ./objects/KML/KML_PolyStyle.h\
-			     ./objects/KML/KML_Style.cpp\
-			     ./objects/KML/KML_Style.h\
-			     ./objects/KML/KML_StyleSelector.cpp\
-			     ./objects/KML/KML_StyleSelector.h\
-			     ./objects/KML/KML_SubStyle.cpp\
-			     ./objects/KML/KML_SubStyle.h\
-			     ./objects/KML/KML_Unknown.cpp\
-			     ./objects/KML/KML_Unknown.h\
-			     ./objects/KML/KMLFileReadUtils.cpp\
-			     ./objects/KML/KMLFileReadUtils.h
-#}}}
-#Petsc sources  {{{1
+			     ./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
+#}}}
+#Petsc sources  {{{
 petsc_sources= ./toolkits/petsc\
 					./toolkits/petsc/patches\
@@ -726,4 +785,9 @@
 					./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/petscincludes.h\
 					./shared/Numerics/PetscOptionsFromAnalysis.cpp\
@@ -732,9 +796,5 @@
 
 #}}}
-#Gsl sources  {{{1
-gsl_sources= ./modules/Solverx/SolverxGsl.cpp
-
-#}}}
-#Mpi sources  {{{1
+#Mpi sources  {{{
 mpi_sources= ./toolkits/mpi/mpiincludes.h\
 				./toolkits/mpi/patches/mpipatches.h\
@@ -744,9 +804,9 @@
 				./toolkits/mpi/patches/MPI_Boundariesfromrange.cpp
 #}}}
-#Metis sources  {{{1
+#Metis sources  {{{
 metis_sources= ./toolkits/metis/patches/metispatches.h\
 					./toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
 #}}}
-#Python sources  {{{1
+#Python sources  {{{
 python_sources=     ./python/io/pythonio.h\
 					./python/python-binding.h\
@@ -756,5 +816,5 @@
 
 #}}}
-#Matlab sources  {{{1
+#Matlab sources  {{{
 matlab_sources= ./toolkits/matlab/matlabincludes.h\
 				    ./matlab/matlab-binding.h\
@@ -773,27 +833,11 @@
 					 ./matlab/io/MatlabVectorToSeqVec.cpp
 #}}}
-#Matlab and Petsc sources  {{{1
-matlabpetsc_sources= ./matlab/io/MatlabMatrixToPetscMatrix.cpp\
-					 ./matlab/io/MatlabVectorToPetscVector.cpp
-	
-#}}}
-#Modules sources{{{1
-module_sources= ./objects/Options/Option.cpp\
-			./objects/Options/Option.h\
-			./objects/Options/OptionDouble.cpp\
-			./objects/Options/OptionDouble.h\
-			./objects/Options/OptionLogical.cpp\
-			./objects/Options/OptionLogical.h\
-			./objects/Options/OptionChar.cpp\
-			./objects/Options/OptionChar.h\
-			./objects/Options/OptionStruct.cpp\
-			./objects/Options/OptionStruct.h\
-			./objects/Options/OptionCell.cpp\
-			./objects/Options/OptionCell.h\
-			./objects/Options/OptionUtilities.cpp\
-			./objects/Options/OptionUtilities.h\
-			./shared/Alloc/alloc_module.h\
-			./shared/Alloc/alloc_module.cpp\
-			./shared/Threads/issm_threads.h\
+#Matlab and Petsc sources  {{{
+matlabpetsc_sources= ./matlab/io/MatlabMatrixToPetscMat.cpp\
+					 ./matlab/io/MatlabVectorToPetscVec.cpp
+
+#}}}
+#Modules sources{{{
+module_sources= ./shared/Threads/issm_threads.h\
 			./shared/Threads/LaunchThread.cpp\
 			./shared/Threads/PartitionRange.cpp\
@@ -866,8 +910,7 @@
 #}}}
 
-#{{{1 Conditional build-up of sources
+#{{{ 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
@@ -883,8 +926,4 @@
 endif
 
-if GSL
-issm_sources  +=  $(gsl_sources)
-endif
-
 if TRANSIENT
 issm_sources  +=  $(transient_sources)
@@ -953,11 +992,22 @@
 endif
 
-
-#}}}
-#Library flags and sources {{{1
+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)
+
+#if SHARED
+#libISSM_la_SOURCES = solutions/issm.cpp
+#libISSM_la_LIBADD = @LTLIBOBJS@
+#libISSM_la_LDFLAGS = -prefer-pic
+
+#libISSMCore_la_SOURCES  = $(issm_sources)
+#libISSMOverload_la_SOURCES = ./shared/String/stricmp.c
+#endif
 
 if MODULES
@@ -967,4 +1017,5 @@
 libISSMModules_a_SOURCES += $(kml_sources)
 libISSMModules_a_CXXFLAGS = $(ALLCXXFLAGS)
+endif
 
 if PYTHON
@@ -977,12 +1028,12 @@
 libISSMMatlab_a_CXXFLAGS= $(ALLCXXFLAGS)
 endif
-endif
-#}}}
-#Overload library, to overload any non-standard symbols. {{{1
+
+#}}}
+#Overload library, to overload any non-standard symbols. {{{
 libISSMOverload_a_SOURCES = ./shared/String/stricmp.c
 libISSMOverload_a_CFLAGS  = -fPIC -D_C_ $(COPTFLAGS) $(CFLAGS)
 #}}}
 
-#Executable {{{1
+#Executable {{{
 bin_PROGRAMS = issm 
 
@@ -991,5 +1042,5 @@
 
 #External packages
-LDADD += $(PETSCLIB) $(TAOLIB) $(PLAPACKLIB) $(MUMPSLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB)
+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
@@ -999,4 +1050,10 @@
 issm_SOURCES = solutions/issm.cpp
 issm_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
+
+if KRIGING
+bin_PROGRAMS += kriging
+kriging_SOURCES = solutions/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 {{{
Index: /issm/branches/trunk-jpl-damage/src/c/classes/DofIndexing.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/DofIndexing.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/DofIndexing.cpp	(revision 12878)
@@ -0,0 +1,210 @@
+/*!\file DofIndexing.c
+ * \brief: implementation of the DofIndexing object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include "./classes.h"
+#include <string.h>
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/shared.h"
+#include "../Container/Container.h"
+#include "../include/include.h"
+
+/*DofIndexing constructors and destructor*/
+/*FUNCTION DofIndexing::DofIndexing(){{{*/
+DofIndexing::DofIndexing(){
+
+	this->gsize=UNDEF;
+	this->fsize=UNDEF;
+	this->ssize=UNDEF;
+	this->clone=0;
+	this->f_set=NULL;
+	this->s_set=NULL;
+	this->svalues=NULL;
+	this->doftype=NULL;
+	this->gdoflist=NULL;
+	this->fdoflist=NULL;
+	this->sdoflist=NULL;
+
+}
+/*}}}*/
+/*FUNCTION DofIndexing::DofIndexing(int gsize){{{*/
+DofIndexing::DofIndexing(int in_gsize){
+	this->Init(in_gsize,NULL);
+}
+/*}}}*/
+/*FUNCTION DofIndexing::DofIndexing(DofIndexing* in)  -> copy{{{*/
+DofIndexing::DofIndexing(DofIndexing* in){ //copy constructor
+
+	int i;
+	this->gsize=in->gsize;
+	this->fsize=in->fsize;
+	this->ssize=in->ssize;
+	
+	this->clone=in->clone;
+
+	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); 
+	}
+	else{
+		this->f_set=NULL;
+		this->s_set=NULL;
+		this->svalues=NULL;
+		this->doftype=NULL;
+		this->gdoflist=NULL;
+	}
+	if(this->fsize>0 && this->fsize!=UNDEF)this->fdoflist=xNew<int>(this->fsize); else this->fdoflist=NULL;
+	if(this->ssize>0 && this->ssize!=UNDEF)this->sdoflist=xNew<int>(this->ssize); else this->sdoflist=NULL;
+
+	if(this->gsize>0){
+		memcpy(this->f_set,in->f_set,this->gsize*sizeof(bool));
+		memcpy(this->s_set,in->s_set,this->gsize*sizeof(bool));
+		xMemCpy<IssmDouble>(this->svalues,in->svalues,this->gsize);
+		if(this->doftype)memcpy(this->doftype,in->doftype,this->gsize*sizeof(int));
+		memcpy(this->gdoflist,in->gdoflist,this->gsize*sizeof(int));
+	}
+	if(this->fsize>0 && this->fsize!=UNDEF)memcpy(this->fdoflist,in->fdoflist,this->fsize*sizeof(int));
+	if(this->ssize>0 && this->ssize!=UNDEF)memcpy(this->sdoflist,in->sdoflist,this->ssize*sizeof(int));
+
+}
+/*}}}*/
+/*FUNCTION DofIndexing::~DofIndexing() {{{*/
+DofIndexing::~DofIndexing(){ //destructor
+
+	xDelete<bool>(f_set); 
+	xDelete<bool>(s_set); 
+	xDelete<IssmDouble>(svalues);
+	xDelete<int>(doftype); 
+	xDelete<int>(gdoflist);
+	xDelete<int>(fdoflist);
+	xDelete<int>(sdoflist);
+
+}
+/*}}}*/
+/*FUNCTION DofIndexing::Init{{{*/
+void DofIndexing::Init(int in_gsize,int* in_doftype){
+
+	int i;
+	this->gsize=in_gsize;
+	
+	this->clone=0;
+
+	/*allocate: */
+	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);
+	}
+
+	for (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;
+	}
+}
+/*}}}*/
+/*FUNCTION DofIndexing::InitSet{{{*/
+void DofIndexing::InitSet(int setenum){
+
+	int i;
+	int size=0;
+
+	/*go through sets, and figure out how many dofs belong to this set, except for g-set, 
+	 * which has already been initialized: */
+	if(setenum==FsetEnum){
+		size=0;
+		for(i=0;i<this->gsize;i++) if(f_set[i])size++;
+		this->fsize=size;
+		xDelete<int>(this->fdoflist);
+		if(this->fsize)this->fdoflist=xNew<int>(size);
+		else this->fdoflist=NULL;
+	}
+	else if(setenum==SsetEnum){
+		size=0;
+		for(i=0;i<this->gsize;i++) if(s_set[i])size++;
+		this->ssize=size;
+		xDelete<int>(this->sdoflist);
+		if(this->ssize)this->sdoflist=xNew<int>(size);
+		else this->sdoflist=NULL;
+	}
+	else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+}
+/*}}}*/
+
+/*Some of the Object functionality: */
+/*FUNCTION DofIndexing::Echo{{{*/
+void DofIndexing::Echo(void){
+
+	int i;
+
+	_printLine_("DofIndexing:");
+	_printLine_("   gsize: " << gsize);
+	_printLine_("   clone: " << clone);
+}
+/*}}}*/
+/*FUNCTION DofIndexing::DeepEcho{{{*/
+void DofIndexing::DeepEcho(void){
+
+	int i;
+
+	_printLine_("DofIndexing:");
+	_printLine_("   gsize: " << gsize);
+	_printLine_("   fsize: " << fsize);
+	_printLine_("   ssize: " << ssize);
+	_printLine_("   clone: " << clone);
+	
+	_printLine_("   set membership: f,s sets ");
+	for(i=0;i<gsize;i++){
+		_printLine_("      dof " << i << ": " <<(f_set[i]?"true":"false")<< " " <<(s_set[i]?"true":"false"));
+	}
+
+	_printString_("   svalues (" << this->ssize << "): |");
+	for(i=0;i<this->gsize;i++){
+		if(this->s_set[i])_printString_(" " << svalues[i] << " |");
+	}
+	_printLine_("");
+
+	if(doftype){
+		_printString_("   doftype: |");
+		for(i=0;i<gsize;i++){
+			_printString_(" " << doftype[i] << " |");
+		}
+		_printLine_("");
+	}
+	else _printLine_("   doftype: NULL");
+
+	_printString_("   g_doflist (" << this->gsize << "): |");
+	for(i=0;i<this->gsize;i++){
+		_printString_(" " << gdoflist[i] << " |");
+	}
+	_printLine_("");
+
+	_printString_("   f_doflist (" << this->fsize << "): |");
+	for(i=0;i<this->fsize;i++){
+		_printString_(" " << fdoflist[i] << " |");
+	}
+	_printLine_("");
+
+	_printString_("   s_doflist (" << this->ssize << "): |");
+	for(i=0;i<this->ssize;i++){
+		_printString_(" " << sdoflist[i] << " |");
+	}
+	_printLine_("");
+}		
+/*}}}*/
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/DofIndexing.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/DofIndexing.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/DofIndexing.h	(revision 12878)
@@ -0,0 +1,54 @@
+/*!\file: DofIndexing.h
+ * \brief prototype for DofIndexing.h
+ */ 
+
+#ifndef _DOFINDEXING_H_
+#define  _DOFINDEXING_H_
+
+#include "../include/include.h"
+
+class DofIndexing{
+	
+	public:
+
+		/*sizes: */
+		int gsize; //number of dofs for a node
+		int fsize; //number of dofs solver for
+		int ssize; //number of constrained dofs
+
+		/*partitioning: */
+		int     clone;   //this node is replicated from another one 
+
+		/*boundary conditions sets: */
+		bool*     f_set; //is dof on f-set (on which we solve)
+		bool*     s_set; //is dof on s-set (on which boundary conditions -dirichlet- are applied)
+		IssmDouble*   svalues; //list of constraint values. size g_size, for ease of use.
+
+		/*types of dofs: */
+		int*     doftype; //approximation type of the dofs (used only for coupling), size g_size
+		
+		/*list of degrees of freedom: */
+		int*     gdoflist; //dof list in g_set
+		int*     fdoflist; //dof list in f_set
+		int*     sdoflist; //dof list in s_set
+
+
+		/*DofIndexing constructors, destructors {{{*/
+		DofIndexing();
+		DofIndexing(int g_size);
+		void Init(int g_size,int* doftype);
+		void InitSet(int setenum);
+		DofIndexing(DofIndexing* properties);
+		~DofIndexing();
+		/*}}}*/
+		/*Object like functionality: {{{*/
+		void  Echo(void); 
+		void  DeepEcho(void); 
+		void  copy(DofIndexing* properties);
+		/*}}}*/
+		/*DofIndexing management: {{{*/
+		DofIndexing* Spawn(int* indices, int numindices);
+		/*}}}*/
+
+};
+#endif //ifndef _DOFINDEXING_H_
Index: /issm/branches/trunk-jpl-damage/src/c/classes/FemModel.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/FemModel.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/FemModel.cpp	(revision 12878)
@@ -0,0 +1,159 @@
+/*!\file FemModel.c
+ * \brief: implementation of the FemModel object
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include "../Container/Container.h"
+#include "../modules/ModelProcessorx/ModelProcessorx.h"
+#include "../io/io.h"
+#include "./classes.h"
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../modules/modules.h"
+
+/*Object constructors and destructor*/
+/*FUNCTION FemModel::constructor {{{*/
+FemModel::FemModel(char* inputfilename, char* outputfilename, const int in_solution_type,const int* analyses,const int nummodels){
+
+	/*intermediary*/
+	int         i;
+	int         analysis_type;
+	FILE       *IOMODEL = NULL;
+	extern int  my_rank;
+
+	/*Open input file on cpu 0: */
+	if(my_rank==0) IOMODEL = pfopen(inputfilename ,"rb");
+
+	/*Initialize internal data: */
+	this->nummodels=nummodels;
+	this->solution_type=in_solution_type;
+	this->analysis_counter=nummodels-1; //point to last analysis_type carried out.
+	this->results=new Results(); //not initialized by CreateDataSets
+	
+	/*Dynamically allocate whatever is a list of length nummodels: */
+	analysis_type_list=xNew<int>(nummodels);
+
+	/*Initialize: */
+	for(i=0;i<nummodels;i++)analysis_type_list[i]=analyses[i];
+
+	/*create datasets for all analyses*/
+	ModelProcessorx(&this->elements,&this->nodes,&this->vertices,&this->materials,&this->constraints,&this->loads,&this->parameters,IOMODEL,this->solution_type,nummodels,analyses);
+
+	/*do the post-processing of the datasets to get an FemModel that can actually run analyses: */
+	for(i=0;i<nummodels;i++){
+
+		if(VerboseMProcessor()) _pprintLine_("   Processing finite element model of analysis " << EnumToStringx(analysis_type_list[i]) << ":");
+		analysis_type=analysis_type_list[i];
+		this->SetCurrentConfiguration(analysis_type);
+	
+		if(i==0){
+			if(VerboseMProcessor()) _pprintLine_("      creating vertex degrees of freedom");
+			VerticesDofx(vertices,parameters); //only call once, we only have one set of vertices
+		}
+
+		if(VerboseMProcessor()) _pprintLine_("      resolving node constraints");
+		SpcNodesx(nodes,constraints,parameters,analysis_type); 
+
+		if(VerboseMProcessor()) _pprintLine_("      creating nodal degrees of freedom");
+		NodesDofx(nodes,parameters,analysis_type);
+	
+		if(VerboseMProcessor()) _pprintLine_("      configuring element and loads");
+		ConfigureObjectsx(elements, loads, nodes, vertices, materials,parameters);
+	}
+	
+	/*Close input file descriptors: */
+	if(my_rank==0) pfclose(IOMODEL,inputfilename);
+
+	/*Add output file name to parameters: */
+	this->parameters->AddObject(new StringParam(OutputfilenameEnum,outputfilename));
+
+}
+
+/*}}}*/
+/*FUNCTION FemModel::destructor {{{*/
+FemModel::~FemModel(){
+
+	/*Intermediary*/
+	int i;
+
+	/*Delete all the datasets: */
+	xDelete<int>(analysis_type_list);
+	delete elements;
+	delete nodes;
+	delete vertices;
+	delete constraints;
+	delete loads;
+	delete materials;
+	delete parameters;
+	delete results;
+
+}
+/*}}}*/
+
+/*Object management*/
+/*FUNCTION FemModel::Echo {{{*/
+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]));
+
+}
+/*}}}*/
+
+/*Numerics: */
+/*FUNCTION FemModel::SetCurrentConfiguration(int configuration_type,int analysis_type){{{*/
+void FemModel::SetCurrentConfiguration(int configuration_type,int analysis_type){
+
+	/*Use configuration_type to setup the analysis counter, the configurations of objects etc ... but use 
+	 * analysis_type to drive the element numerics. This allows for use of 1 configuration_type for several 
+	 * analyses. For example: do a SurfaceSlopeX, SurfaceSlopeY, BedSlopeX and BedSlopeY analysis using the 
+	 * Slope configuration.*/
+
+	int found=-1;
+	for(int i=0;i<nummodels;i++){
+		if (analysis_type_list[i]==configuration_type){
+			found=i;
+			break;
+		}
+	}
+	if(found!=-1) analysis_counter=found;
+	else _error2_("Could not find alias for analysis_type " << EnumToStringx(configuration_type) << " in list of FemModel analyses");
+
+	/*Now, plug analysis_counter and analysis_type inside the parameters: */
+	this->parameters->SetParam(analysis_counter,AnalysisCounterEnum);
+	this->parameters->SetParam(analysis_type,AnalysisTypeEnum);
+	this->parameters->SetParam(configuration_type,ConfigurationTypeEnum);
+
+	/*configure elements, loads and nodes, for this new analysis: */
+	this->elements->SetCurrentConfiguration(elements,loads, nodes,vertices, materials,parameters);
+	this->nodes->SetCurrentConfiguration(elements,loads, nodes,vertices, materials,parameters);
+	this->loads->SetCurrentConfiguration(elements, loads, nodes,vertices, materials,parameters);
+
+	#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
+
+}
+/*}}}*/
+/*FUNCTION FemModel::SetCurrentConfiguration(int configuration_type){{{*/
+void FemModel::SetCurrentConfiguration(int configuration_type){
+
+	/*overload: analysis_type = configuration_type: */
+	this->SetCurrentConfiguration(configuration_type,configuration_type);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/FemModel.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/FemModel.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/FemModel.h	(revision 12878)
@@ -0,0 +1,57 @@
+/*
+ * FemModel.h: 
+ */
+
+#ifndef _FEMMODEL_H_
+#define _FEMMODEL_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./objects/Object.h"
+#include "../toolkits/toolkits.h"
+class DataSet;
+class Parameters;
+class NodeSets;
+class Nodes;
+class Vertices;
+class Results;
+class Constraints;
+class Loads;
+class Materials;
+/*}}}*/
+
+
+class FemModel {
+
+	/*no private members, as we need access to these datasets quite often!:*/
+
+	public:
+
+		int                 nummodels;
+		int                 solution_type;
+		int*                analysis_type_list; //list of analyses this femmodel is going to carry out
+		int                 analysis_counter; //counter into analysis_type_list
+		
+		Elements*           elements; //elements (one set for all analyses)
+		Nodes*              nodes; //one set of nodes
+		Vertices*           vertices; //one set of vertices
+		Constraints*        constraints; //one set of constraints. each constraint knows which analysis_type it handles
+		Loads*              loads;  //one set of constraints. each constraint knows which analysis_type it handles
+		Materials*          materials;  //one set of materials, for each element
+		Parameters*         parameters; //one set of parameters, independent of the analysis_type
+		Results*            results; //results that cannot be fit into the elements (such as one time constants, arrays, strings, etc ...)
+
+		/*constructors, destructors: */
+		FemModel(char* inputfilename, char* outputfilename, const int solution_type,const int* analyses,const int nummodels);
+		~FemModel();
+
+		/*Methods: */
+		void Echo();
+
+		/*Fem: */
+		void  SetCurrentConfiguration(int configuration_type);
+		void  SetCurrentConfiguration(int configuration_type,int analysis_type);
+
+};
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/Hook.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/Hook.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/Hook.cpp	(revision 12878)
@@ -0,0 +1,266 @@
+/*!\file Hook.cpp
+ * \brief: implementation of the Hook object: see Hook.h for more explanations.
+ */
+
+
+#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 "../Container/Container.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+
+
+/*Constructor/Destructors*/
+/*FUNCTION Hook::Hook(){{{*/
+Hook::Hook(){
+	this->num=0;
+	this->objects=NULL;
+	this->ids=NULL;
+	this->offsets=NULL;
+	return;
+}
+/*}}}*/
+/*FUNCTION Hook::Hook(int* ids, int num){{{*/
+Hook::Hook(int* in_ids, int in_num){
+
+	/*Intermediaries*/
+	int i;
+
+	/*Get number of objects to hook*/
+	this->num=in_num;
+
+	/*Get out if num=0*/
+	if (num==0){
+		/*Empty hook*/
+		this->ids=NULL;
+		this->objects=NULL;
+		this->offsets=NULL;
+	}
+	else{
+		/*Allocate: */
+		this->objects=xNew<Object*>(this->num);
+		this->ids=xNew<int>(this->num);
+		this->offsets=xNew<int>(this->num);
+
+		/*Copy ids: */
+		for (i=0;i<this->num;i++){
+			this->ids[i]=in_ids[i];
+			this->objects[i]=NULL;
+			this->offsets[i]=0;
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Hook::~Hook(){{{*/
+Hook::~Hook(){
+	/*deallocate: */
+	xDelete<Object*>(this->objects);
+	xDelete<int>(this->ids);
+	xDelete<int>(this->offsets);
+	return;
+}
+/*}}}*/
+
+/*Some of the Object functionality: */
+/*FUNCTION Hook::Echo{{{*/
+void Hook::Echo(void){
+
+	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_("");
+	}
+	else{
+		_printLine_("   Hook: num=0 ");
+	}
+}
+/*}}}*/
+/*FUNCTION Hook::DeepEcho{{{*/
+void Hook::DeepEcho(void){
+
+	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");
+		else{
+			_printString_("      objects:\n   ");
+			for (i=0;i<this->num;i++){
+				_printLine_("         object " << i);
+				if(objects[i]) objects[i]->DeepEcho();
+				else           _printLine_("            no object hooked yet (not configured)");
+			}
+		}
+	}
+	else{
+		_printLine_("   Hook: num=0 ");
+	}
+}
+/*}}}*/
+/*FUNCTION Hook::copy {{{*/
+Object* Hook::copy(void){
+
+	int i;
+
+	/*output: */
+	Hook* output=NULL;
+
+	/*initalize output: */
+	output=new Hook();
+
+	/*copy in the fields: */
+	output->num=this->num;
+	if(output->num){
+		output->objects=xNew<Object*>(output->num);
+		output->ids=xNew<int>(output->num);
+		output->offsets=xNew<int>(output->num);
+	}
+	
+	for(i=0;i<output->num;i++){
+		output->objects[i]=this->objects[i];
+		output->offsets[i]=this->offsets[i];
+		output->ids[i]=this->ids[i];
+	}
+
+	return (Object*)output;
+}
+/*}}}*/
+
+/*Hook management: */
+/*FUNCTION Hook::configure{{{*/
+void Hook::configure(DataSet* dataset){
+
+	/*intermediary: */
+	Object* object=NULL;
+	int i;
+
+	/*Checks if debugging mode*/
+	_assert_(this->num==0 || this->ids!=NULL);
+
+	for(i=0;i<this->num;i++){
+
+		/*is this object id -1? If so, drop this search, it was not requested: */
+		if (this->ids[i]==-1) continue;
+
+		/*Check whether existing this->objects are correct: */
+		if(this->objects[i]){
+			if(this->objects[i]->Id()==this->ids[i]) continue; //this node is good.
+			else this->objects[i]=NULL; //this node was incorrect, reset it.
+		}
+
+		/*May be the object this->offsets into this->objects are valid?: */
+		if(this->offsets[i]!=UNDEF){
+			/* Look at the this->offsets[i]'th node in the nodes dataset. If it has the correct id, 
+			 * we are good: */
+			object=(Object*)dataset->GetObjectByOffset(this->offsets[i]);
+			if (object->Id()==this->ids[i]){
+				this->objects[i]=object;
+				continue;
+			}
+			else this->offsets[i]=UNDEF; //object offset was wrong, reset it.
+		}
+
+		/*Now, for this->objects that did not get resolved, and for which we have no offset, chase them in the dataset, by id: */
+		if(this->objects[i]==NULL){
+			this->objects[i]=(Object*)dataset->GetObjectById(this->offsets+i,this->ids[i]); //remember the offset for later on.
+			/*check the id is correct!: */
+			if (this->objects[i]->Id()!=this->ids[i]) _error2_("wrong id: " << this->objects[i]->Id() << " vs " << this->ids[i] << "  in resolved pointer!");
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Hook::delivers{{{*/
+Object* Hook::delivers(void){
+	
+	/*first, check that we only have one T object in our object list: */
+	if (this->num!=1) _error2_("trying to delivery a single hook object when hook holds " << this->num << " objects" << "\n");
+
+	/*check NULL: */
+	if (this->objects==NULL) _error2_("hook is not pointing to any object, objects pointer is NULL");
+
+	return *objects;
+}
+
+/*}}}*/
+/*FUNCTION Hook::deliverp{{{*/
+Object** Hook::deliverp(void){
+	return objects;
+}
+/*}}}*/
+/*FUNCTION Hook::Ids{{{*/
+int* Hook::Ids(void){
+	return this->ids;
+}
+/*}}}*/
+/*FUNCTION Hook::GetNum{{{*/
+int Hook::GetNum(void){
+	return this->num;
+}
+/*}}}*/
+/*FUNCTION Hook::GetObjects{{{*/
+Object** Hook::GetObjects(void){
+	return this->objects;
+}
+/*}}}*/
+/*FUNCTION Hook::GetOffsets{{{*/
+int* Hook::GetOffsets(void){
+	return this->offsets;
+}
+/*}}}*/
+/*FUNCTION Hook::Spawn{{{*/
+Hook* Hook::Spawn(int* indices, int numindices){
+
+	int i;
+
+	/*output: */
+	Hook* output=NULL;
+
+	/*allocate: */
+	output=new Hook();
+
+	/*If this Hook is empty, simply return*/
+	if(this->num==0){
+		output->num=0;
+		return output;
+	}
+
+	/*Else, check that we are requesting a half of num*/
+	if (numindices>this->num) _error2_("Cannot spawn hook with " << numindices << " objects from a Hook of " << this->num << " objects");
+
+	/*go pickup the correct objects, ids and offsets :*/
+	output->num=numindices;
+	if(output->num<1) _error2_("Trying to spawn an empty ElementProperties!");
+
+	output->objects=xNew<Object*>(output->num);
+	output->ids=xNew<int>(output->num);
+	output->offsets=xNew<int>(output->num);
+
+	for(i=0;i<output->num;i++){
+		output->objects[i]=this->objects[indices[i]];
+		output->ids[i]=this->ids[indices[i]];
+		output->offsets[i]=this->offsets[indices[i]];
+	}
+
+	return output;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/Hook.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/Hook.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/Hook.h	(revision 12878)
@@ -0,0 +1,50 @@
+/*!\file Hook.h
+ * \brief: header file for hook object.
+ * A hook is a class  that can store the id, offset, and object corresponding to this id and offset into a dataset.
+ * For example, an element has a hook to its nodes. A node has a hook to its vertex.  The hook abstracts the need for having
+ * ids and offsets (necesarry for proper configuration of an object) in our objects. 
+ */
+
+#ifndef _HOOK_H_
+#define _HOOK_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./objects/Object.h"
+class DataSet;
+/*}}}*/
+
+class Hook{
+
+	private: 
+
+		int	   num; //number of objects being hooked onto
+		Object**	   objects; //list of object pointers. we do not allocate objects, just a list a pointers, that will get to point to the real objects from a dataset.
+		int*   ids;     //list of object ids, to go look for them in datasets.
+		int*   offsets;  //list of object offsets into datasets, to speed up lookup.
+
+	public:
+
+		/*Hook constructors, destructors: {{{*/
+		Hook();
+		Hook(int* ids, int num);
+		~Hook();
+		/*}}}*/
+		/*Object like functionality:{{{*/
+		void       Echo(void);
+		void       DeepEcho(void);
+		Object*    copy(void);
+		/*}}}*/
+		/*Hook management: {{{*/
+		Object*    delivers(void); //single object deliver
+		Object**   deliverp(void); //deliver all objects
+		void       configure(DataSet* dataset);
+		Hook*      Spawn(int* indices, int numindices);
+		Object**   GetObjects(void);
+		int*       Ids(void);
+		int*       GetOffsets(void);
+		int        GetNum(void);
+		/*}}}*/
+};
+
+#endif  /* _HOOK_H_ */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/IoModel.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/IoModel.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/IoModel.cpp	(revision 12878)
@@ -0,0 +1,1250 @@
+/*! \file IoModel.cpp
+ * \brief  file containing the methods that will help in processing the input data coming 
+ * into ISSM, from Matlab, or through a binary file opened for reading.
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+#include "./classes.h"
+#include "../io/io.h"
+#include "./Container/Parameters.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../include/include.h"
+
+/*FUNCTION IoModel::IoModel(){{{*/
+IoModel::IoModel(){
+	this->fid=NULL;
+	this->data=NULL;
+	this->constants=NULL;
+	
+	this->my_elements=NULL;
+	this->my_nodes=NULL;
+	this->my_vertices=NULL;
+	this->singlenodetoelementconnectivity=NULL;
+	this->numbernodetoelementconnectivity=NULL;
+	
+	this->nodecounter=0;
+	this->loadcounter=0;
+	this->constraintcounter=0;
+}
+/*}}}*/
+/*FUNCTION IoModel::IoModel(FILE*  iomodel_handle){{{*/
+IoModel::IoModel(FILE* iomodel_handle){
+	
+	/*First, keep track of the file handle: */
+	this->fid=iomodel_handle;
+
+	/*Check that Enums are Synchronized*/
+	this->CheckEnumSync();
+
+	/*Initialize and read constants:*/
+	this->constants=new Parameters();
+	this->FetchConstants(); /*this routine goes through the input file, and fetches bools, ints, IssmDoubles and strings only, nothing memory intensive*/
+
+	/*Initialize data: */
+	this->data=xNew<IssmDouble*>(MaximumNumberOfEnums);
+	for(int i=0;i<MaximumNumberOfEnums;i++) this->data[i]=NULL;
+	
+	/*Initialize permanent data: */
+	this->my_elements=NULL;
+	this->my_nodes=NULL;
+	this->my_vertices=NULL;
+	this->singlenodetoelementconnectivity=NULL;
+	this->numbernodetoelementconnectivity=NULL;
+	
+	this->nodecounter=0;
+	this->loadcounter=0;
+	this->constraintcounter=0;
+}
+/*}}}*/
+/*FUNCTION IoModel::~IoModel(){{{*/
+IoModel::~IoModel(){
+
+	if(this->constants) delete this->constants;
+
+	/*Some checks in debugging mode*/
+	#ifdef _ISSM_DEBUG_
+	if(this->data){
+		for(int i=0;i<MaximumNumberOfEnums;i++){
+			if(this->data[i]){
+				_pprintLine_("Info: previous pointer of " << EnumToStringx(i) << " has not been freed (DeleteData has not been called)");
+			}
+		}
+	}
+	#endif
+
+	xDelete<IssmDouble*>(this->data);
+	xDelete<bool>(this->my_elements);
+	xDelete<bool>(this->my_nodes);
+	xDelete<int>(this->my_vertices);
+	xDelete<int>(this->singlenodetoelementconnectivity);
+	xDelete<int>(this->numbernodetoelementconnectivity);
+}
+/*}}}*/
+
+/*FUNCTION IoModel::CheckEnumSync{{{*/
+void  IoModel::CheckEnumSync(void){
+
+	extern int my_rank;
+	int record_enum = 0;
+
+	/*Check that some fields have been allocated*/
+	_assert_(this->fid || my_rank);
+
+	/*Go find in the binary file, the position of the data we want to fetch: */
+	if(my_rank==0){ //cpu 0
+
+		/*First set FILE* position to the beginning of the file: */
+		fseek(this->fid,0,SEEK_SET);
+
+		/*Get first Enum*/
+		if(fread(&record_enum,sizeof(int),1,this->fid)==0){
+			_error2_("Marshalled file is empty");
+		}
+		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_("");
+				_error2_("Enums not consistent (See error message above)");
+			}
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION IoModel::Constant(bool* poutput,int constant_enum){{{*/
+void IoModel::Constant(bool* poutput,int constant_enum){
+
+	_assert_(constant_enum>=0);
+	_assert_(this->constants);
+
+	this->constants->FindParam(poutput,constant_enum);
+}
+/*}}}*/
+/*FUNCTION IoModel::Constant(int* poutput,int constant_enum){{{*/
+void IoModel::Constant(int* poutput,int constant_enum){
+
+	_assert_(constant_enum>=0);
+	_assert_(this->constants);
+
+	this->constants->FindParam(poutput,constant_enum);
+}
+/*}}}*/
+/*FUNCTION IoModel::Constant(IssmDouble* poutput,int constant_enum){{{*/
+void IoModel::Constant(IssmDouble* poutput,int constant_enum){
+
+	_assert_(constant_enum>=0);
+	_assert_(this->constants);
+
+	this->constants->FindParam(poutput,constant_enum);
+}
+/*}}}*/
+/*FUNCTION IoModel::Constant(char** poutput,int constant_enum){{{*/
+void IoModel::Constant(char** poutput,int constant_enum){
+
+	_assert_(constant_enum>=0);
+	_assert_(this->constants);
+
+	this->constants->FindParam(poutput,constant_enum);
+}
+/*}}}*/
+/*FUNCTION IoModel::CopyConstantObject{{{*/
+Param* IoModel::CopyConstantObject(int constant_enum){
+
+	_assert_(this->constants);
+
+	/*Find constant*/
+	Param* param=(Param*)this->constants->FindParamObject(constant_enum);
+	if(!param) _error2_("Constant " << EnumToStringx(constant_enum) << " not found in iomodel");
+
+	return (Param*)param->copy();
+}
+/*}}}*/
+/*FUNCTION IoModel::Data{{{*/
+IssmDouble* IoModel::Data(int data_enum){
+
+	_assert_(data_enum<MaximumNumberOfEnums);
+	_assert_(data_enum>=0);
+
+	return this->data[data_enum];
+}
+/*}}}*/
+/*FUNCTION IoModel::DeleteData{{{*/
+void  IoModel::DeleteData(int num,...){
+
+	va_list ap;
+	int     dataenum;
+	int     i;
+	DoubleMatParam* parameter=NULL;
+
+	/*Go through the entire list of enums and delete the corresponding data from the iomodel-data dataset: */
+
+	va_start(ap,num);
+	for(i = 0; i <num; i++){
+		dataenum=va_arg(ap, int);
+		_assert_(dataenum<MaximumNumberOfEnums);
+		xDelete<IssmDouble>(this->data[dataenum]);
+	}
+	va_end(ap);
+} /*}}}*/
+/*FUNCTION IoModel::FetchConstants{{{*/
+void  IoModel::FetchConstants(void){
+
+	extern int my_rank;
+	extern int num_procs;
+	
+	/*record descriptions; */
+	int record_enum;
+	int record_length;
+	int record_code; //1 to 7 number
+
+	/*records: */
+	int  booleanint=0;
+	int  integer=0;
+	IssmPDouble scalar=0;
+	char* string=NULL;
+	int   string_size;
+
+	/*Check that some fields have been allocated*/
+	_assert_(this->fid || my_rank);
+	_assert_(this->constants);
+
+	/*Go find in the binary file, the position of the data we want to fetch: */
+	if(my_rank==0){ //cpu 0{{{
+	
+		/*First set FILE* position to the beginning of the file: */
+		fseek(this->fid,0,SEEK_SET);
+
+		/*Now march through file looking for the correct data identifiers (bool,int,IssmDouble or string): */
+		for(;;){
+			if(fread(&record_enum,sizeof(int),1,this->fid)==0){
+
+				/*Ok, we have reached the end of the file. break: */
+				record_code=0; //0 means bailout
+				#ifdef _HAVE_MPI_
+				MPI_Bcast(&record_code,1,MPI_INT,0,MPI_COMM_WORLD);  /*tell others cpus we are bailing: */
+				#endif
+				break;
+			}
+			else{
+			
+				/* 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);
+					
+				#ifdef _HAVE_MPI_
+				/*Tell other cpus what we are doing: */
+				MPI_Bcast(&record_code,1,MPI_INT,0,MPI_COMM_WORLD);  /*tell other cpus what we are going to do: */
+
+				/*Tell other cpus the name of the data, then branch according to the data type: */
+				MPI_Bcast(&record_enum,1,MPI_INT,0,MPI_COMM_WORLD);  
+				MPI_Bcast(&record_length,1,MPI_INT,0,MPI_COMM_WORLD);  
+				#endif
+				
+				switch(record_code){
+					case 1: 
+						/*Read the boolean and broadcast it to other cpus:*/
+						if(fread(&booleanint,sizeof(int),1,this->fid)!=1) _error2_("could not read boolean ");
+						#ifdef _HAVE_MPI_
+						MPI_Bcast(&booleanint,1,MPI_INT,0,MPI_COMM_WORLD); 
+						#endif
+
+						/*create BoolParam: */
+						this->constants->AddObject(new BoolParam(record_enum,(bool)booleanint)); //cast to boolean
+
+						break;
+					case 2:
+						/*Read the integer and broadcast it to other cpus:*/
+						if(fread(&integer,sizeof(int),1,this->fid)!=1) _error2_("could not read integer ");
+						#ifdef _HAVE_MPI_
+						MPI_Bcast(&integer,1,MPI_INT,0,MPI_COMM_WORLD); 
+						#endif
+
+						/*create IntParam: */
+						this->constants->AddObject(new IntParam(record_enum,integer));
+
+						break;
+					case 3:
+						/*Read the scalar and broadcast it to other cpus:*/
+						if(fread(&scalar,sizeof(IssmPDouble),1,this->fid)!=1) _error2_("could not read scalar ");
+						#ifdef _HAVE_MPI_
+						MPI_Bcast(&scalar,1,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+						#endif
+
+						/*create DoubleParam: */
+						this->constants->AddObject(new DoubleParam(record_enum,scalar));
+
+						break;
+					case 4: 
+						/*We have to read a string from disk. First read the dimensions of the string, then the string: */
+						if(fread(&string_size,sizeof(int),1,this->fid)!=1) _error2_("could not read length of string ");
+						#ifdef _HAVE_MPI_
+						MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD); 
+						#endif
+
+						if(string_size){
+							string=xNew<char>(string_size+1);
+							string[string_size]='\0';
+
+							/*Read string, then broadcast: */
+							if(fread(string,string_size*sizeof(char),1,this->fid)!=1)_error2_(" could not read string ");
+							#ifdef _HAVE_MPI_
+							MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
+							#endif
+						}
+						else{
+							string=xNew<char>(1);
+							string[0]='\0';
+						}
+						
+						/*Add string to parameters: */
+						this->constants->AddObject(new StringParam(record_enum,string));
+
+						/*Free string*/
+						xDelete<char>(string);
+
+						break;
+					case 5: 
+							/*We are not interested in this record, too memory intensive. Skip it: */
+							/*skip: */
+							fseek(fid,-sizeof(int),SEEK_CUR); //backtrak 1 integer
+							fseek(fid,record_length,SEEK_CUR);
+							break;
+					case 6: 
+							/*We are not interested in this record, too memory intensive. Skip it: */
+							/*skip: */
+							fseek(fid,-sizeof(int),SEEK_CUR); //backtrak 1 integer
+							fseek(fid,record_length,SEEK_CUR);
+							break;
+					case 7: 
+							/*We are not interested in this record, too memory intensive. Skip it: */
+							/*skip: */
+							fseek(fid,-sizeof(int),SEEK_CUR); //backtrak 1 integer
+							fseek(fid,record_length,SEEK_CUR);
+							break;
+
+					case 8: 
+							/*We are not interested in this record, too memory intensive. Skip it: */
+							/*skip: */
+							fseek(fid,-sizeof(int),SEEK_CUR); //backtrak 1 integer
+							fseek(fid,record_length,SEEK_CUR);
+							break;
+
+					case 9: 
+							/*We are not interested in this record, too memory intensive. Skip it: */
+							/*skip: */
+							fseek(fid,-sizeof(int),SEEK_CUR); //backtrak 1 integer
+							fseek(fid,record_length,SEEK_CUR);
+							break;
+
+					default: 
+						_error2_("unknown record type:" << record_code); 
+						break;;
+				}
+			}
+		}
+	} //}}}
+	#ifdef _HAVE_MPI_
+	else{ //cpu ~0 {{{
+		for(;;){ //wait on cpu 0
+			MPI_Bcast(&record_code,1,MPI_INT,0,MPI_COMM_WORLD);  /*get from cpu 0 what we are going to do: */
+			if(record_code==0){
+				break; //we are done, break from the loop
+			}
+			else{
+				MPI_Bcast(&record_enum,1,MPI_INT,0,MPI_COMM_WORLD);   //get from cpu 0 name of the data
+				MPI_Bcast(&record_length,1,MPI_INT,0,MPI_COMM_WORLD);  
+				switch(record_code){
+				case 1: 
+					/*boolean. get it from cpu 0 */
+					MPI_Bcast(&booleanint,1,MPI_INT,0,MPI_COMM_WORLD); 
+						
+					/*create BoolParam: */
+					this->constants->AddObject(new BoolParam(record_enum,(bool)booleanint)); //cast to a boolean
+					break;
+
+				case 2:
+					/*integer. get it from cpu 0 */
+					MPI_Bcast(&integer,1,MPI_INT,0,MPI_COMM_WORLD); 
+						
+					/*create IntParam: */
+					this->constants->AddObject(new IntParam(record_enum,integer));
+
+					break;
+				case 3:
+					/*scalar. get it from cpu 0 */
+					MPI_Bcast(&scalar,1,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+						
+					/*create DoubleParam: */
+					this->constants->AddObject(new DoubleParam(record_enum,scalar));
+
+					break;
+				case 4: 
+					MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD); 
+					if(string_size){
+						string=xNew<char>((string_size+1));
+						string[string_size]='\0';
+
+						/*Read string from cpu 0: */
+						MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
+					}
+					else{
+						string=xNew<char>(1);
+						string[0]='\0';
+					}
+					/*Add string to parameters: */
+					this->constants->AddObject(new StringParam(record_enum,string));
+
+					/*Free string*/
+					xDelete<char>(string);
+
+					break;
+				case 5: break; //do nothing. not interested in this type of data, which is memory intensive.
+				case 6: break; //do nothing. not interested in this type of data, which is memory intensive.
+				case 7: break; //do nothing. not interested in this type of data, which is memory intensive.
+				case 8: break; //do nothing. not interested in this type of data, which is memory intensive.
+				case 9: break; //do nothing. not interested in this type of data, which is memory intensive.
+
+				default: 
+					_error2_("unknown record type:" << record_code); 
+					break;;
+				}
+
+
+			}
+		}
+	} //}}}
+	#endif
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(bool*     pbool,int data_enum){{{*/
+void  IoModel::FetchData(bool* pboolean,int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+	
+
+	/*output: */
+	int   booleanint;
+	int   code;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
+
+	if(code!=1)_error2_("expecting a boolean for enum " << EnumToStringx(data_enum));
+	
+	/*We have to read a boolean from disk. */
+	if(my_rank==0){  
+		if(fread(&booleanint,sizeof(int),1,fid)!=1) _error2_("could not read boolean ");
+	}
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&booleanint,1,MPI_INT,0,MPI_COMM_WORLD); 
+	#endif
+
+	/*cast to bool: */
+	/*Assign output pointers: */
+	*pboolean=(bool)booleanint;
+
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(int*      pinteger,int data_enum){{{*/
+void  IoModel::FetchData(int* pinteger,int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+
+	/*output: */
+	int   integer;
+	int   code;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
+	
+	if(code!=2)_error2_("expecting an integer for enum " << EnumToStringx(data_enum));
+	
+	/*We have to read a integer from disk. First read the dimensions of the integer, then the integer: */
+	if(my_rank==0){  
+		if(fread(&integer,sizeof(int),1,fid)!=1) _error2_("could not read integer ");
+	}
+
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&integer,1,MPI_INT,0,MPI_COMM_WORLD); 
+	#endif
+
+	/*Assign output pointers: */
+	*pinteger=integer;
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(IssmDouble*   pscalar,int data_enum){{{*/
+void  IoModel::FetchData(IssmDouble* pscalar,int data_enum){
+
+
+	extern int my_rank;
+	extern int num_procs;
+	
+
+	/*output: */
+	IssmPDouble   scalar;
+	int      code;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
+	
+	if(code!=3)_error2_("expecting a IssmDouble for enum " << EnumToStringx(data_enum));
+	
+	/*We have to read a scalar from disk. First read the dimensions of the scalar, then the scalar: */
+	if(my_rank==0){
+		if(fread(&scalar,sizeof(IssmPDouble),1,fid)!=1)_error2_("could not read scalar ");
+	}
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&scalar,1,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+	#endif
+
+	/*Assign output pointers: */
+	*pscalar=scalar;
+		 
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(char**    pstring,int data_enum){{{*/
+void  IoModel::FetchData(char** pstring,int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+	
+
+	/*output: */
+	char* string=NULL;
+	int   string_size;
+	int code=0;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
+	
+	if(code!=4)_error2_("expecting a string for enum " << EnumToStringx(data_enum));
+	
+	/*Now fetch: */
+	
+	/*We have to read a string from disk. First read the dimensions of the string, then the string: */
+	if(my_rank==0){  
+		if(fread(&string_size,sizeof(int),1,fid)!=1) _error2_("could not read length of string ");
+	}
+
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD); 
+	#endif
+
+	/*Now allocate string: */
+	if(string_size){
+		string=xNew<char>((string_size+1));
+		string[string_size]='\0';
+
+		/*Read string on node 0, then broadcast: */
+		if(my_rank==0){  
+			if(fread(string,string_size*sizeof(char),1,fid)!=1)_error2_(" could not read string ");
+		}
+		#ifdef _HAVE_MPI_
+		MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
+		#endif
+	}
+	else{
+		string=xNew<char>(1);
+		string[0]='\0';
+	}
+
+
+	/*Assign output pointers: */
+	*pstring=string;
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(int**     pintegerematrix,int* pM,int* pN,int data_enum){{{*/
+void  IoModel::FetchData(int** pmatrix,int* pM,int* pN,int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+	int i,j;
+
+	/*output: */
+	int M,N;
+	IssmPDouble* matrix=NULL;
+	int*    integer_matrix=NULL;
+	int code=0;
+	int vector_type=0;
+	
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,&vector_type,data_enum);
+
+	if((code!=5) && (code!=6) && (code!=7))_error2_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum));
+	
+	/*Now fetch: */
+
+	/*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) _error2_("could not read number of rows for matrix ");
+	}
+
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD); 
+	#endif
+
+	if(my_rank==0){  
+		if(fread(&N,sizeof(int),1,fid)!=1) _error2_("could not read number of columns for matrix ");
+	}
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD);
+	#endif
+
+	/*Now allocate matrix: */
+	if(M*N){
+		matrix=xNew<IssmPDouble>(M*N);
+
+		/*Read matrix on node 0, then broadcast: */
+		if(my_rank==0){  
+			if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error2_("could not read matrix ");
+		}
+		
+		#ifdef _HAVE_MPI_
+		MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+		#endif
+	}
+
+	/*Now cast to integer: */
+	if(M*N){
+		integer_matrix=xNew<int>(M*N);
+		for (i=0;i<M;i++){
+			for (j=0;j<N;j++){
+				integer_matrix[i*N+j]=(int)matrix[i*N+j];
+			}
+		}
+	}
+	else{
+		integer_matrix=NULL;
+	}
+	/*Free ressources:*/
+	xDelete<IssmPDouble>(matrix);
+
+	/*Assign output pointers: */
+	*pmatrix=integer_matrix;
+	if (pM)*pM=M;
+	if (pN)*pN=N;
+
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(IssmDouble**  pIssmDoublematrix,int* pM,int* pN,int data_enum){{{*/
+void  IoModel::FetchData(IssmDouble** pmatrix,int* pM,int* pN,int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+
+	/*output: */
+	int M,N;
+	IssmPDouble* matrix=NULL;
+	int code=0;
+	int vector_type=0;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,&vector_type,data_enum);
+	if((code!=5) && (code!=6) && (code!=7))_error2_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum));
+	
+	/*Now fetch: */
+
+	/*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) _error2_("could not read number of rows for matrix ");
+	}
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD); 
+	#endif
+
+	if(my_rank==0){  
+		if(fread(&N,sizeof(int),1,fid)!=1) _error2_("could not read number of columns for matrix ");
+	}
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD); 
+	#endif
+
+	/*Now allocate matrix: */
+	if(M*N){
+		matrix=xNew<IssmPDouble>(M*N);
+
+		/*Read matrix on node 0, then broadcast: */
+		if(my_rank==0){  
+			if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error2_("could not read matrix ");
+		}
+		#ifdef _HAVE_MPI_
+		MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+		#endif
+	        *pmatrix=xNew<IssmDouble>(M*N);
+	        for (int i=0;i<M*N;++i) (*pmatrix)[i]=matrix[i];
+	        xDelete<IssmPDouble>(matrix);
+	}
+	else
+	  *pmatrix=NULL;
+	/*Assign output pointers: */
+	if (pM)*pM=M;
+	if (pN)*pN=N;
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(char***   pstrings,int* pnumstrings,int data_enum){{{*/
+void  IoModel::FetchData(char*** pstrings,int* pnumstrings,int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+	
+	int i;
+
+	/*output: */
+	int   numstrings=0;
+	char** strings=NULL;
+	
+	/*intermediary: */
+	char* string=NULL;
+	int   string_size;
+	int   code;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
+	
+	if(code!=9)_error2_("expecting a string array for enum " << EnumToStringx(data_enum));
+	
+	/*We have to read a bunch of strings from disk. First read the number of strings, and allocate: */
+	if(my_rank==0){  
+		if(fread(&numstrings,sizeof(int),1,fid)!=1) _error2_("could not read length of string array");
+	}
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&numstrings,1,MPI_INT,0,MPI_COMM_WORLD); 
+	#endif
+
+	/*Now allocate string array: */
+	if(numstrings){
+		strings=xNew<char*>(numstrings);
+		for(i=0;i<numstrings;i++)strings[i]=NULL;
+
+		/*Go through strings, and read: */
+		for(i=0;i<numstrings;i++){
+			
+			if(my_rank==0){  
+				if(fread(&string_size,sizeof(int),1,fid)!=1) _error2_("could not read length of string ");
+			}
+			#ifdef _HAVE_MPI_
+			MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD); 
+			#endif
+			if(string_size){
+				string=xNew<char>((string_size+1));
+				string[string_size]='\0';
+
+				/*Read string on node 0, then broadcast: */
+				if(my_rank==0){  
+					if(fread(string,string_size*sizeof(char),1,fid)!=1)_error2_(" could not read string ");
+				}
+				#ifdef _HAVE_MPI_
+				MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
+				#endif
+			}
+			else{
+				string=xNew<char>(1);
+				string[0]='\0';
+			}
+
+			strings[i]=string;
+		}
+	}
+
+	/*Assign output pointers: */
+	*pstrings=strings;
+	*pnumstrings=numstrings;
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pM,int data_enum){{{*/
+void  IoModel::FetchData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){
+
+	int i;
+
+	extern int my_rank;
+	extern int num_procs;
+
+	/*output: */
+	IssmDouble** matrices=NULL;
+	int*     mdims=NULL;
+	int*     ndims=NULL;
+	int      numrecords=0;
+
+	/*intermediary: */
+	int     M, N;
+	IssmPDouble *matrix = NULL;
+	int     code;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,NULL,data_enum);
+	if(code!=8)_error2_("expecting a IssmDouble mat array for enum " << EnumToStringx(data_enum));
+	
+	/*Now fetch: */
+	if(my_rank==0){  
+		if(fread(&numrecords,sizeof(int),1,fid)!=1) _error2_("could not read number of records in matrix array ");
+	}
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&numrecords,1,MPI_INT,0,MPI_COMM_WORLD); 
+	#endif
+
+	if(numrecords){
+
+		/*Allocate matrices :*/
+		matrices=xNew<IssmDouble*>(numrecords);
+		mdims=xNew<int>(numrecords);
+		ndims=xNew<int>(numrecords);
+
+		for(i=0;i<numrecords;i++){
+			matrices[i]=NULL;
+			mdims[i]=0;
+			ndims[i]=0;
+		}
+
+		/*Loop through records and fetch matrix: */
+		for(i=0;i<numrecords;i++){
+
+			if(my_rank==0){  
+				if(fread(&M,sizeof(int),1,fid)!=1) _error2_("could not read number of rows in " << i << "th matrix of matrix array");
+			}
+			#ifdef _HAVE_MPI_
+			MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD); 
+			#endif
+
+			if(my_rank==0){  
+				if(fread(&N,sizeof(int),1,fid)!=1) _error2_("could not read number of columns in " << i << "th matrix of matrix array");
+			}
+			#ifdef _HAVE_MPI_
+			MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD); 
+			#endif
+
+			/*Now allocate matrix: */
+			if(M*N){
+				matrix=xNew<IssmPDouble>(M*N);
+
+				/*Read matrix on node 0, then broadcast: */
+				if(my_rank==0){  
+					if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error2_("could not read matrix ");
+				}
+
+				#ifdef _HAVE_MPI_
+				MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+				#endif
+				matrices[i]=xNew<IssmDouble>(M*N);
+				for (int j=0;j<M*N;++j) {matrices[i][j]=matrix[j];}
+				xDelete<IssmPDouble>(matrix);
+			}
+			else
+			  matrices[i]=NULL;
+			/*Assign: */
+			mdims[i]=M;
+			ndims[i]=N;
+		}
+	}
+
+	/*Assign output pointers: */
+	*pmatrices=matrices;
+	*pmdims=mdims;
+	*pndims=ndims;
+	*pnumrecords=numrecords;
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(Option**  poption,int data_enum){{{*/
+void  IoModel::FetchData(Option** poption,int index){
+
+	extern int my_rank;
+	extern int num_procs;
+
+	/*output: */
+	int     code;
+	Option *option      = NULL;
+	char   *name        = NULL;
+
+	/*First get option name*/
+	this->FetchData(&name,index);
+
+	/*Get option value*/
+	fid=this->SetFilePointerToData(&code,NULL,index+1);
+	switch(code){
+		case 3: {//IssmDouble
+			  IssmDouble *value = NULL;
+			  value=xNew<IssmDouble>(1);
+			  FetchData(value,index+1);
+			  option = new OptionDouble();
+			  ((OptionDouble*)option)->values = value;
+			  option->name  = name;
+			  option->numel = 1;
+			  option->ndims = 1;
+			  option->size  = NULL;
+			  break;
+			  }
+		case 4: {//char
+			  char* value = NULL;
+			  FetchData(&value,index+1);
+			  option = new OptionChar();
+			  ((OptionChar*)option)->values = value;
+			  option->name  = name;
+			  option->numel = 1;
+			  option->ndims = 1;
+			  option->size  = NULL;
+			  break;
+			  }
+		default:
+			  _error2_("Option of format " << code << " not supported yet");
+	}
+
+	/*Assign output pointers: */
+	*poption=option;
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchData(int num,...){{{*/
+void  IoModel::FetchData(int num,...){
+
+	va_list ap;
+	int     dataenum;
+	IssmDouble* matrix=NULL;
+	int     M,N;
+	int     i;
+
+	/*Go through the entire list of enums and fetch the corresponding data. Add it to the iomodel->data dataset. Everything
+	 *we fetch is a IssmDouble* : */
+	
+	va_start(ap,num);
+	for(i=0; i<num; i++){
+		
+		dataenum=va_arg(ap, int);
+
+		/*Some checks in debugging mode*/
+		/*{{{*/
+		#ifdef _ISSM_DEBUG_
+		_assert_(dataenum<MaximumNumberOfEnums);
+		if(this->data[dataenum]){
+			_error2_("Info: trying to fetch " << EnumToStringx(dataenum) << " but previous pointer has not been freed (DeleteData has not been called)");
+		}
+		#endif
+		/*}}}*/
+
+		/*Add to this->data: */
+		this->FetchData(&matrix,&M,&N,dataenum);
+		this->data[dataenum]=matrix;
+	}
+	va_end(ap);
+
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchDataToInput{{{*/
+void IoModel::FetchDataToInput(Elements* elements,int vector_enum,int default_vector_enum,IssmDouble default_value){
+
+	/*intermediary: */
+	int     i;
+	bool    defaulting    = false;
+	bool    transient     = false;
+
+	FILE   *fid           = NULL;
+	int     code          = 0;
+	int     vector_layout = 0;
+	int     counter;
+	int     nods;
+	int     nel;
+	int     numberofelements;
+
+
+	/*variables being fetched: */
+	bool    boolean;
+	int     integer;
+	IssmDouble  scalar;
+	char   *string        = NULL;
+	IssmDouble *IssmDoublevector  = NULL;
+	int     M,N;
+
+	/*Fetch parameters: */
+	this->constants->FindParam(&numberofelements,MeshNumberofelementsEnum);
+
+	/*First of, find the record for the enum, and get code  of data type: */
+	fid=this->SetFilePointerToData(&code, &vector_layout,vector_enum);
+
+	switch(code){
+		case 1: //boolean constant.  {{{
+			this->FetchData(&boolean,vector_enum);
+
+			/*Add boolean constant input to all elements: */
+			counter=0;
+			for (i=0;i<numberofelements;i++){
+				if(this->my_elements[i]){
+					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					element->InputCreate((IssmDouble)boolean,vector_enum,code);
+					counter++;
+				}
+			}
+			break; /*}}}*/
+		case 2: //integer constant.  {{{
+			this->FetchData(&integer,vector_enum);
+
+			/*Add integer constant input to all elements: */
+			counter=0;
+			for (i=0;i<numberofelements;i++){
+				if(this->my_elements[i]){
+					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					element->InputCreate((IssmDouble)integer,vector_enum,code);
+					counter++;
+				}
+			}
+			break; /*}}}*/
+		case 3: //IssmDouble constant.  {{{
+			this->FetchData(&scalar,vector_enum);
+
+			/*Add IssmDouble constant input to all elements: */
+			counter=0;
+			for (i=0;i<numberofelements;i++){
+				if(this->my_elements[i]){
+					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					element->InputCreate(scalar,vector_enum,code); 
+					counter++;
+				}
+			}
+			break; /*}}}*/
+		case 5: //boolean vector.  {{{
+
+			/*Fetch vector:*/
+			this->FetchData(&IssmDoublevector,&M,&N,vector_enum); //we still have a IssmDoublevector, because it might include times in transient mode
+			/*Check we got something, otherwise fetch default: */
+			if(IssmDoublevector){
+				defaulting=false;  //we are not defaulting, because  we do have a vector
+			}
+			else{
+				/*do we have a default enum to go fetch? */
+				if(default_vector_enum!=NoneEnum){
+					/*yes. fetch it: */
+					this->FetchData(&IssmDoublevector,&M,&N,default_vector_enum);
+					if(IssmDoublevector){
+						defaulting=false;  //we are not defaulting, because  we do have a vector
+					}
+					else{
+						/*even the default vector is non existent. we are defaulting to the default value: */
+						defaulting=true;
+					}
+				}
+				else{
+					/*we are left with the default value: */
+					defaulting=true;
+				}
+			}
+
+			/*Create inputs:*/
+			counter=0;
+			for (i=0;i<numberofelements;i++){
+				if(this->my_elements[i]){
+					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					if(defaulting) element->InputCreate(default_value,vector_enum,code); 
+					else           element->InputCreate(IssmDoublevector,i,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+					counter++;
+				}
+			}
+			break; /*}}}*/
+		case 6: //int vector{{{
+
+			/*Fetch vector:*/
+			this->FetchData(&IssmDoublevector,&M,&N,vector_enum); //we still have a IssmDoublevector, because it might include times in transient mode
+			/*Check we got something, otherwise fetch default: */
+			if(IssmDoublevector){
+				defaulting=false;  //we are not defaulting, because  we do have a vector
+			}
+			else{
+				/*do we have a default enum to go fetch? */
+				if(default_vector_enum!=NoneEnum){
+					/*yes. fetch it: */
+					this->FetchData(&IssmDoublevector,&M,&N,default_vector_enum);
+					if(IssmDoublevector){
+						defaulting=false;  //we are not defaulting, because  we do have a vector
+					}
+					else{
+						/*even the default vector is non existent. we are defaulting to the default value: */
+						defaulting=true;
+					}
+				}
+				else{
+					/*we are left with the default value: */
+					defaulting=true;
+				}
+			}
+
+			/*Create inputs:*/
+			counter=0;
+			for (i=0;i<numberofelements;i++){
+				if(this->my_elements[i]){
+					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					if(defaulting) element->InputCreate(default_value,vector_enum,code); 
+					else           element->InputCreate(IssmDoublevector,i,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+					counter++;
+				}
+			}
+			break; /*}}}*/
+		case 7: //IssmDouble vector{{{
+
+			/*Fetch vector:*/
+			this->FetchData(&IssmDoublevector,&M,&N,vector_enum);
+			/*Check we got something, otherwise fetch default: */
+			if(IssmDoublevector){
+				defaulting=false;  //we are not defaulting, because  we do have a vector
+			}
+			else{
+				/*do we have a default enum to go fetch? */
+				if(default_vector_enum!=NoneEnum){
+					/*yes. fetch it: */
+					this->FetchData(&IssmDoublevector,&M,&N,default_vector_enum);
+					if(IssmDoublevector){
+						defaulting=false;  //we are not defaulting, because  we do have a vector
+					}
+					else{
+						/*even the default vector is non existent. we are defaulting to the default value: */
+						defaulting=true;
+					}
+				}
+				else{
+					/*we are left with the default value: */
+					defaulting=true;
+				}
+			}
+
+			/*Create inputs:*/
+			counter=0;
+			for (i=0;i<numberofelements;i++){
+				if(this->my_elements[i]){
+					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					if(defaulting) element->InputCreate(default_value,vector_enum,code); 
+					else           element->InputCreate(IssmDoublevector,i,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
+					counter++;
+				}
+			}
+
+			break; /*}}}*/
+		default: /*{{{*/
+			_error2_("data code " << code << " not supported yet!");
+			break;
+			/*}}}*/
+	}
+	/*Free ressources:*/
+	xDelete<IssmDouble>(IssmDoublevector);
+	xDelete<char>(string);
+}
+/*FUNCTION IoModel::LastIndex{{{*/
+void IoModel::LastIndex(int *pindex){
+
+	extern int my_rank;
+	int        lastindex,index;
+	int        record_length;
+
+	/*Go find in the binary file, the position of the data we want to fetch: */
+	if(my_rank==0){
+
+		/*First set FILE* position to the beginning of the file: */
+		fseek(fid,0,SEEK_SET);
+
+		/*Now march through file looking for the correct data identifier: */
+		for(;;){
+			/*Read enum for this size of first string name: */
+			if(fread(&index,sizeof(int),1,fid)==0){
+				/*Ok, we have reached the end of the file. break: */
+				break;
+			}
+
+			/*read the record length, and use it to skip this record: */
+			fread(&record_length,sizeof(int),1,fid);
+			fseek(fid,record_length,SEEK_CUR);
+			lastindex=index;
+		}
+	}
+	/*Broadcast code and vector type: */
+#ifdef _HAVE_MPI_
+	MPI_Bcast(&lastindex,1,MPI_INT,0,MPI_COMM_WORLD); 
+#endif
+
+	/*Assign output pointers:*/
+	*pindex=lastindex;
+}
+/*FUNCTION IoModel::SetFilePointerToData{{{*/
+FILE* IoModel::SetFilePointerToData(int* pcode,int* pvector_type, int data_enum){
+
+	extern int my_rank;
+	extern int num_procs;
+
+	int found=0;
+	int record_enum;
+	int record_length;
+	int record_code; //1 to 7 number
+	int vector_type; //nodal or elementary
+
+	/*Go find in the binary file, the position of the data we want to fetch: */
+	if(my_rank==0){
+
+		/*First set FILE* position to the beginning of the file: */
+		fseek(fid,0,SEEK_SET);
+
+		/*Now march through file looking for the correct data identifier: */
+		for(;;){
+			/*Read enum for this size of first string name: */
+			if(fread(&record_enum,sizeof(int),1,fid)==0){
+				/*Ok, we have reached the end of the file. break: */
+				found=0;
+				break;
+			}
+
+			/*Is this the record sought for? : */
+			if (data_enum==record_enum){
+				/*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 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);
+				found=1;
+				break;
+			}
+			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);
+				/*skip: */
+				fseek(fid,record_length,SEEK_CUR);
+			}
+		}
+	}
+#ifdef _HAVE_MPI_
+	MPI_Bcast(&found,1,MPI_INT,0,MPI_COMM_WORLD); 
+	if(!found)_error2_("could not find data with name" << " " << EnumToStringx(data_enum) << " ");
+#endif
+
+	/*Broadcast code and vector type: */
+#ifdef _HAVE_MPI_
+	MPI_Bcast(&record_code,1,MPI_INT,0,MPI_COMM_WORLD); 
+	MPI_Bcast(&vector_type,1,MPI_INT,0,MPI_COMM_WORLD); 
+	if(record_code==5) MPI_Bcast(&vector_type,1,MPI_INT,0,MPI_COMM_WORLD); 
+#endif
+
+	/*Assign output pointers:*/
+	*pcode=record_code;
+	if(pvector_type)*pvector_type=vector_type;
+
+	return fid;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/IoModel.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/IoModel.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/IoModel.h	(revision 12878)
@@ -0,0 +1,68 @@
+/* \file IoModel.h
+ * \brief  Header file defining the IoModel structure that will help in processing the input data coming 
+ * into ISSM, from Matlab, or through a binary file opened for reading.
+ * \sa IoModel.cpp
+ */
+
+#ifndef _IOMODEL_H
+#define _IOMODEL_H
+
+#include "../include/include.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+
+class Parameters;
+class Elements;
+class Param;
+class Option;
+
+class IoModel {
+
+	private: 
+		IssmDouble **data;        //this dataset holds temporary data, memory intensive.
+		Parameters  *constants;   //this dataset holds all IssmDouble, int, bool and char *parameters read in from the input file.*
+
+	public:
+		/*This data needs to stay memory resident at all time, even if it's memory intensive: */
+		FILE *fid;         //pointer to input file
+		bool *my_elements;
+		bool *my_nodes;
+		int  *my_vertices;
+		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
+
+		/*Methods*/
+		~IoModel();
+		IoModel();
+		IoModel(FILE* iomodel_handle);
+
+		/*Input/Output*/
+		void        CheckEnumSync(void);
+		void        Constant(bool *poutput,int constant_enum);
+		void        Constant(int *poutput,int constant_enum);
+		void        Constant(IssmDouble *poutput,int constant_enum);
+		void        Constant(char **poutput,int constant_enum);
+		Param      *CopyConstantObject(int constant_enum);
+		IssmDouble *Data(int dataenum);
+		void        DeleteData(int num,...);
+		void        FetchConstants(void);
+		void        FetchData(bool* pboolean,int data_enum);
+		void        FetchData(int* pinteger,int data_enum);
+		void        FetchData(IssmDouble* pscalar,int data_enum);
+		void        FetchData(char** pstring,int data_enum);
+		void        FetchData(int** pmatrix,int* pM,int* pN,int data_enum);
+		void        FetchData(IssmDouble**  pscalarmatrix,int* pM,int* pN,int data_enum);
+		void        FetchData(char***   pstringarray,int* pnumstrings,int data_enum);
+		void        FetchData(IssmDouble*** pmatrixarray,int** pmdims,int** pndims, int* pnumrecords,int data_enum);
+		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        LastIndex(int *pindex);
+		FILE*       SetFilePointerToData(int* pcode,int* pvector_type, int data_enum);
+};
+
+#endif  /* _IOMODEL_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/OptArgs.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/OptArgs.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/OptArgs.h	(revision 12878)
@@ -0,0 +1,13 @@
+/*!\file:  OptArgs.h
+ * \brief place holder for optimization function arguments
+ */ 
+
+#ifndef _OPTARGS_H_
+#define _OPTARGS_H_
+
+class Model;
+struct OptArgs{
+	FemModel* femmodel;
+};
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/OptPars.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/OptPars.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/OptPars.h	(revision 12878)
@@ -0,0 +1,17 @@
+/*!\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/branches/trunk-jpl-damage/src/c/classes/Patch.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/Patch.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/Patch.cpp	(revision 12878)
@@ -0,0 +1,175 @@
+/*!\file Patch.c
+ * \brief: implementation of the Patch object
+ */
+
+/*Include files: {{{*/
+#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 <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:*/
+/*FUNCTION Patch::Patch() default constructor {{{*/
+Patch::Patch(){
+	this->numrows=0;
+	this->numcols=0;
+	this->maxvertices=0;
+	this->maxnodes=0;
+	this->values=NULL;
+}
+/*}}}*/
+/*FUNCTION Patch::Patch(int numrows, int maxvertices, int maxnodes){{{*/
+Patch::Patch(int in_numrows, int in_maxvertices, int in_maxnodes){
+
+	int i,j;
+	this->numrows=in_numrows;
+	this->maxvertices=in_maxvertices;
+	this->maxnodes=in_maxnodes;
+    
+	this->numcols=1  //enum_type
+		+1           //step
+		+1           //time 
+		+1           //element id
+		+1           //interpolation type
+		+maxvertices //vertices
+		+maxnodes;   //nodes
+
+	//Allocate values and fill with NaN:
+	if (this->numcols*this->numrows==0){
+		this->values=NULL;
+	}
+	else{
+	        this->values=xNew<IssmDouble>(this->numcols*this->numrows);
+		for(i=0;i<this->numrows;i++){
+			for(j=0;j<this->numcols;j++){
+				this->values[i*this->numcols+j]=NAN;
+			}
+		}
+	}
+
+}
+/*}}}*/
+/*FUNCTION Patch::~Patch(){{{*/
+Patch::~Patch(){
+	xDelete<IssmDouble>(values);
+}
+/*}}}*/
+
+/*Object methods*/
+/*FUNCTION Patch::fillelementinfo{{{*/
+void Patch::fillelementinfo(int count, int element_id, int* vertices_ids, int num_vertices){
+
+	int i;
+	IssmDouble* row=NULL;
+
+	/*point to the start of the row: */
+	row=this->values+count*this->numcols;
+
+	/*Let's remember what is on a row: 
+	 enum_type step time element_id interpolation vertices_ids nodal_values
+	 */
+	row[3]=element_id;
+	for(i=0;i<num_vertices;i++){
+		row[5+i]=vertices_ids[i];
+	}
+
+}
+/*}}}*/
+/*FUNCTION Patch::fillresultinfo{{{*/
+void Patch::fillresultinfo(int count,int enum_type,int step, IssmDouble time, int interpolation, IssmDouble* nodal_values, int num_nodes){
+
+	int i;
+	IssmDouble* row=NULL;
+
+	/*point to the start of the row: */
+	row=this->values+count*this->numcols;
+
+	/*Let's remember what is on a row: 
+	 enum_type step time element_id interpolation vertices_ids nodal_values
+	 */
+	row[0]=enum_type;
+	row[1]=(IssmDouble)step;
+	row[2]=time;
+	row[4]=interpolation;
+	for(i=0;i<num_nodes;i++){
+		row[5+this->maxvertices+i]=nodal_values[i];
+	}
+
+}
+/*}}}*/
+/*FUNCTION Patch::Gather{{{*/
+void Patch::Gather(void){
+
+	int         i;
+	int         count;
+	extern int  my_rank;
+	extern int  num_procs;
+	int         total_numrows;
+	int         node_numrows;
+	IssmDouble     *total_values  = NULL;
+	#ifdef _HAVE_MPI_
+	MPI_Status  status;
+	#endif
+
+	/*First, figure out total number of rows combining all the cpus: */
+	#ifdef _HAVE_MPI_
+	MPI_Reduce(&this->numrows,&total_numrows,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&total_numrows,1,MPI_INT,0,MPI_COMM_WORLD);
+	#else
+	total_numrows=this->numrows;
+	#endif
+
+	/*return if patch empty*/
+	if(total_numrows==0) return;
+
+	/*Now, allocate buffer to holds all the values, on node 0: */
+	if(my_rank==0)total_values=xNew<IssmDouble>(this->numcols*total_numrows);
+
+	/*Start by copying node 0 values onto total_values: */
+	if(my_rank==0){
+		count=0;
+		xMemCpy<IssmDouble>(total_values+count,this->values,this->numcols*this->numrows);
+		count+=this->numrows*this->numcols;
+	}
+
+	/*Now, ask other nodes to send their values: */
+	#ifdef _HAVE_MPI_
+	for (i=1;i<num_procs;i++){
+		if (my_rank==i){ 
+			MPI_Send(&this->numrows,1,MPI_INT,0,1,MPI_COMM_WORLD);   
+			if (this->numrows)MPI_Send(this->values,this->numrows*this->numcols,MPI_DOUBLE,0,1,MPI_COMM_WORLD); 
+		}
+		if (my_rank==0){
+			MPI_Recv(&node_numrows,1,MPI_INT,i,1,MPI_COMM_WORLD,&status); 
+			if (node_numrows)MPI_Recv(total_values+count,node_numrows*this->numcols,MPI_DOUBLE,i,1,MPI_COMM_WORLD,&status);
+			count+=node_numrows*this->numcols;
+		}
+	}	
+	#endif
+
+	/*Now, node 0 has total_values, of size total_numrows*this->numcols. Update the fields in the patch, to reflect this new 
+	 * reality. For other cpus, no point in keeping their data anymore: */
+	if(my_rank==0){
+		this->numrows=total_numrows;
+		xDelete<IssmDouble>(this->values);
+		this->values=total_values;
+	}
+	#ifdef _HAVE_MPI_
+	else{
+		this->numrows=0;
+		xDelete<IssmDouble>(this->values);
+	}
+	#endif
+}/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/Patch.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/Patch.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/Patch.h	(revision 12878)
@@ -0,0 +1,46 @@
+/*!\file: Patch.h
+ * \brief prototypes for Patch.h
+ */ 
+
+/*A Patch object is used to store all results held in elements, in a serial way, and to dump them to disk. 
+	
+	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).
+	
+	For ex: 
+	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
+*/
+
+
+#ifndef _PATCH_H_
+#define  _PATCH_H_
+
+/*Headers:*/
+class Patch{
+
+	public:
+
+		int     numrows; //number of results held in Patch object
+		int     numcols; //number of columns
+		int     maxvertices; //maxvertices corresponds to largest amount of vertices on a given element, determined by the geometry.
+		int     maxnodes;    // maxnodes corresponds to the largest amout of nodes on a given element, determined by the interpolation type.
+		
+		IssmDouble* values;  //result values
+
+		Patch();
+		Patch(int numrows, int maxvertices, int maxnodes);
+		~Patch();
+		void fillelementinfo(int row, int element_id, int* vertices_ids, int num_vertices);
+		void fillresultinfo(int row,int enum_type,int step, IssmDouble time, int interpolation, IssmDouble* nodal_values, int num_nodes);
+		void Gather(void);
+
+};
+#endif //ifndef _PATCH_H_
Index: /issm/branches/trunk-jpl-damage/src/c/classes/Update.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/Update.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/Update.h	(revision 12878)
@@ -0,0 +1,35 @@
+/*!\file: Update.h: abstract class used by some objects to update their properties
+ * \brief prototypes for Update.h
+ */ 
+
+#ifndef _UPDATE_H_
+#define  _UPDATE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../shared/shared.h"
+/*}}}*/
+
+class Update{
+
+	public:
+
+		virtual void  InputUpdateFromVector(IssmDouble* vector, int name, int type)=0;
+		virtual void  InputUpdateFromVector(int* vector, int name, int type)=0;
+		virtual void  InputUpdateFromVector(bool* vector, int name, int type)=0; 
+		#ifdef _HAVE_DAKOTA_
+		virtual void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int rows, int ncols, int name, int type)=0;
+		virtual void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type)=0;
+		virtual void  InputUpdateFromVectorDakota(int* vector, int name, int type)=0;
+		virtual void  InputUpdateFromVectorDakota(bool* vector, int name, int type)=0;
+		#endif
+		virtual void  InputUpdateFromConstant(IssmDouble constant, int name)=0;
+		virtual void  InputUpdateFromConstant(int constant, int name)=0;
+		virtual void  InputUpdateFromConstant(bool constant, int name)=0;
+		virtual void  InputUpdateFromSolution(IssmDouble* solution)=0;
+		virtual void  InputUpdateFromIoModel(int index, IoModel* iomodel)=0;
+
+};
+
+#endif //ifndef _UPDATE_H_
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/AdjacentTriangle.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/AdjacentTriangle.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/AdjacentTriangle.cpp	(revision 12878)
@@ -0,0 +1,76 @@
+#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/branches/trunk-jpl-damage/src/c/classes/bamg/AdjacentTriangle.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/AdjacentTriangle.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/AdjacentTriangle.h	(revision 12878)
@@ -0,0 +1,46 @@
+#ifndef _TRIANGLEADJACENT_H_
+#define _TRIANGLEADJACENT_H_
+
+#include "./include.h"
+#include "./BamgVertex.h"
+
+namespace bamg {
+
+	//classes
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/BamgGeom.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgGeom.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgGeom.cpp	(revision 12878)
@@ -0,0 +1,34 @@
+#include <stdio.h>
+#include "../objects.h"
+#include "../../io/io.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/branches/trunk-jpl-damage/src/c/classes/bamg/BamgGeom.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgGeom.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgGeom.h	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/BamgMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgMesh.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgMesh.cpp	(revision 12878)
@@ -0,0 +1,56 @@
+#include <stdio.h>
+#include "../objects.h"
+#include "../../io/io.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/branches/trunk-jpl-damage/src/c/classes/bamg/BamgMesh.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgMesh.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgMesh.h	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/BamgOpts.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgOpts.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgOpts.cpp	(revision 12878)
@@ -0,0 +1,89 @@
+#include <stdio.h>
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../objects.h"
+#include "../../io/io.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) _error2_("'anisomax' option should be >=1");
+	if (this->coeff==0) _error2_("'coeff' should be positive");
+	if (this->errg<0) _error2_("'errg' option should be >0");
+	if (this->gradation<1) _error2_("'gradation' option should be >=1");
+	if (this->Hessiantype!=0  && this->Hessiantype!=1) _error2_("'Hessiantype' supported options are 0 and 1");
+	if (this->maxnbv<3) _error2_("'maxnbv' option should be >3");
+	if (this->maxsubdiv<=1) _error2_("'maxsubdiv' should be >1");
+	if (this->Metrictype!=0   && this->Metrictype!=1 && this->Metrictype!=2) _error2_("'Metrictype' supported options are 0, 1 and 2");
+	if (this->nbjacobi<=0) _error2_("'nbjacobi' option should be >0");
+	if (this->nbsmooth<=0) _error2_("'nbsmooth' option should be >0");
+
+	if (this->Crack!=0  && this->Crack!=1) _error2_("'Crack' supported options are 0 and 1");
+	if (this->KeepVertices!=0 && this->KeepVertices!=1) _error2_("'KeepVertices' supported options are 0 and 1");
+	if (this->geometricalmetric!=0  && this->geometricalmetric!=1) _error2_("'geometricalmetric' supported options are 0 and 1");
+
+	if (this->hmin<=0) _error2_("'hmin' option should be >0");
+	if (this->hmax<=0 || this->hmax<this->hmin) _error2_("'hmax' option should be between 0 and hmin=" << this->hmin);
+	if (this->hminVertices && this->hminVerticesSize[1]!=1) _error2_("'hminVertices' should be a column");
+	if (this->hmaxVertices && this->hmaxVerticesSize[1]!=1) _error2_("'hmaxVertices' should be a column");
+	if (this->hVertices && this->hVerticesSize[1]!=1) _error2_("'hVertices' should be a column");
+	if (this->metric && (this->metricSize[1]!=1 && this->metricSize[1]!=3)) _error2_("'metric' should have either 1 (iso) or 3 (aniso) columns.");
+	if (this->field){
+		if (this->errSize[0]!=1 || this->errSize[1]!=this->fieldSize[1]) _error2_("'err' should be of size " << 1 << " x " << this->fieldSize[1]);
+		for (i=0;i<this->fieldSize[1];i++) {if (this->err[i]<=0) _error2_("'err' option should be >0");};
+	}
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgOpts.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgOpts.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgOpts.h	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/BamgQuadtree.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgQuadtree.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgQuadtree.cpp	(revision 12878)
@@ -0,0 +1,598 @@
+#include <limits.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "../objects.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/branches/trunk-jpl-damage/src/c/classes/bamg/BamgQuadtree.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgQuadtree.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgQuadtree.h	(revision 12878)
@@ -0,0 +1,62 @@
+/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, BamgQuadtree.h)*/
+#ifndef _BAMGQUADTREE_H
+#define _BAMGQUADTREE_H
+
+#include "./include.h"
+#include "../objects/Object.h"
+class DataSet;
+
+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()       {_error2_("not implemented yet"); };
+					void    DeepEcho()   {_error2_("not implemented yet"); };
+					int     Id()         {_error2_("not implemented yet"); };
+					int     MyRank()     {_error2_("not implemented yet"); };
+					int     ObjectEnum() {_error2_("not implemented yet"); };
+					Object *copy()       {_error2_("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/branches/trunk-jpl-damage/src/c/classes/bamg/BamgVertex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgVertex.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgVertex.cpp	(revision 12878)
@@ -0,0 +1,256 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "../objects.h"
+
+namespace bamg {
+
+	/*Methods*/
+	/*FUNCTION BamgVertex::Echo {{{*/
+
+	void BamgVertex::Echo(void){
+
+		_printLine_("Vertex:");
+		_printLine_("  integer   coordinates i.x: " << i.x << ", i.y: " << i.y);
+		_printLine_("  Euclidean coordinates r.x: " << r.x << ", r.y: " << r.y);
+		_printLine_("  ReferenceNumber = " << ReferenceNumber);
+		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{
+			_error2_("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){
+				_error2_("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){
+					_error2_("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/branches/trunk-jpl-damage/src/c/classes/bamg/BamgVertex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgVertex.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/BamgVertex.h	(revision 12878)
@@ -0,0 +1,58 @@
+#ifndef _BAMGVERTEX_H_
+#define _BAMGVERTEX_H_
+
+#include "./include.h"
+#include "./Metric.h"
+#include "./Direction.h"
+#include "./BamgOpts.h"
+
+namespace bamg {
+
+	//classes
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/CrackedEdge.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/CrackedEdge.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/CrackedEdge.cpp	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/CrackedEdge.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/CrackedEdge.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/CrackedEdge.h	(revision 12878)
@@ -0,0 +1,31 @@
+#ifndef _CRACKEDEDGE_H_
+#define _CRACKEDEDGE_H_
+
+#include "./typedefs.h"
+
+namespace bamg {
+
+	//classes
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/Curve.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Curve.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Curve.cpp	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/Curve.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Curve.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Curve.h	(revision 12878)
@@ -0,0 +1,27 @@
+#ifndef _CURVE_H_
+#define _CURVE_H_
+
+#include "../../shared/Bamg/shared.h"
+
+namespace bamg {
+
+	//classes
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/Direction.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Direction.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Direction.cpp	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/Direction.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Direction.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Direction.h	(revision 12878)
@@ -0,0 +1,21 @@
+#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/branches/trunk-jpl-damage/src/c/classes/bamg/DoubleAndInt.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/DoubleAndInt.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/DoubleAndInt.h	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/Edge.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Edge.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Edge.cpp	(revision 12878)
@@ -0,0 +1,54 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Edge.h"
+#include "Mesh.h"
+#include "Geometry.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){ 
+		_printLine_("Edge:");
+		_printLine_("   pointers towards two vertices: " << v[0] << " " << v[1]);
+		_printLine_("   ReferenceNumber = " << ReferenceNumber);
+		_printLine_("   GeomEdgeHook = " << GeomEdgeHook);
+		_printLine_("   two adjacent edges on the same curve: " << adj[0] << " " << adj[1]);
+	}
+	/*}}}*/
+	/*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)){ _error2_("Intersection bug"); }
+		_assert_(adj[0]==&e || adj[1]==&e);
+
+		return adj[0]==&e?0:1;
+	}
+	/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Edge.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Edge.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Edge.h	(revision 12878)
@@ -0,0 +1,38 @@
+#ifndef _EDGE_H_
+#define _EDGE_H_
+
+#include "./include.h"
+#include "./BamgVertex.h"
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "./GeomEdge.h"
+
+namespace bamg {
+
+	//classes
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/EigenMetric.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/EigenMetric.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/EigenMetric.cpp	(revision 12878)
@@ -0,0 +1,168 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Metric.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){
+
+		_printLine_("EigenMetric:");
+		_printLine_("   lambda1: " << lambda1);
+		_printLine_("   lambda2: " << lambda2);
+		_printLine_("   v.x: " << v.x);
+		_printLine_("   v.y: " << v.y);
+
+		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/branches/trunk-jpl-damage/src/c/classes/bamg/GeomEdge.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/GeomEdge.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/GeomEdge.cpp	(revision 12878)
@@ -0,0 +1,190 @@
+#include <cstdio>
+#include <string.h>
+#include <cmath>
+
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.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/branches/trunk-jpl-damage/src/c/classes/bamg/GeomEdge.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/GeomEdge.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/GeomEdge.h	(revision 12878)
@@ -0,0 +1,47 @@
+#ifndef _GEOMETRICALEDGE_H_
+#define _GEOMETRICALEDGE_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	//classes
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/GeomSubDomain.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/GeomSubDomain.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/GeomSubDomain.cpp	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/GeomSubDomain.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/GeomSubDomain.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/GeomSubDomain.h	(revision 12878)
@@ -0,0 +1,23 @@
+#ifndef _GEOMETRICALSUBDOMAIN_H_
+#define _GEOMETRICALSUBDOMAIN_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	//classes
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/GeomVertex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/GeomVertex.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/GeomVertex.cpp	(revision 12878)
@@ -0,0 +1,38 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "GeomVertex.h"
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.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/branches/trunk-jpl-damage/src/c/classes/bamg/GeomVertex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/GeomVertex.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/GeomVertex.h	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/Geometry.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Geometry.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Geometry.cpp	(revision 12878)
@@ -0,0 +1,971 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "../objects.h"
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.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){   _printString_("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,k,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) _error2_("the domain provided does not contain any vertex");
+		if (bamggeom->Edges==NULL) _error2_("the domain provided does not contain any edge");
+
+		//Vertices
+		if (bamggeom->Vertices){
+			if(verbose>5) _printLine_("      processing Vertices");
+			if (bamggeom->VerticesSize[1]!=3) _error2_("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) _error2_("coefIcoor should be positive");
+		}
+		else{
+			_error2_("No BamgVertex provided");
+		}
+
+		//Edges
+		if (bamggeom->Edges){
+			R2      zerovector(0,0);
+			double* verticeslength=NULL;
+
+			if(verbose>5) _printLine_("      processing Edges");
+			if (bamggeom->EdgesSize[1]!=3) _error2_("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{
+			_error2_("No edges provided");
+		}
+
+		//hVertices
+		if(bamgopts->hVertices && bamgopts->hVerticesSize[0]==nbv){
+			if(verbose>5) _printLine_("      processing hVertices");
+			for (i=0;i< nbv;i++){
+				if (!xIsNan<IssmDouble>(bamgopts->hVertices[i])){
+					vertices[i].m=Metric((double)bamgopts->hVertices[i]);
+				}
+			}
+		}
+
+		//MetricVertices
+		if(bamgopts->metric && bamgopts->metric[0]==nbv){
+			if(verbose>5) _printLine_("      processing MetricVertices");
+			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) _printLine_("      processing MaxCornerAngle");
+			MaxCornerAngle=bamgopts->MaxCornerAngle*Pi/180;
+		}
+
+		//TangentAtEdges
+		if (bamggeom->TangentAtEdges){
+			if(verbose>5) _printString_("      processing TangentAtEdges");
+			if (bamggeom->TangentAtEdgesSize[1]!=4) _error2_("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) _error2_("TangentAtEdges first index exceeds matrix dimension");
+				if (j!=0 && j!=1)  _error2_("TangentAtEdges second index should be 1 or 2 only");
+				edges[i].tg[j] = tg;
+			}
+		}
+
+		//Corners
+		if(bamggeom->Corners){
+			if(verbose>5) _printString_("      processing Corners");
+			if (bamggeom->CornersSize[1]!=1) _error2_("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) _error2_("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) _printLine_("      processing RequiredVertices");
+			if (bamggeom->RequiredVerticesSize[1]!=1) _error2_("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) _error2_("Bad RequiredVerticess  definition: should in [0 " << nbv << "]");
+				vertices[j].SetRequired();
+			}
+		}
+
+		//RequiredEdges
+		if(bamggeom->RequiredEdges){
+			if(verbose>5) _printLine_("      processing RequiredEdges");
+			if (bamggeom->RequiredEdgesSize[1]!=1) _error2_("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) _error2_("Bad RequiredEdges definition: should in [0 " << nbe << "]");
+				edges[j].SetRequired();  
+			}
+		}
+
+		//SubDomain
+		if(bamggeom->SubDomains){
+			if(verbose>5) _printLine_("      processing SubDomains");
+			if (bamggeom->SubDomainsSize[1]!=4) _error2_("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) _error2_("Bad Subdomain definition: first number should be 2 (for Edges)");
+				if (i1>nbe || i1<=0) _error2_("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) _printLine_("      writing Vertices");
+		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) _printLine_("      writing Edges");
+		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) _printLine_("      writing " << nbreq << " RequiredEdges");
+		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) _printLine_("      writing " << nbreqv << " RequiredVertices");
+		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) _printLine_("      writing SubDomains");
+		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) _printLine_("      writing TangentAtEdges");
+		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){
+
+		_printLine_("Geometry:");
+		_printLine_("   nbv  (number of vertices) : " << nbv);
+		_printLine_("   nbe  (number of edges)    : " << nbe);
+		_printLine_("   nbsubdomains: " << nbsubdomains);
+		_printLine_("   nbcurves: " << nbcurves);
+		_printLine_("   vertices: " << vertices);
+		_printLine_("   edges: " << edges);
+		_printLine_("   quadtree: " << quadtree);
+		_printLine_("   subdomains: " << subdomains);
+		_printLine_("   curves: " << curves);
+		_printLine_("   pmin (x,y): (" << pmin.x << " " << pmin.y << ")");
+		_printLine_("   pmax (x,y): (" << pmax.x << " " << pmax.y << ")");
+		_printLine_("   coefIcoor: " << coefIcoor);
+		_printLine_("   MaxCornerAngle: " << MaxCornerAngle);
+
+		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;
+		int                jj;
+		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;
+		GeomVertex *v0g      = (GeomVertex*) (void*)v0;
+
+		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 ){
+				_printLine_("reference numbers: " << v->ReferenceNumber << " " << vertices[i].ReferenceNumber);
+				_printLine_("Id: " << i+1);
+				delete [] next_p;
+				delete [] head_v;
+				delete [] eangle;
+				_error2_("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;
+				_error2_("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]) _error2_("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){
+			_error2_("ProjectOnCurve error message: edge provided should be on geometry");
+		}
+		if (!e[0].GeomEdgeHook ||  !e[1].GeomEdgeHook){
+			_error2_("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) {
+					_printLine_("Fatal Error: on the class Mesh before call Geometry::ProjectOnCurve");
+					_printLine_("That bug might come from:");
+					_printLine_(" 1)  a mesh edge  containing more than " << mxe/2 << " geometrical edges");
+					_printLine_(" 2)  code bug : be sure that we call   Mesh::SetVertexFieldOn() before");
+					_printLine_("To solve the problem do a coarsening of the geometrical mesh or change the constant value of mxe (dangerous)");
+					_error2_("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 ) { 
+				_printLine_("WARNING: on the class Mesh before call Geometry::ProjectOnCurve is having issues (isn't it Eric?)");
+				NbTry++;
+				if (NbTry<2) goto retry;
+				_printLine_("Fatal Error: on the class Mesh before call Geometry::ProjectOnCurve");
+				_printLine_("That bug might come from:");
+				_printLine_(" 1)  a mesh edge  contening more than " << mxe/2 << " geometrical edges");
+				_printLine_(" 2)  code bug : be sure that we call   Mesh::SetVertexFieldOn() before");
+				_printLine_("To solve the problem do a coarsening of the geometrical mesh or change the constant value of mxe (dangerous)");
+				_error2_("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/branches/trunk-jpl-damage/src/c/classes/bamg/Geometry.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Geometry.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Geometry.h	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/ListofIntersectionTriangles.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/ListofIntersectionTriangles.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/ListofIntersectionTriangles.cpp	(revision 12878)
@@ -0,0 +1,425 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "../objects.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){
+			_error2_("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();
+			//_printLine_("cx = " << cx << ", cy=" << cy);
+
+			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){
+				_printLine_("   reshape lSegsI from " << mneo << " to " << MaxNbSeg);
+			}
+			_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) _printLine_("   ListofIntersectionTriangles  ReShape Maxsize " << MaxSize << " -> " << MaxNbSeg);
+		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){
+					_error2_("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){
+					_error2_("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 {
+						_error2_("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/branches/trunk-jpl-damage/src/c/classes/bamg/ListofIntersectionTriangles.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/ListofIntersectionTriangles.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/ListofIntersectionTriangles.h	(revision 12878)
@@ -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){
+						_error2_("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/branches/trunk-jpl-damage/src/c/classes/bamg/Mesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Mesh.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Mesh.cpp	(revision 12878)
@@ -0,0 +1,6005 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "../objects.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*/
+			_printLine_("WARNING: mesh present but no geometry found. Reconstructing...");
+			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++;
+			}
+		  _printLine_("   number of vertices " << k << ", remove = " << Tho.nbv - k);
+		  _printLine_("   number of triangles " << kt << ", remove = " << nbInT-kt);
+		  _printLine_("   number of New boundary edge " << nbNewBedge);
+		  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;
+			  _error2_("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;
+					_error2_("i0<0 || i1<0 || i2< 0");
+				}
+				if (i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv){
+					_error2_("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){
+			  _error2_("kt!=nbt");
+		  }
+		  if (nbt==0 && nbv==0) {
+			  _error2_("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){
+			  _error2_("nbsubdomains==0");
+		  }
+		  if (!subdomains[0].head || !subdomains[0].head->link){
+			  _error2_("!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,j;
+		Metric M1(1);
+		int verbose=0;
+		bool* nodeflags=NULL;
+
+		nbv=nods;
+		maxnbv=nbv;
+		nbt=nels;
+
+		//Vertices
+		if (verbose) _printLine_("Reading vertices (" << nbv << ")");
+		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) _printLine_("Reading triangles (" << nbt << ")");
+		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) _printLine_("Building Geometry");
+		BuildGeometryFromMesh();
+		if (verbose) _printLine_("Completing geometry");
+		Gh.PostRead();
+
+		/*Check that there is no orphan*/
+		bool isorphan=false;
+		for(i=0;i<nbv;i++){
+			if(!nodeflags[i]){
+				_printLine_("Vertex " << i+1 << " does not belong to any element");
+				isorphan=true;
+			}
+		}
+		if(isorphan) _error2_("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) _printLine_("      processing Vertices");
+
+			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) _error2_("no Vertices found in the initial mesh");
+		}
+
+		//Triangles
+		if(bamgmesh->Triangles){
+			if(verbose>5) _printLine_("      processing Triangles");
+			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) _error2_("no Triangles found in the initial mesh");
+		}
+
+		//Quadrilaterals
+		if(bamgmesh->Quadrilaterals){
+			if(verbose>5) _printLine_("      processing Quadrilaterals");
+			long i1,i2,i3,i4,iref;
+			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) _printLine_("      processing VerticesOnGeomEdge");
+			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) _printLine_("      processing VerticesOnGeomVertex");
+			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) _printLine_("      processing Edges");
+			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) _printLine_("      processing EdgesOnGeomEdge");
+			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)) {
+					_error2_("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) _printLine_("      processing SubDomains");
+			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) _error2_("Bad Subdomain definition: first number should be 3");
+				if (head<0 || head>=nbt) _error2_("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) _error2_("k = " << k << ", nbt = " << nbt);
+					next_1[k]=head_1[v];
+					if (v>nbv-1 || v<0)   _error2_("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) _printLine_("      writing Vertices");
+		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) _printLine_("      writing Edges");
+		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) _printLine_("      writing element edges");
+		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) _printLine_("      writing IssmSegments");
+		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){
+					_error2_("Element holding segment [" << i1+1 << " " << i2+1 << "] not found...");
+				}
+			}
+		}
+
+		/*Triangles*/
+		if(verbose>5) _printLine_("      writing Triangles");
+		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) _printLine_("      writing Quadrilaterals");
+		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) _printLine_("      writing SubDomains");
+		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) _printLine_("      writing SubDomainsFromGeom");
+		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) _printLine_("      writing VerticesOnGeomVertex");
+		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) _printLine_("      writing VerticesOnGeomEdge");
+		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()){
+					_error2_("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) _printLine_("      writing EdgesOnGeomEdge");
+		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) _printLine_("      writing Element connectivity");
+		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) _printLine_("      writing Nodal element connectivity");
+		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) _printLine_("      writing Nodal connectivity");
+		//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) _error2_("Index exceed matrix dimensions (k=" << k << " not in [0 " << 2*i1-1 << "]");
+				next_2[k]=head_2[v];
+				if (v>nbv-1 || v<0)   _error2_("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
+		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]=NAN;
+		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++;
+			}
+		}
+
+		/*Cracked vertices*/
+		if(verbose>5) _printLine_("      writing Cracked vertices");
+		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) _printLine_("      writing Cracked vertices");
+		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) _printLine_("      processing metric");
+		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,num;
+		int verbose=0;
+
+		/*output*/
+		int* index=NULL;
+
+		/*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);
+			num=0;
+			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){
+			_error2_("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){
+					_error2_("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 P2 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{
+			_error2_("Hessiantype " << Hessiantype << " not supported yet (1->use Green formula, 0-> double P2 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) ){
+			_error2_("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{
+				_error2_("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) _error2_("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) {
+				_error2_("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)  _printLine_("   BoundAnisotropy by " << anisomax);
+
+		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){
+			_printLine_("      input:  Hmin = " << pow(h2,-0.5)  << ", Hmax = " << pow(h1,-0.5) << ", factor of anisotropy max  = " << pow(rx,0.5));
+			_printLine_("      output: Hmin = " << pow(hn2,-0.5) << ", Hmax = " << pow(hn1,-0.5)<< ", factor of anisotropy max  = " <<pow(rnx,0.5));
+		}
+	}
+	/*}}}*/
+	/*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) _printLine_("   construction of the geometry from the 2d mesh");
+
+		//check that the mesh is not empty
+		if (nbt<=0 || nbv <=0 ) {
+			_error2_("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;
+			_error2_("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))){
+						_error2_("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 {
+					_printLine_("The edge (" << GetId(triangles[i][VerticesOfTriangularEdge[j][0]]) << "," << GetId(triangles[i][VerticesOfTriangularEdge[j][1]]) << ") belongs to more than 2 triangles (" << k << ")");
+					_printLine_("Edge " << j << " of triangle " << i);
+					_printLine_("Edge " << (-st[k]+2)%3 << " of triangle " << (-st[k]+2)/3);
+					_printLine_("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))));
+					_error2_("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) {
+			_printLine_("         info on Mesh:");
+			_printLine_("            - number of vertices    = " << nbv); 
+			_printLine_("            - number of triangles   = " << nbt); 
+			_printLine_("            - number of given edges = " << nbe); 
+			_printLine_("            - number of all edges   = " << nbedges); 
+			_printLine_("            - Euler number 1 - nb of holes = " << nbt-nbedges+nbv); 
+		}
+
+		// 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) _printLine_("   Construction of the edges " << nbe);
+
+			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
+						_printLine_("oh no...");
+					}
+					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){
+				_error2_("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]){
+						_error2_("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){
+			_error2_("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) _printLine_("      The Number of sub domain = " << nbsubdomains); 
+
+		//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;
+			_error2_("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) _printLine_("   number of vertices = " << Gh.nbv << "\n   number of edges = " << Gh.nbe);
+		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;
+			_error2_("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;
+				_error2_("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
+			 _error2_("%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 P2 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) _error2_("'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) {
+			_printLine_("   Construction of Metric: number of field: " << nbsol << " (nbt=" << nbt << ", nbv=" << nbv << ")");
+		}
+
+		//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) _printLine_("      Solution " << nusol << ", Min = " << smin << ", Max = " << smax << ", Delta = " << sdelta);
+
+			//skip constant field
+			if (sdelta < 1.0e-10*Max(absmax,1e-20)){
+				_printLine_("      Solution " << nusol << " is constant, skipping...");
+				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) _error2_("'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) {
+			_printLine_("   Construction of Metric: number of field: " << nbsol << " (nbt=" << nbt << ", nbv=" << nbv << ")");
+		}
+
+		//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) _printLine_("      Solution " << nusol << ", Min = " << smin << ", Max = " << smax << ", Delta = " << sdelta << ", number of fields = " << nbsol);
+
+			//skip constant field
+			if (sdelta < 1.0e-10*Max(absmax,1e-20) ){
+				if (verbose>2) _printLine_("      Solution " << nusol << " is constant, skipping...");
+				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) _printLine_("      number of Cracked Edges = " << k);
+
+		//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;
+					_error2_("Crossing rifts not supported yet");
+				}
+			}
+		}
+		_assert_(k==NbCrackedEdges);
+
+		//Add new vertices
+		if (verbose>4) _printLine_("      number of Cracked Vertices = " << NbCrackedVertices);
+		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;
+					}
+				}
+				//_printLine_(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 << "]");
+				ta = Next(ta).Adj(); 
+				if (count++>50) _error2_("Maximum number of iteration exceeded");
+			}while ((tbegin != ta)); 
+		}
+
+		//Check EdgeFlag
+		for(i=0;i<NbCrackedEdges;i++){
+			if (Edgeflags[i]!=2){
+				_error2_("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;
+
+		_printLine_("Mesh Echo:");
+		_printLine_("   nbv = " << nbv);
+		_printLine_("   nbt = " << nbt);
+		_printLine_("   nbe = " << nbe);
+		_printLine_("   nbq = " << nbq);
+		_printLine_("   index:");
+		for (i=0;i<nbt;i++){
+			_printLine_("   " << 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) << "]");
+		}
+		_printLine_("   coordinates:");
+		for (i=0;i<nbv;i++){
+			_printLine_("   " << setw(4) << i+1 << ": [" << vertices[i].r.x << " " << vertices[i].r.y << "]");
+		}
+
+	}
+	/*}}}*/
+	/*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) _printLine_("   ForceBoundary  nb of edge: " << nbe);
+
+			//check that there is no triangle with 0 determinant
+			for (int t = 0; t < nbt; t++){
+				if (!triangles[t].det) k++;
+			}
+			if (k!=0) {
+				_error2_("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){
+					_error2_("Missing Edge " << i << ", v0=" << GetId(edges[i][0]) << ",v1=" << GetId(edges[i][1]));
+				}
+			}
+
+			if (k!=0) {
+				_error2_("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) _printLine_("      number of inforced edge = " << nbfe << ", number of swap= " << Nbswap); 
+		}
+	/*}}}*/
+	/*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) _printLine_("   Find all external sub-domain"); 
+			else _printLine_("   Find all internal sub-domain");
+		  }
+		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;
+				_error2_("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;
+							_error2_("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) _printLine_("      Number of removes subdomains (OutSideMesh) = " << nbsubdomains-j);
+							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) {
+								_error2_("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){
+									_error2_("mark[GetId(tt)]>=0");
+								}
+								mark[GetId(tt)]=i;
+								tt=tt->link;
+							  } while (tt!=t);
+							break;
+						}
+						ta = Previous(Adj(ta));         
+						if(t == (Triangle *) ta) {
+							_error2_("bad definition of SubSomain " << i);
+						}
+					}
+				}
+
+				if (inew < nbsubdomains) {
+					if (verbose>5) _printLine_("WARNING: " << nbsubdomains-inew << " SubDomains are being removed");
+					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) _printLine_("   Insert initial " << nbv << " vertices");
+
+		//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) _error2_("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) _printLine_("   Begining of insertion process...");
+
+		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) {
+			_printLine_("      NbSwap of insertion: " << NbSwap);
+			_printLine_("      NbSwap/nbv:          " << NbSwap/nbv);
+		}
+
+#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) {
+				_printLine_("      Optim Loop: " << Nbloop);
+				_printLine_("      NbSwap/nbv:          " << NbSwap/nbv);
+			}
+			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) _printLine_("      Try to Insert " << nbvnew << " new points");
+
+		//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]){
+					_error2_("&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();
+					_error2_("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) {
+			_printLine_("         number of new points: " << iv);
+			_printLine_("         number of to close (?) points: " << nbv-iv);
+			_printLine_("         number of swap after: " << NbSwap);
+		}
+		nbv = iv;
+
+		for (i=nbvold;i<nbv;i++) NbSwap += vertices[i].Optim(1);  
+		if (verbose>3) _printLine_("   NbSwap=" << NbSwap);
+
+		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){
+			_error2_("!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) _printLine_("BUG: the geometrical edge " << i << " is on no edge curve");
+			}
+		}
+		if(kk) _error2_("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) _printLine_("MakeQuadrangles costheta = " << costheta);
+
+		if (costheta >1) {
+			if (verbose>5) _printLine_("   do nothing: costheta > 1");
+		}
+
+
+			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){
+				_printLine_("   number of quadrilaterals    = " << nbq);
+				_printLine_("   number of triangles         = " << nbt-nbtout- nbq*2);
+				_printLine_("   number of outside triangles = " << nbtout);
+			}
+			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) _printLine_("   Limit the subdivision of a edges in the new mesh by " << maxsubdiv);
+		// 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){
+			_printLine_("      number of metric changes = " << nbchange << ", maximum number of subdivision of a edges before change = " << pow(lmax,0.5));
+		}
+	}
+	/*}}}*/
+	/*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) _printLine_("         Inserting initial mesh points");
+			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) _printLine_("         Big loop");
+		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 ){
+					_error2_("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){
+						_error2_("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 {
+			_error2_("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 {
+			_error2_("ProjectOnCurve On BamgVertex " << BTh.GetId(vB) << " forget call to SetVertexFieldOnBTh");
+		} 
+		Edge * e = &BhAB;
+		if (!pA || !pB || !e){
+			_error2_("!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){
+			_error2_("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 
+			_error2_("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;
+
+		  }
+		_error2_("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) _printLine_("      Reconstruct mesh of " << nbv << " vertices"); 
+
+	//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){ 
+		_error2_("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 {
+				_error2_("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) {
+		_printLine_("         info of Mesh:");
+		_printLine_("            - number of vertices    = " << nbv << " "); 
+		_printLine_("            - number of triangles   = " << nbt << " "); 
+		_printLine_("            - number of given edges = " << nbe << " "); 
+		_printLine_("            - number of all edges   = " << edge4->nb()); 
+		_printLine_("            - Euler number 1 - nb of holes = " << nbt-edge4->nb()+nbv); 
+	}
+
+	//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
+					_printLine_("Lost boundary edges " << i << " : " << edge4->i(i) << " " << edge4->j(i));
+				}
+				else if (k==10){
+					_printLine_("Other lost boundary edges not shown...");
+				}
+			}
+		}
+	}
+	if(k) {
+		_error2_(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) {
+		 _error2_("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) {
+		_error2_("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) {
+		_error2_("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()){
+						_printLine_("ReconstructExistingMesh error message: problem with the edge number " << i+1 << ": [" << GetId(edges[i][0])+1 << " " << GetId(edges[i][1])+1 << "]");
+						_printLine_("This edge is on geometrical edge number " << Gh.GetId(edges[i].GeomEdgeHook)+1);
+						if (edges[i][j].GeomEdgeHook->OnGeomVertex())
+						 _printLine_("the vertex number " << GetId(edges[i][j])+1 << " of this edge is a geometric BamgVertex number " << Gh.GetId(edges[i][j].GeomEdgeHook->gv)+1);
+						else if (edges[i][j].GeomEdgeHook->OnGeomEdge())
+						 _printLine_("the vertex number " << GetId(edges[i][j])+1 << " of this edge is a geometric Edge number " << Gh.GetId(edges[i][j].GeomEdgeHook->ge)+1);
+						else
+						 _printLine_("Its pointer is " << edges[i][j].GeomEdgeHook);
+
+						_printLine_("This edge is on geometry and has no adjacent edge (open curve) and one of the tip is not required");
+						_error2_("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
+				_error2_("!t0");
+			}
+			do { 
+				long kt = GetId(t);
+				if (kt<0 || kt >= nbt ){
+					_error2_("kt<0 || kt >= nbt");
+				}
+				if (renu[kt]!=-1){
+					_error2_("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){
+			_error2_("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;
+
+		_printLine_("renumbering triangles");
+		for ( it=0;it<nbt;it++) 
+		 triangles[it].Renumbering(vertices,ve,renu);
+
+		_printLine_("renumbering edges");
+		for ( ie=0;ie<nbe;ie++) 
+		 edges[ie].Renumbering(vertices,ve,renu);
+
+		_printLine_("renumbering vertices on geom");
+		for (i=0;i< NbVerticesOnGeomVertex;i++)
+		  {
+			BamgVertex *v = VerticesOnGeomVertex[i].meshvertex;
+			if (v>=vertices && v < ve)
+			 VerticesOnGeomVertex[i].meshvertex=vertices+renu[GetId(v)];
+		  }
+
+		_printLine_("renumbering vertices on edge");
+		for (i=0;i< NbVerticesOnGeomEdge;i++)
+		  {
+			BamgVertex *v =VerticesOnGeomEdge[i].meshvertex;
+			if (v>=vertices && v < ve)
+			 VerticesOnGeomEdge[i].meshvertex=vertices+renu[GetId(v)];
+		  }
+
+		_printLine_("renumbering vertices on Bth vertex");
+		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){
+		_error2_("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){
+					_printLine_("Area of Triangle " << i+1 << " < 0 (det=" << triangles[i].det << ")");
+				}
+			}
+		}
+
+		//else, set as -1
+		else triangles[i].det=-1;
+	}
+
+	if (number_of_errors) _error2_("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);    
+	_printLine_("   Adaptmesh info:");
+	_printLine_("      number of triangles = " << nt);
+	_printLine_("      hmin = " << hmin << ", hmax=" << hmax);
+	_printLine_("      area = " << area << ", M area = " << Marea << ", M area/( |Khat| nt) = " <<  Marea/(aireKh*nt));
+	_printLine_("      infinite-regularity(?): min = " << gammamn << ", max = " << gammamx);
+	_printLine_("      anisomax = " << pow(alpha2,0.5) << ", beta max = " << 1./pow(beta/aireKh,0.5) << ", min = " << 1./pow(beta0/aireKh,0.5));
+}
+/*}}}*/
+/*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]++;
+				}
+			}
+		}  
+	_printLine_(" --- Histogram of the unit mesh,  nb of edges = " << nbedges);
+	_printLine_("      length of edge in   | %% of edge  | Nb of edges "); 
+	_printLine_("      --------------------+-------------+-------------"); 
+	for   (i=0;i<=kmax;i++){ 
+		if (i==0) _printString_( "      " << setw(10) << 0.);
+		else      _printString_( "      " << setw(10) << exp(lmin+i/delta));
+		if (i==kmax) _printString_("          +inf   ");
+		else      _printString_( "      " << setw(10) << exp(lmin+(i+1)/delta));
+		_printLine_("|  " << setw(10) << (long((10000. * histo[i])/ nbedges)/100.) << " |");
+		_printLine_("  " << histo[i]);
+	}
+	_printLine_("      --------------------+-------------+-------------"); 
+}
+/*}}}*/
+/*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) _printLine_("   SmoothingVertex: nb Iteration = " << nbiter << ", Omega=" << omega);
+	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) _printLine_("      move max = " << pow(delta,0.5) << ", iteration = " << k << ", nb of swap = " << NbSwap);
+	  }
+
+	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) _printLine_("   Mesh::SmoothMetric raisonmax = " << raisonmax);
+	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){
+				_error2_("!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)){
+					_error2_("vertices+i != ta.EdgeVertex(1)");
+				}
+				BamgVertex & vj = *(ta.EdgeVertex(0));
+				if ( &vj ) {
+					j= &vj-vertices;
+					if (j<0 || j >= nbv){
+						_error2_("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) _printLine_("      number of iterations = " << kch); 
+	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){
+						_error2_("!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){
+				_error2_("!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)){
+							_printLine_(ke + nbvold << " not in triangle " << i << " In= " << !!t.link << " " << aa << " " << bb << " " << cc << " " << dd);
+							_error2_("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)){
+							_printLine_(ke + nbvold << " not in triangle " << ii << " In= " << !!tt.link << " " << aa << " " << bb << " " << cc << " " << dd);
+							_error2_("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
+						 _error2_("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){
+				_error2_("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){
+				_error2_("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){
+				_error2_("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){
+				_error2_("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){
+								_error2_("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){
+								_error2_("kedge[3*i+k1]<0");
+							}
+							if (kedge[3*i+k2]<0){
+								_error2_("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){
+								_error2_("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 +
+				_error2_("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){
+			_printLine_("   number of quadrilaterals    = " << nbq);
+			_printLine_("   number of triangles         = " << nbt-nbtout- nbq*2);
+			_printLine_("   number of outside triangles = " << nbtout);
+		}
+
+		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) {
+				_printLine_("problem inserting point in SplitInternalEdgeWithBorderVertices (tcvj && !tcvj->link)");
+			}
+
+			quadtree->Add(vi);
+			if (!tcvi || tcvi->det<0){// internal
+				_error2_("!tcvi || tcvi->det < 0");
+			}
+			AddVertex(vi,tcvi,det3);
+			NbSwap += vi.Optim(1);          
+			iv++;
+		}
+		if (verbose>3) {
+			_printLine_("   number of points: " << iv);
+			_printLine_("   number of swap to  split internal edges with border vertices: " << NbSwap);
+			nbv = iv;
+		}
+	}
+	if (NbSplitEdge>nbv-nbvold) _printLine_("WARNING: not enough vertices  to split all internal edges, we lost " << NbSplitEdge - ( nbv-nbvold) << " edges...");
+	if (verbose>2) _printLine_("SplitInternalEdgeWithBorderVertices: Number of splited edge " << NbSplitEdge);
+
+	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) _error2_("no starting triangle provided and no quadtree available");
+
+		/*Call NearestVertex*/
+		BamgVertex *a = quadtree->NearestVertex(B.x,B.y) ;
+
+		/*Check output (Vertex a)*/
+		if (!a)    _error2_("problem while trying to find nearest vertex from a given point. No output found");
+		if (!a->t) _error2_("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) _error2_("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){ _error2_("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) _printLine_("Reading vertices (" << 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 
+
+	/*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,j,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) _error2_("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) _error2_("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) _printLine_("      -- current number of vertices = " << nbv);
+		if (verbose>3) _printLine_("      Creating initial Constrained Delaunay Triangulation...");
+		if (verbose>3) _printLine_("         Inserting boundary points");
+		Insert();
+
+		//Force the boundary
+		if (verbose>3) _printLine_("         Forcing boundaries");
+		ForceBoundary();
+
+		//Extract SubDomains
+		if (verbose>3) _printLine_("         Extracting subdomains");
+		FindSubDomain();
+
+		if (verbose>3) _printLine_("      Inserting internal points");
+		NewPoints(*this,bamgopts,0) ;
+		if (verbose>4) _printLine_("      -- current number of vertices = " << nbv);
+	}
+	/*}}}*/
+	/*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){
+			_error2_("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;
+					
+					//_printLine_("Dealing with curve number " << nc);
+					//_printLine_("edge on geometry is same as GhCurve? " << (ei.GeomEdgeHook==Gh.curves[nc].FirstEdge || ei.GeomEdgeHook==Gh.curves[nc].LastEdge)?"yes":"no");
+					//if(ei.GeomEdgeHook==Gh.curves[nc].FirstEdge || ei.GeomEdgeHook==Gh.curves[nc].LastEdge){
+					//	_printLine_("Do we have the right extremity? curve first vertex -> " << ((GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].FirstEdge)[Gh.curves[nc].FirstVertexIndex])?"yes":"no");
+					//	_printLine_("Do we have the right extremity? curve last  vertex -> " << ((GeomVertex *)*ei[je].GeomEdgeHook==&(*Gh.curves[nc].LastEdge)[Gh.curves[nc].LastVertexIndex])?"yes":"no");
+					//}
+					//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;
+			_error2_("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){
+										_error2_("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){
+										_error2_("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]) {
+								_error2_("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) {
+					_error2_("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) _printLine_("      -- current number of vertices = " << nbv);
+		if (verbose>3) _printLine_("      Creating initial Constrained Delaunay Triangulation...");
+		if (verbose>3) _printLine_("         Inserting boundary points");
+		Insert();
+
+		//Force the boundary
+		if (verbose>3) _printLine_("         Forcing boundaries");
+		ForceBoundary();
+
+		//Extract SubDomains
+		if (verbose>3) _printLine_("         Extracting subdomains");
+		FindSubDomain();
+
+		if (verbose>3) _printLine_("      Inserting internal points");
+		NewPoints(BTh,bamgopts,KeepVertices) ;
+		if (verbose>4) _printLine_("      -- current number of vertices = " << nbv);
+	}
+	/*}}}*/
+
+	/*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){
+			_error2_("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){
+				_error2_("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){
+								_error2_("IJ2==0");
+							}
+							a= IJ_AJ/IJ2;
+							b= IJ_IA/IJ2;
+							return edge;
+		  } 
+	}
+	/*}}}*/
+	/*FUNCTION CloseBoundaryEdgeV2{{{*/
+	AdjacentTriangle CloseBoundaryEdgeV2(I2 C,Triangle *t, double &a,double &b) { 
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/CloseBoundaryEdgeV2)*/
+		// walk around the vertex 
+		// version 2 for remove the probleme if we fill the hole
+		//int bug=1;
+		//  Triangle *torigine = t;
+		// restart:
+		//   int dir=0;
+		if (t->link != 0){
+			_error2_("t->link != 0");
+		}
+		// to have a starting edges 
+		// try the 3 edge bourna-- in case of internal hole 
+		// and choice  the best 
+		// 
+		// the probleme is in case of  the fine and long internal hole
+		// for exemple neart the training edge of a wing
+		BamgVertex * s=0,*s1=0, *s0=0;
+		Icoor2 imax = MaxICoor22;
+		Icoor2 l0 = imax,l1 = imax;
+		double dd2 =  imax;// infinity
+		AdjacentTriangle er; 
+		int  cas=-2;
+		for (int j=0;j<3;j++)
+		  { 
+			AdjacentTriangle ta=t->FindBoundaryEdge(j);
+			if  (! (Triangle *) ta) continue;
+			s0 = ta.EdgeVertex(0);
+			s1 = ta.EdgeVertex(1);
+			I2 A = * s0;
+			I2 B = *ta.EdgeVertex(1);
+			I2 AB = B-A,AC=C-A,BC=B-C;
+			Icoor2  ACAC = (AC,AC), BCBC = (BC,BC);
+			Icoor2  AB2  =   Norme2_2(AB); //  ||AB||^2
+			Icoor2  ABAC  =   (AB,AC);         //  AB.AC|
+
+			double d2;
+			if ( ABAC < 0 )   // DIST A
+			  {
+				if ( (d2=(double) ACAC)  <  dd2) 
+				  {
+					er = ta;
+					l0 = ACAC;
+					l1 = BCBC;
+					cas = 0;
+					s = s0;
+				  }
+			  }
+			else if (ABAC > AB2)  // DIST B
+			  {
+				if ( (d2=(double) BCBC)  <  dd2) 
+				  {
+					dd2 = d2;
+					er = Adj(ta); // other direction
+					l0 = BCBC;
+					l1 = ACAC;
+					cas = 1;
+					s = s1;
+				  }
+			  }
+			else  // DIST AB
+			  { 
+
+				double det_2 =  (double) Det(AB,AC); 
+				det_2 *= det_2; // square of area*2 of triangle ABC
+				d2 = det_2/ (double) AB2; // hauteur^2 in C of of triangle ABC      
+
+				if (d2 < dd2) 
+				  {
+					dd2 = d2;
+					er = ta;
+					l0 = (AC,AC);
+					l1 = (BC,BC);
+					s = 0;
+					cas = -1;
+					b = ((double) ABAC/(double) AB2);
+					a = 1 - b;
+				  }
+			  }
+		  }
+		if (cas ==-2){
+			_error2_("cas==-2");
+		}
+		// l1 = ||C s1||  , l0 = ||C s0||
+		// where s0,s1 are the vertex of the edge er
+
+		if ( s) 
+		  { 
+			t=er;
+			AdjacentTriangle edge(er); 
+
+			int kkk=0;  
+			int linkp = t->link == 0;
+
+			Triangle * tt=t=edge=Adj(Previous(edge));
+			do  {  // loop over vertex s
+				kkk++;
+				if (edge.EdgeVertex(0)!=s && kkk>=10000){
+					_error2_("edge.EdgeVertex(0)!=s && kkk>=10000");
+				}
+
+				int link = tt->link == 0;
+				if ((link + linkp) == 1) 
+				  { // a boundary edge 
+					BamgVertex * st = edge.EdgeVertex(1);
+					I2 I=*st;
+					Icoor2  ll = Norme2_2 (C-I);
+					if (ll < l1) {  // the other vertex is neart 
+						s1=st;
+						l1=ll;
+						er = edge;
+						if(ll<l0) { // change of direction --
+							s1=s;
+							l1=l0;
+							s=st;
+							l0=ll;
+							t=tt;
+							edge=Adj(edge);
+							link=linkp;
+							er = edge;
+						}
+					}
+				  }
+
+				linkp=link;
+				edge=Adj(Previous(edge));
+				tt = edge;
+			} while (t!=tt);
+
+			if (!(Triangle *) er){
+				_error2_("!(Triangle *) er");
+			}
+			I2 A((I2)*er.EdgeVertex(0));
+			I2 B((I2)*er.EdgeVertex(1));
+			I2 AB=B-A,AC=C-A,CB=B-C;
+			double aa =  (double) (AB,AC);
+			double bb =  (double) (AB,CB);
+			if (aa<0)       a=1,b=0;
+			else if(bb<0)   a=0,b=1;
+			else  
+			  {
+				a  = bb/(aa+bb);
+				b  = aa/(aa+bb);
+			  }
+		  }
+		return er;
+	} 
+	/*}}}*/
+/*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
+		_error2_("!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){
+			_error2_("!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){
+				_error2_("!v1 || !v2");
+			}
+			Icoor2 detss = 0,l=0,ks;
+			while ((ks=SwapForForcingEdge(  va,  vb, tc, detss, det1,det2,NbSwap)))
+			 if(l++ > 10000000) {
+				 _error2_("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){
+			_error2_("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 ){
+			_error2_("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)){
+			_error2_("(det1<=0 ) || (det2<=0)");
+		}
+		if ( (detsa>=0) || (detsb<=0) ){ // [a,b] cut infinite line va,bb
+			_error2_("(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/branches/trunk-jpl-damage/src/c/classes/bamg/Mesh.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Mesh.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Mesh.h	(revision 12878)
@@ -0,0 +1,194 @@
+#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 {
+
+	//classes
+	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 &) ;
+	AdjacentTriangle CloseBoundaryEdgeV2(I2 A,Triangle *t, double &a,double &b);
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/Metric.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Metric.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Metric.cpp	(revision 12878)
@@ -0,0 +1,353 @@
+#include <cstdio>
+#include <string.h>
+#include <cmath>
+
+#include "Metric.h"
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.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){
+
+		_printLine_("Metric:");
+		_printLine_("   [a11 a21 a22]: [" << a11 << " " << a21 << " " << a22 << "]");
+
+		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){
+			_error2_("i>=512");
+		}
+		LastMetricInterpole.lab=l;
+		LastMetricInterpole.opt=i;
+		if (i>200 && kkk++<10) _printLine_("WARNING: LengthInterpole: ( i=" << i << " l=" << l << " sss=" << sss << " ) " << sstop); 
+		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){
+			_error2_("r>1 || r<0");
+		}
+		return r ;
+	}
+	/*}}}*/
+
+}
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Metric.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Metric.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Metric.h	(revision 12878)
@@ -0,0 +1,138 @@
+#ifndef _METRIC_H
+#define _METRIC_H
+
+#include "./include.h"
+#include "../../shared/Bamg/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/branches/trunk-jpl-damage/src/c/classes/bamg/R2.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/R2.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/R2.h	(revision 12878)
@@ -0,0 +1,105 @@
+/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, R2.h)*/
+#ifndef _R2_H
+#define _R2_H
+
+#include <cstdio>
+
+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{
+
+		  private:
+
+			  friend P2<R,RR> operator*(P2<R,RR> c,P2xP2<R,RR> cc){
+				  return P2<R,RR>(c.x*cc.x.x + c.y*cc.y.x, c.x*cc.x.y + c.y*cc.y.y);
+			  } 
+		  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/branches/trunk-jpl-damage/src/c/classes/bamg/SetOfE4.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SetOfE4.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SetOfE4.cpp	(revision 12878)
@@ -0,0 +1,120 @@
+#include "../objects.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 ) {
+			_error2_("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/branches/trunk-jpl-damage/src/c/classes/bamg/SetOfE4.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SetOfE4.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SetOfE4.h	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/SubDomain.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SubDomain.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SubDomain.cpp	(revision 12878)
@@ -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){
+			_error2_("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);{
+			_error2_("edge-Th.edges<0 || edge-Th.edges>=Th.nbe");
+		}
+		edge = ThNew.edges+ Th.GetId(edge);
+	}
+	/*}}}*/
+
+} 
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SubDomain.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SubDomain.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/SubDomain.h	(revision 12878)
@@ -0,0 +1,27 @@
+#ifndef _SUBDOMAIN_H_
+#define _SUBDOMAIN_H_
+
+#include "./include.h"
+#include "./Edge.h"
+
+namespace bamg {
+
+	//classes
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/Triangle.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Triangle.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Triangle.cpp	(revision 12878)
@@ -0,0 +1,491 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "../objects.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){
+			_error2_("i<0 || j<0 || k<0");
+		}
+		if (i>=nbv || j>=nbv || k>=nbv){
+			_error2_("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;
+
+		_printLine_("Triangle:");
+		_printLine_("   vertices pointer towards three vertices");
+		_printLine_("      vertices[0] vertices[1] vertices[2] = " << vertices[0] << " " << vertices[1] << " " << vertices[2]);
+		_printLine_("   adj pointer towards three adjacent triangles");
+		_printLine_("      adj[0] adj[1] adj[2] = " << adj[0] << " " << adj[1] << " " << adj[2]);
+		_printLine_("   det (integer triangle determinant) = " << det);
+		if (link){
+			_printLine_("   link (pointer toward duplicate triangle)= " << link);
+		}
+		else{
+			_printLine_("   color = " << color);
+		}
+
+		_printLine_("\nThree vertices:");
+		for(i=0;i<3;i++){
+			if (vertices[i]){
+				vertices[i]->Echo();
+			}
+			else{
+				_printLine_("   vertex " << i+1 << " does not exist");
+			}
+		}
+
+		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){
+				_error2_("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) _error2_("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/branches/trunk-jpl-damage/src/c/classes/bamg/Triangle.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Triangle.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/Triangle.h	(revision 12878)
@@ -0,0 +1,76 @@
+#ifndef _TRIANGLE_H_
+#define _TRIANGLE_H_
+
+#include "./include.h"
+#include "AdjacentTriangle.h"
+
+namespace bamg {
+
+	//classes
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnEdge.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnEdge.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnEdge.cpp	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnEdge.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnEdge.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnEdge.h	(revision 12878)
@@ -0,0 +1,36 @@
+#ifndef _VERTEXONEDGE_H_
+#define _VERTEXONEDGE_H_
+
+#include "./include.h"
+#include "./Edge.h"
+
+namespace bamg {
+
+	//classes
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnGeom.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnGeom.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnGeom.cpp	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnGeom.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnGeom.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnGeom.h	(revision 12878)
@@ -0,0 +1,46 @@
+#ifndef _VERTEXONGEOM_H_
+#define _VERTEXONGEOM_H_
+
+#include "./include.h"
+#include "./GeomVertex.h"
+
+namespace bamg {
+
+	//classes
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnVertex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnVertex.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnVertex.cpp	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnVertex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnVertex.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/VertexOnVertex.h	(revision 12878)
@@ -0,0 +1,28 @@
+#ifndef _VERTEXONVERTEX_H_
+#define _VERTEXONVERTEX_H_
+
+#include "./include.h"
+#include "./BamgVertex.h"
+
+namespace bamg {
+
+	//classes
+	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/branches/trunk-jpl-damage/src/c/classes/bamg/bamgobjects.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/bamgobjects.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/bamgobjects.h	(revision 12878)
@@ -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/branches/trunk-jpl-damage/src/c/classes/bamg/include.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/include.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/include.h	(revision 12878)
@@ -0,0 +1,12 @@
+/*!\file: include.h
+ * \brief prototypes for include.h
+ */ 
+
+#ifndef _INCLUDE2_H_
+#define  _INCLUDE2_H_
+
+#include "../../include/macros.h"
+#include "./macros.h"
+#include "./typedefs.h"
+
+#endif //ifndef _INCLUDE2_H_
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/macros.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/macros.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/macros.h	(revision 12878)
@@ -0,0 +1,25 @@
+#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)
+	const  Icoor2 MaxICoor22 = Icoor2(2)*Icoor2(MaxICoor)*Icoor2(MaxICoor) ;
+}
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/bamg/typedefs.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/bamg/typedefs.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/bamg/typedefs.h	(revision 12878)
@@ -0,0 +1,17 @@
+#ifndef _BAMGTYPEDEFS_H
+#define _BAMGTYPEDEFS_H
+
+#include "./R2.h"
+
+namespace bamg {
+
+	/*Integer coordinates types*/
+	typedef int  Icoor1; 
+	typedef long Icoor2;
+
+	/*I2 and R2*/
+	typedef P2<Icoor1,Icoor2>  I2;
+	typedef P2<double,double>  R2;
+}
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/classes.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/classes.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/classes.h	(revision 12878)
@@ -0,0 +1,33 @@
+/* \file classes.h
+ * \brief: prototype header for all classes used in ISSM.
+ */
+
+#ifndef ALL_CLASSES_H_
+#define ALL_CLASSES_H_
+
+/*Objects derived classes, which are used in our containers: */
+#include "./objects/objects.h"
+
+/*matrix: */
+#include "./matrix/matrixobjects.h"
+
+/*bamg: */
+#include "./bamg/bamgobjects.h"
+
+/*gauss: */
+#include "./gauss/gaussobjects.h"
+
+/*kriging: */
+#include "./kriging/krigingobjects.h"
+
+/*diverse: */
+#include "./Hook.h"
+#include "./DofIndexing.h"
+#include "./IoModel.h"
+#include "./Patch.h"
+#include "./Update.h"
+#include "./FemModel.h"
+#include "./OptArgs.h"
+#include "./OptPars.h"
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/dakota/DakotaPlugin.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/dakota/DakotaPlugin.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/dakota/DakotaPlugin.cpp	(revision 12878)
@@ -0,0 +1,118 @@
+/*!\file:  DakotaPlugin.cpp (see DakotaPlugin.h for explanations)
+ * \brief  header file for derived DirectApplicInterface class. 
+ * \sa SpwanCore.cpp and \sa qmu.cpp
+ *
+ * This class needs to be understood simultaneously with qmu.cpp and SpwanCore.cpp. 
+ * This call is derived from the Dakota DirectApplicInterface class. This is the 
+ * only way to plug ISSM's own routines into the Dakota engine. The derived class 
+ * has one function called derived_map_ac, which is called by Dakota to drive the 
+ * entire snesitivity analysis. 
+ *
+ * We use this routine (which gets variables, variable_descriptors from the Dakota 
+ * engine, and requests responses from the ISSM solution sequences), to call our 
+ * own solutoin cores. This routines calls the SpawnCore routine, which will drive 
+ * the entire computations. 
+ */ 
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*Standard ISSM includes: */
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../classes.h"
+#include "../../modules/Dakotax/Dakotax.h"
+
+/*Standard includes: */
+#include <string>
+
+#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+
+//Dakota headers
+#include "DakotaResponse.H"
+#include "ParamResponsePair.H"
+#include "DakotaPlugin.h"
+#include "system_defs.h"
+#include "ProblemDescDB.H"
+#include "ParallelLibrary.H"
+
+namespace SIM {
+
+//constructor
+DakotaPlugin::DakotaPlugin(const Dakota::ProblemDescDB& problem_db,void* in_femmodel):Dakota::DirectApplicInterface(problem_db){
+
+
+	femmodel=in_femmodel;
+	counter=0;
+}
+
+//destructor
+DakotaPlugin::~DakotaPlugin(){ /* Virtual destructor handles referenceCount at Interface level. */ }
+
+int DakotaPlugin::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++){
+		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: */
+	SpawnCore(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;
+}
+  
+
+int DakotaPlugin::GetCounter(){
+	return counter;
+}
+
+} // namespace SIM
+
+
+#endif //only works if dakota library has been compiled in.
Index: /issm/branches/trunk-jpl-damage/src/c/classes/dakota/DakotaPlugin.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/dakota/DakotaPlugin.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/dakota/DakotaPlugin.h	(revision 12878)
@@ -0,0 +1,52 @@
+/*!\file:  DakotaPlugin.h:
+ */ 
+
+#ifndef _DAKOTAPLUGIN_H
+#define _DAKOTAPLUGIN_H
+
+
+#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+
+/*Headers:*/
+/*{{{*/
+#include "DirectApplicInterface.H"
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+/*}}}*/
+
+namespace SIM {
+
+class DakotaPlugin: public Dakota::DirectApplicInterface
+{
+public:
+
+	DakotaPlugin(const Dakota::ProblemDescDB& problem_db,void* model);
+	~DakotaPlugin();
+
+	/*these fields are used by core solutions: */
+	void* femmodel;
+
+	int counter;
+
+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& ac_name);
+  // execute the output filter portion of a direct evaluation invocation
+  //int derived_map_of(const Dakota::String& of_name);
+
+  /*add for issm: */
+  int GetCounter();
+
+private:
+
+};
+
+} // namespace SIM
+
+#endif //only works if dakota library has been compiled in.
+
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussPenta.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussPenta.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussPenta.cpp	(revision 12878)
@@ -0,0 +1,404 @@
+/*!\file GaussPenta.c
+ * \brief: implementation of the GaussPenta object
+ */
+
+#include "./gaussobjects.h"
+
+/*GaussPenta constructors and destructors:*/
+/*FUNCTION GaussPenta::GaussPenta() {{{*/
+GaussPenta::GaussPenta(){
+
+	numgauss=-1;
+
+	weights=NULL;
+	coords1=NULL;
+	coords2=NULL;
+	coords3=NULL;
+	coords4=NULL;
+
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+	coord4=UNDEF;
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussPenta(int order_horiz,int order_vert) {{{*/
+GaussPenta::GaussPenta(int order_horiz,int order_vert){
+
+	/*Intermediaries*/
+	int     ighoriz,igvert;
+	int     numgauss_horiz;
+	int     numgauss_vert;
+	double *coords1_horiz = NULL;
+	double *coords2_horiz = NULL;
+	double *coords3_horiz = NULL;
+	double *weights_horiz  = NULL;
+	double *coords_vert = NULL;
+	double *weights_vert   = NULL;
+
+	/*Get gauss points*/
+	GaussLegendreTria(&numgauss_horiz,&coords1_horiz,&coords2_horiz,&coords3_horiz,&weights_horiz,order_horiz);
+	GaussLegendreLinear(&coords_vert,&weights_vert,order_vert);
+	numgauss_vert=order_vert;
+
+	/*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);
+
+	/*Combine Horizontal and vertical points*/
+	for (ighoriz=0; ighoriz<numgauss_horiz; ighoriz++){
+		for (igvert=0; igvert<numgauss_vert; igvert++){
+			coords1[numgauss_vert*ighoriz+igvert]=coords1_horiz[ighoriz];
+			coords2[numgauss_vert*ighoriz+igvert]=coords2_horiz[ighoriz];
+			coords3[numgauss_vert*ighoriz+igvert]=coords3_horiz[ighoriz];
+			coords4[numgauss_vert*ighoriz+igvert]=coords_vert[igvert];
+			weights[numgauss_vert*ighoriz+igvert]=weights_horiz[ighoriz]*weights_vert[igvert];
+		}
+	}
+
+	/*Initialize static fields as undefinite*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+	coord4=UNDEF;
+
+	/*Clean up*/
+	xDelete<double>(coords1_horiz);
+	xDelete<double>(coords2_horiz);
+	xDelete<double>(coords3_horiz);
+	xDelete<double>(coords_vert);
+	xDelete<double>(weights_horiz);
+	xDelete<double>(weights_vert);
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussPenta(int index1, int index2, int order){{{*/
+GaussPenta::GaussPenta(int index1, int index2,int order){
+
+	/*Intermediaties*/
+	double *seg_coords  = NULL;
+	double *seg_weights = NULL;
+	int     i;
+
+	/*Get Segment gauss points*/
+	numgauss=order;
+	GaussLegendreLinear(&seg_coords,&seg_weights,numgauss);
+
+	/*Allocate GaussPenta fields*/
+	coords1=xNew<double>(numgauss);
+	coords2=xNew<double>(numgauss);
+	coords3=xNew<double>(numgauss);
+	coords4=xNew<double>(numgauss);
+	weights=xNew<double>(numgauss);
+
+	if(index1==0 && index2==3){
+		for(i=0;i<numgauss;i++) coords1[i]=1.0;
+		for(i=0;i<numgauss;i++) coords2[i]=0.0;
+		for(i=0;i<numgauss;i++) coords3[i]=0.0;
+		for(i=0;i<numgauss;i++) coords4[i]=seg_coords[i];
+		for(i=0;i<numgauss;i++) weights[i]=seg_weights[i];
+	}
+	else if (index1==1 && index2==4){
+		for(i=0;i<numgauss;i++) coords1[i]=0.0;
+		for(i=0;i<numgauss;i++) coords2[i]=1.0;
+		for(i=0;i<numgauss;i++) coords3[i]=0.0;
+		for(i=0;i<numgauss;i++) coords4[i]=seg_coords[i];
+		for(i=0;i<numgauss;i++) weights[i]=seg_weights[i];
+	}
+	else if (index1==2 && index2==5){
+		for(i=0;i<numgauss;i++) coords1[i]=0.0;
+		for(i=0;i<numgauss;i++) coords2[i]=0.0;
+		for(i=0;i<numgauss;i++) coords3[i]=1.0;
+		for(i=0;i<numgauss;i++) coords4[i]=seg_coords[i];
+		for(i=0;i<numgauss;i++) weights[i]=seg_weights[i];
+	}
+	else{
+		_error2_("Penta not supported yet");
+	}
+
+	/*Initialize static fields as undefined*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+	coord4=UNDEF;
+
+	/*clean up*/
+	xDelete<double>(seg_coords);
+	xDelete<double>(seg_weights);
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussPenta(int index1, int index2, int index3, int order){{{*/
+GaussPenta::GaussPenta(int index1, int index2, int index3, int order){
+
+	/*Basal Tria*/
+	if(index1==0 && index2==1 && index3==2){
+
+		/*Get GaussTria*/
+		GaussLegendreTria(&numgauss,&coords1,&coords2,&coords3,&weights,order);
+
+		/*compute z coordinate*/
+		coords4=xNew<double>(numgauss);
+		for(int i=0;i<numgauss;i++) coords4[i]=-1.0;
+	}
+	/*Upper surface Tria*/
+	else if(index1==3 && index2==4 && index3==5){
+
+		/*Get GaussTria*/
+		GaussLegendreTria(&numgauss,&coords1,&coords2,&coords3,&weights,order);
+
+		/*compute z coordinate*/
+		coords4=xNew<double>(numgauss);
+		for(int i=0;i<numgauss;i++) coords4[i]=1.0;
+	}
+	else{
+		_error2_("Tria not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussPenta(int index1, int index2, int index3, int index4,int order_horiz,int order_vert){{{*/
+GaussPenta::GaussPenta(int index1, int index2, int index3, int index4,int order_horiz,int order_vert){
+
+	/*Intermediaties*/
+	double *seg_horiz_coords  = NULL;
+	double *seg_horiz_weights = NULL;
+	double *seg_vert_coords   = NULL;
+	double *seg_vert_weights  = NULL;
+	int     i,j;
+
+	/*get the gauss points using the product of two line rules*/
+	GaussLegendreLinear(&seg_horiz_coords,&seg_horiz_weights,order_horiz);
+	GaussLegendreLinear(&seg_vert_coords, &seg_vert_weights, order_vert);
+
+	/*Allocate GaussPenta fields*/
+	numgauss=order_horiz*order_vert;
+	coords1=xNew<double>(numgauss);
+	coords2=xNew<double>(numgauss);
+	coords3=xNew<double>(numgauss);
+	coords4=xNew<double>(numgauss);
+	weights=xNew<double>(numgauss);
+
+	/*Quads: get the gauss points using the product of two line rules  */
+	if(index1==0 && index2==1 && index3==4 && index4==3){
+		for(i=0;i<order_horiz;i++){
+			for(j=0;j<order_vert;j++){
+				coords1[i*order_vert+j]=  0.5*(1-seg_horiz_coords[i]);
+				coords2[i*order_vert+j]=1-0.5*(1-seg_horiz_coords[i]);
+				coords3[i*order_vert+j]=0.0;
+				coords4[i*order_vert+j]=seg_vert_coords[j];
+				weights[i*order_vert+j]=seg_horiz_weights[i]*seg_vert_weights[j];
+			}
+		}
+	}
+	else if(index1==1 && index2==2 && index3==5 && index4==4){
+		for(i=0;i<order_horiz;i++){
+			for(j=0;j<order_vert;j++){
+				coords1[i*order_vert+j]=0.0;
+				coords2[i*order_vert+j]=  0.5*(1-seg_horiz_coords[i]);
+				coords3[i*order_vert+j]=1-0.5*(1-seg_horiz_coords[i]);
+				coords4[i*order_vert+j]=seg_vert_coords[j];
+				weights[i*order_vert+j]=seg_horiz_weights[i]*seg_vert_weights[j];
+			}
+		}
+	}
+	else if(index1==2 && index2==0 && index3==3 && index4==5){
+		for(i=0;i<order_horiz;i++){
+			for(j=0;j<order_vert;j++){
+				coords1[i*order_vert+j]=1-0.5*(1-seg_horiz_coords[i]);
+				coords2[i*order_vert+j]=0.0;
+				coords3[i*order_vert+j]=  0.5*(1-seg_horiz_coords[i]);
+				coords4[i*order_vert+j]=seg_vert_coords[j];
+				weights[i*order_vert+j]=seg_horiz_weights[i]*seg_vert_weights[j];
+			}
+		}
+	}
+	else{
+		_error2_("Tria not supported yet (user provided indices " << index1 << " " << index2 << " " << index3 << " " << index4 << ")");
+	}
+
+	/*clean-up*/
+	xDelete<double>(seg_horiz_coords);
+	xDelete<double>(seg_horiz_weights);
+	xDelete<double>(seg_vert_coords);
+	xDelete<double>(seg_vert_weights);
+}
+/*}}}*/
+/*FUNCTION GaussPenta::~GaussPenta(){{{*/
+GaussPenta::~GaussPenta(){
+	xDelete<double>(weights);
+	xDelete<double>(coords1);
+	xDelete<double>(coords2);
+	xDelete<double>(coords3);
+	xDelete<double>(coords4);
+}
+/*}}}*/
+
+/*Methods*/
+/*FUNCTION GaussPenta::Echo{{{*/
+void GaussPenta::Echo(void){
+
+	_printLine_("GaussPenta:");
+	_printLine_("   numgauss: " << numgauss);
+
+	if (weights){
+	 _printString_("   weights = ["); 
+	 for(int i=0;i<numgauss;i++) _printLine_(" " << weights[i]);
+	 _printLine_("]");
+	}
+	else _printLine_("weights = NULL");
+	if (coords1){
+	 _printString_("   coords1 = ["); 
+	 for(int i=0;i<numgauss;i++) _printLine_(" " << coords1[i]);
+	 _printLine_("]");
+	}
+	else _printLine_("coords1 = NULL");
+	if (coords2){
+	 _printString_("   coords2 = ["); 
+	 for(int i=0;i<numgauss;i++) _printLine_(" " << coords2[i]);
+	 _printLine_("]");
+	}
+	else _printLine_("coords2 = NULL");
+	if (coords3){
+	 _printString_("   coords3 = ["); 
+	 for(int i=0;i<numgauss;i++) _printLine_(" " << coords3[i]);
+	 _printLine_("]");
+	}
+	else _printLine_("coords3 = NULL");
+	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);
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussCenter{{{*/
+void GaussPenta::GaussCenter(void){
+
+	/*update static arrays*/
+	coord1=ONETHIRD;
+	coord2=ONETHIRD;
+	coord3=ONETHIRD;
+	coord4=0.0;
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussPoint{{{*/
+void GaussPenta::GaussPoint(int ig){
+
+	/*Check input in debugging mode*/
+	 _assert_(ig>=0 && ig< numgauss);
+
+	 /*update static arrays*/
+	 weight=weights[ig];
+	 coord1=coords1[ig];
+	 coord2=coords2[ig];
+	 coord3=coords3[ig];
+	 coord4=coords4[ig];
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussVertex{{{*/
+void GaussPenta::GaussVertex(int iv){
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(iv){
+		case 0:
+			coord1=1; coord2=0; coord3=0; coord4= -1;
+			break;
+		case 1:
+			coord1=0; coord2=1; coord3=0; coord4= -1;
+			break;
+		case 2:
+			coord1=0; coord2=0; coord3=1; coord4= -1;
+			break;
+		case 3:
+			coord1=1; coord2=0; coord3=0; coord4= +1;
+			break;
+		case 4:
+			coord1=0; coord2=1; coord3=0; coord4= +1;
+			break;
+		case 5:
+			coord1=0; coord2=0; coord3=1; coord4= +1;
+			break;
+		default:
+			_error2_("vertex index should be in [0 5]");
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussFaceTria{{{*/
+void GaussPenta::GaussFaceTria(int index1, int index2, int index3, int order){
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*Basal Tria*/
+	if(index1==0 && index2==1 && index3==2){
+		GaussLegendreTria(&numgauss,&coords1,&coords2,&coords3,&weights,order);
+		coords4=xNew<double>(numgauss);
+		for(int i=0;i<numgauss;i++) coords4[i]=-1.0;
+	}
+	else{
+		_error2_("Tria not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::begin{{{*/
+int GaussPenta::begin(void){
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+	_assert_(coords4);
+
+	/*return first gauss index*/
+	return 0;
+}
+/*}}}*/
+/*FUNCTION GaussPenta::end{{{*/
+int GaussPenta::end(void){
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+	_assert_(coords4);
+
+	/*return last gauss index +1*/
+	return numgauss;
+}
+/*}}}*/
+/*FUNCTION GaussPenta::SynchronizeGaussTria{{{*/
+void GaussPenta::SynchronizeGaussTria(GaussTria* gauss_tria){
+
+	gauss_tria->coord1=this->coord1;
+	gauss_tria->coord2=this->coord2;
+	gauss_tria->coord3=this->coord3;
+	gauss_tria->weight=UNDEF;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussPenta.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussPenta.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussPenta.h	(revision 12878)
@@ -0,0 +1,51 @@
+/*!\file GaussPenta.h
+ * \brief: header file for node object
+ */
+
+#ifndef _GAUSSPENTA_H_
+#define _GAUSSPENTA_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./../../shared/shared.h"
+class GaussTria;
+/*}}}*/
+
+class GaussPenta{
+
+	private:
+		int numgauss;
+		double* weights;
+		double* coords1;
+		double* coords2;
+		double* coords3;
+		double* coords4;
+
+	public:
+		double weight;
+		double coord1;
+		double coord2;
+		double coord3;
+		double coord4;
+		
+	public:
+
+		/*GaussPenta constructors, destructors*/
+		GaussPenta();
+		GaussPenta(int order_horiz,int order_vert);
+		GaussPenta(int index1, int index2,int order);
+		GaussPenta(int index1, int index2, int index3, int order);
+		GaussPenta(int index1, int index2, int index3, int index4,int order_horiz,int order_vert);
+		~GaussPenta();
+
+		/*Methods*/
+		int  begin(void);
+		int  end(void);
+		void Echo(void);
+		void GaussPoint(int ig);
+		void GaussVertex(int iv);
+		void GaussFaceTria(int index1, int index2, int index3, int order);
+		void GaussCenter(void);
+		void SynchronizeGaussTria(GaussTria* gauss_tria);
+};
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussTria.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussTria.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussTria.cpp	(revision 12878)
@@ -0,0 +1,276 @@
+/*!\file GaussTria.c
+ * \brief: implementation of the GaussTria object
+ */
+
+#include "./gaussobjects.h"
+
+/*GaussTria constructors and destructors:*/
+/*FUNCTION GaussTria::GaussTria() {{{*/
+GaussTria::GaussTria(){
+
+	numgauss=-1;
+
+	weights=NULL;
+	coords1=NULL;
+	coords2=NULL;
+	coords3=NULL;
+
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussTria(int order) {{{*/
+GaussTria::GaussTria(int order){
+
+	/*Get gauss points*/
+	GaussLegendreTria(&numgauss,&coords1,&coords2,&coords3,&weights,order);
+
+	/*Initialize static fields as undefinite*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussTria(int index1,int index2,int order) {{{*/
+GaussTria::GaussTria(int index1,int index2,int order){
+
+	/*Intermediaties*/
+	IssmPDouble *seg_coords  = NULL;
+	IssmPDouble *seg_weights = NULL;
+	int     i,index3;
+
+	/*Get Segment gauss points*/
+	numgauss=order;
+	GaussLegendreLinear(&seg_coords,&seg_weights,numgauss);
+
+	/*Allocate GaussTria fields*/
+	coords1=xNew<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];
+	}
+
+	/*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
+	 _error2_("The 2 indices provided are not supported yet (user provided " << index1 << " and " << index2 << ")");
+
+	/*Initialize static fields as undefined*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+
+	/*clean up*/
+	xDelete<double>(seg_coords);
+	xDelete<double>(seg_weights);
+}
+/*}}}*/
+/*FUNCTION GaussTria::~GaussTria(){{{*/
+GaussTria::~GaussTria(){
+	xDelete<IssmPDouble>(weights);
+	xDelete<IssmPDouble>(coords1);
+	xDelete<IssmPDouble>(coords2);
+	xDelete<IssmPDouble>(coords3);
+}
+/*}}}*/
+
+/*Methods*/
+/*FUNCTION GaussTria::Echo{{{*/
+void GaussTria::Echo(void){
+
+	_printLine_("GaussTria:");
+	_printLine_("   numgauss: " << numgauss);
+
+	if (weights){
+	 _printString_("   weights = ["); 
+	 for(int i=0;i<numgauss;i++) _printLine_(" " << weights[i]);
+	 _printLine_("]");
+	}
+	else _printLine_("weights = NULL");
+	if (coords1){
+	 _printString_("   coords1 = ["); 
+	 for(int i=0;i<numgauss;i++) _printLine_(" " << coords1[i]);
+	 _printLine_("]");
+	}
+	else _printLine_("coords1 = NULL");
+	if (coords2){
+	 _printString_("   coords2 = ["); 
+	 for(int i=0;i<numgauss;i++) _printLine_(" " << coords2[i]);
+	 _printLine_("]");
+	}
+	else _printLine_("coords2 = NULL");
+	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);
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussCenter{{{*/
+void GaussTria::GaussCenter(void){
+
+	/*update static arrays*/
+	coord1=ONETHIRD;
+	coord2=ONETHIRD;
+	coord3=ONETHIRD;
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussEdgeCenter{{{*/
+void GaussTria::GaussEdgeCenter(int index1,int index2){
+
+	int     index3;
+
+	/*Reverse index1 and 2 if necessary*/
+	if (index1>index2){
+		index3=index1; index1=index2; index2=index3;
+	}
+
+	/*update static arrays*/
+	if (index1==0 && index2==1){
+		coord1=0.5;
+		coord2=0.5;
+		coord3=0.0;
+	}
+	else if (index1==0 && index2==2){
+		coord1=0.5;
+		coord2=0.0;
+		coord3=0.5;
+	}
+	else if (index1==1 && index2==2){
+		coord1=0.0;
+		coord2=0.5;
+		coord3=0.5;
+	}
+	else
+	 _error2_("The 2 indices provided are not supported yet (user provided " << index1 << " and " << index2 << ")");
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussPoint{{{*/
+void GaussTria::GaussPoint(int ig){
+
+	/*Check input in debugging mode*/
+	 _assert_(ig>=0 && ig< numgauss);
+
+	 /*update static arrays*/
+	 weight=weights[ig];
+	 coord1=coords1[ig];
+	 coord2=coords2[ig];
+	 coord3=coords3[ig];
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussFromCoords{{{*/
+void GaussTria::GaussFromCoords(IssmPDouble x,IssmPDouble y,IssmPDouble* xyz_list){
+
+	/*Intermediaries*/
+	IssmPDouble    area = 0;
+	IssmPDouble    x1,y1,x2,y2,x3,y3;
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	x1=*(xyz_list+3*0+0); y1=*(xyz_list+3*0+1);
+	x2=*(xyz_list+3*1+0); y2=*(xyz_list+3*1+1);
+	x3=*(xyz_list+3*2+0); y3=*(xyz_list+3*2+1);
+
+	area=(x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1)/2;
+
+	/*Get first area coordinate = det(x-x3  x2-x3 ; y-y3   y2-y3)/area*/
+	coord1=((x-x3)*(y2-y3)-(x2-x3)*(y-y3))/area;
+
+	/*Get second area coordinate = det(x1-x3  x-x3 ; y1-y3   y-y3)/area*/
+	coord2=((x1-x3)*(y-y3)-(x-x3)*(y1-y3))/area;
+
+	/*Get third  area coordinate 1-area1-area2: */
+	coord3=1-coord1-coord2;
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussVertex{{{*/
+void GaussTria::GaussVertex(int iv){
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	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:
+			_error2_("vertex index should be in [0 2]");
+
+	}
+
+}
+/*}}}*/
+/*FUNCTION GaussTria::begin{{{*/
+int GaussTria::begin(void){
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+
+	/*return first gauss index*/
+	return 0;
+}
+/*}}}*/
+/*FUNCTION GaussTria::end{{{*/
+int GaussTria::end(void){
+
+	/*Check that this has been initialized*/
+	_assert_(numgauss>0);
+	_assert_(weights);
+	_assert_(coords1);
+	_assert_(coords2);
+	_assert_(coords3);
+
+	/*return last gauss index +1*/
+	return numgauss;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussTria.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussTria.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/gauss/GaussTria.h	(revision 12878)
@@ -0,0 +1,46 @@
+/*!\file GaussTria.h
+ * \brief: header file for node object
+ */
+
+#ifndef _GAUSSTRIA_H_
+#define _GAUSSTRIA_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./../../shared/shared.h"
+/*}}}*/
+
+class GaussTria{
+
+	private:
+		int numgauss;
+		IssmPDouble* weights;
+		IssmPDouble* coords1;
+		IssmPDouble* coords2;
+		IssmPDouble* coords3;
+
+	public:
+		IssmPDouble weight;
+		IssmPDouble coord1;
+		IssmPDouble coord2;
+		IssmPDouble coord3;
+		
+	public:
+
+		/*GaussTria constructors, destructors*/
+		GaussTria();
+		GaussTria(int order);
+		GaussTria(int index1,int index2,int order);
+		~GaussTria();
+
+		/*Methods*/
+		int  begin(void);
+		int  end(void);
+		void Echo(void);
+		void GaussFromCoords(IssmPDouble x1,IssmPDouble y1,IssmPDouble* xyz_list);
+		void GaussPoint(int ig);
+		void GaussVertex(int iv);
+		void GaussCenter(void);
+		void GaussEdgeCenter(int index1,int index2);
+};
+#endif  /* _GAUSSTRIA_H_ */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/gauss/gaussobjects.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/gauss/gaussobjects.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/gauss/gaussobjects.h	(revision 12878)
@@ -0,0 +1,11 @@
+/* \file gaussobjects.h
+ * \brief: prototype header for all gauss related objects
+ */
+
+#ifndef ALL_GAUSS_OBJECTS_H_
+#define ALL_GAUSS_OBJECTS_H_
+
+#include "./GaussTria.h"
+#include "./GaussPenta.h"
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/ExponentialVariogram.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 12878)
@@ -0,0 +1,95 @@
+/*!\file ExponentialVariogram.c
+ * \brief: implementation of the ExponentialVariogram object
+ */
+
+#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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+
+/*ExponentialVariogram constructors and destructor*/
+/*FUNCTION ExponentialVariogram::ExponentialVariogram(){{{*/
+ExponentialVariogram::ExponentialVariogram(){
+	this->nugget = 0.2;
+	this->sill   = 1;
+	this->range  = SQRT3;
+	return;
+}
+/*}}}*/
+/*FUNCTION ExponentialVariogram::ExponentialVariogram(Options* options){{{*/
+ExponentialVariogram::ExponentialVariogram(Options* options){
+
+	/*Defaults*/
+	this->nugget = 0.2;
+	this->sill   = 1;
+	this->range  = SQRT3;
+
+	/*Overwrite from options*/
+	if(options->GetOption("nugget")) options->Get(&this->nugget,"nugget");
+	if(options->GetOption("sill"))   options->Get(&this->sill,"sill");
+	if(options->GetOption("range"))  options->Get(&this->range,"range");
+
+	/*Checks*/
+	if(nugget==sill) _error2_("nugget and sill cannot be equal (constant semivariogram not allowed)");
+}
+/*}}}*/
+/*FUNCTION ExponentialVariogram::~ExponentialVariogram(){{{*/
+ExponentialVariogram::~ExponentialVariogram(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION ExponentialVariogram::Echo {{{*/
+void ExponentialVariogram::Echo(void){
+	_printLine_("ExponentialVariogram");
+	_printLine_("   nugget: " << this->nugget);
+	_printLine_("   sill  : " << this->sill);
+	_printLine_("   range : " << this->range);
+}
+/*}}}*/
+
+/*Variogram function*/
+/*FUNCTION ExponentialVariogram::Covariance{{{*/
+double ExponentialVariogram::Covariance(double deltax,double deltay){
+	/*The covariance can be deduced from the variogram from the following
+	 * relationship:
+	 *    2 gamma = C(x,x) + C(y,y) -2 C(x,y)
+	 * so
+	 *    C(h) = sill - gamma                                            */
+	double h,a,cova;
+
+	/*Calculate length*/
+	h=sqrt(pow(deltax,2.)+pow(deltay,2.));
+
+	/*If h is too small, return sill*/
+	if(h<0.0000001) return sill;
+
+	/*compute covariance*/
+	a     = 1./3.;
+	cova = (sill-nugget)*exp(-h/(a*range));
+	return cova;
+}
+/*}}}*/
+/*FUNCTION ExponentialVariogram::SemiVariogram{{{*/
+double ExponentialVariogram::SemiVariogram(double deltax,double deltay){
+	/*http://en.wikipedia.org/wiki/Variogram*/
+	double h,a,gamma;
+
+	/*Calculate length*/
+	h=sqrt(pow(deltax,2.)+pow(deltay,2.));
+
+	/*return semi-variogram*/
+	a     = 1./3.;
+	gamma = (sill-nugget)*(1-exp(-h/(a*range))) + nugget;
+	return gamma;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/ExponentialVariogram.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/ExponentialVariogram.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/ExponentialVariogram.h	(revision 12878)
@@ -0,0 +1,35 @@
+/*! \file ExponentialVariogram.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _EXPONENTIALVARIOGRAM_H_
+#define _EXPONENTIALVARIOGRAM_H_
+
+/*Headers:*/
+#include "./Variogram.h"
+
+class ExponentialVariogram: public Variogram{
+
+	public:
+		double nugget; //The height of the jump of the semivariogram at the discontinuity at the origin
+		double sill;   //Limit of the variogram tending to infinity lag distances
+		double range;  //The distance in which the difference of the variogram from the sill becomes negligible
+
+		/*ExponentialVariogram constructors, destructors*/
+		ExponentialVariogram();
+		ExponentialVariogram(Options* options);
+		~ExponentialVariogram();
+
+		/*Object virtual functions definitions*/
+		void  Echo();
+		void  DeepEcho(){_error2_("Not implemented yet");};
+		int   Id(){_error2_("Not implemented yet");}; 
+		int   MyRank(){_error2_("Not implemented yet");};
+		int   ObjectEnum(){_error2_("Not implemented yet");};
+		Object* copy(){_error2_("Not implemented yet");};
+
+		/*Variogram functions*/
+		double SemiVariogram(double deltax,double deltay);
+		double Covariance(double deltax,double deltay);
+};
+#endif  /* _EXPONENTIALVARIOGRAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/GaussianVariogram.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/GaussianVariogram.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/GaussianVariogram.cpp	(revision 12878)
@@ -0,0 +1,99 @@
+/*!\file GaussianVariogram.c
+ * \brief: implementation of the GaussianVariogram object
+ */
+
+#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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+
+/*GaussianVariogram constructors and destructor*/
+/*FUNCTION GaussianVariogram::GaussianVariogram(){{{*/
+GaussianVariogram::GaussianVariogram(){
+	this->nugget = 0.2;
+	this->sill   = 1;
+	this->range  = SQRT3;
+	return;
+}
+/*}}}*/
+/*FUNCTION GaussianVariogram::GaussianVariogram(Options* options){{{*/
+GaussianVariogram::GaussianVariogram(Options* options){
+
+	/*Defaults*/
+	this->nugget = 0.2;
+	this->sill   = 1;
+	this->range  = SQRT3;
+
+	/*Overwrite from options*/
+	if(options->GetOption("nugget")) options->Get(&this->nugget,"nugget");
+	if(options->GetOption("sill"))   options->Get(&this->sill,"sill");
+	if(options->GetOption("range"))  options->Get(&this->range,"range");
+
+	/*Checks*/
+	if(nugget==sill) _error2_("nugget and sill cannot be equal (constant semivariogram not allowed)");
+}
+/*}}}*/
+/*FUNCTION GaussianVariogram::~GaussianVariogram(){{{*/
+GaussianVariogram::~GaussianVariogram(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION GaussianVariogram::Echo {{{*/
+void GaussianVariogram::Echo(void){
+	_printLine_("GaussianVariogram");
+	_printLine_("   nugget: " << this->nugget);
+	_printLine_("   sill  : " << this->sill);
+	_printLine_("   range : " << this->range);
+}
+/*}}}*/
+
+/*Variogram function*/
+/*FUNCTION GaussianVariogram::Covariance{{{*/
+double GaussianVariogram::Covariance(double deltax,double deltay){
+	/*The covariance can be deduced from the variogram from the following
+	 * relationship:
+	 *    2 gamma = C(x,x) + C(y,y) -2 C(x,y)
+	 * so
+	 *    C(h) = sill - gamma                                            */
+	double h2,a,cova;
+
+	/*Calculate length square*/
+	h2=pow(deltax,2.)+pow(deltay,2.);
+
+	/*If h is too small, return sill*/
+	if(h2<0.0000001) return sill;
+
+	/*compute covariance*/
+	a     = 1./3.;
+	cova = (sill-nugget)*exp(-h2/(a*range*range));
+
+	return cova;
+}
+/*}}}*/
+/*FUNCTION GaussianVariogram::SemiVariogram{{{*/
+double GaussianVariogram::SemiVariogram(double deltax,double deltay){
+	/*http://en.wikipedia.org/wiki/Variogram*/
+	double h2,a,gamma;
+
+	/*Calculate length square*/
+	h2=pow(deltax,2.)+pow(deltay,2.);
+
+	/*return semi-variogram*/
+	a     = 1./3.;
+	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);
+	return gamma;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/GaussianVariogram.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/GaussianVariogram.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/GaussianVariogram.h	(revision 12878)
@@ -0,0 +1,36 @@
+/*! \file GaussianVariogram.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _GAUSSIANVARIOGRAM_H_
+#define _GAUSSIANVARIOGRAM_H_
+
+/*Headers:*/
+#include "./Variogram.h"
+class Options;
+
+class GaussianVariogram: public Variogram{
+
+	public:
+		double nugget; //The height of the jump of the semivariogram at the discontinuity at the origin
+		double sill;   //Limit of the variogram tending to infinity lag distances
+		double range;  //The distance in which the difference of the variogram from the sill becomes negligible
+
+		/*GaussianVariogram constructors, destructors*/
+		GaussianVariogram();
+		GaussianVariogram(Options* options);
+		~GaussianVariogram();
+
+		/*Object virtual functions definitions*/
+		void  Echo();
+		void  DeepEcho(){_error2_("Not implemented yet");};
+		int   Id(){_error2_("Not implemented yet");}; 
+		int   MyRank(){_error2_("Not implemented yet");};
+		int   ObjectEnum(){_error2_("Not implemented yet");};
+		Object* copy(){_error2_("Not implemented yet");};
+
+		/*Variogram functions*/
+		double SemiVariogram(double deltax,double deltay);
+		double Covariance(double deltax,double deltay);
+};
+#endif  /* _GAUSSIANVARIOGRAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Observation.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Observation.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Observation.cpp	(revision 12878)
@@ -0,0 +1,57 @@
+/*!\file Observation.c
+ * \brief: implementation of the Observation object
+ */
+
+#include <stdlib.h>
+#include "../objects.h"
+
+/*Observation constructors and destructor*/
+/*FUNCTION Observation::Observation(){{{*/
+Observation::Observation(){
+	return;
+}
+/*}}}*/
+/*FUNCTION Observation::Observation(double x,double y,int xi,int yi,int index,double value){{{*/
+Observation::Observation(double x_in,double y_in,int xi_in,int yi_in,int index_in,double value_in){
+
+	this->x      = x_in;
+	this->y      = y_in;
+	this->xi     = xi_in;
+	this->yi     = yi_in;
+	this->index  = index_in;
+	this->value  = value_in;
+	this->weight = 1.;
+
+}
+/*}}}*/
+/*FUNCTION Observation::~Observation(){{{*/
+Observation::~Observation(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Observation::Echo {{{*/
+void Observation::Echo(void){
+
+	int  bit;
+
+	_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);
+}
+/*}}}*/
+
+/*Observations functions*/
+/*FUNCTION Observation::WriteXYObs(double* px,double* py,double* pobs){{{*/
+void Observation::WriteXYObs(double* px,double* py,double* pobs){
+	*px   = this->x;
+	*py   = this->y;
+	*pobs = this->value;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Observation.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Observation.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Observation.h	(revision 12878)
@@ -0,0 +1,35 @@
+/*! \file Observation.h 
+ *  \brief: header file for Observation object
+ */
+
+#ifndef _OBSERVATION_H_
+#define _OBSERVATION_H_
+
+#include "../objects/Object.h"
+
+class Observation: public Object{
+
+	public:
+		double x,y;
+		int    xi,yi;
+		int    index;
+		double weight;
+		double value;
+
+		/*Observation constructors, destructors*/
+		Observation();
+		Observation(double x_in,double y_in,int xi_in,int yi_in,int index_in,double value_in);
+		~Observation();
+
+		/*Object virtual functions definitions*/
+		void    Echo();
+		void    DeepEcho()  {_error2_("Not implemented yet"); };
+		int     Id()        {_error2_("Not implemented yet"); };
+		int     MyRank()    {_error2_("Not implemented yet"); };
+		int     ObjectEnum(){_error2_("Not implemented yet"); };
+		Object *copy()      {_error2_("Not implemented yet"); };
+
+		/*Management*/
+		void WriteXYObs(double* px,double* py,double* pobs);
+};
+#endif  /* _OBSERVATION_*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/PowerVariogram.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/PowerVariogram.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/PowerVariogram.cpp	(revision 12878)
@@ -0,0 +1,94 @@
+/*!\file PowerVariogram.c
+ * \brief: implementation of the PowerVariogram object
+ */
+
+#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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+
+/*PowerVariogram constructors and destructor*/
+/*FUNCTION PowerVariogram::PowerVariogram(){{{*/
+PowerVariogram::PowerVariogram(){
+	this->nugget = 0.2;
+	this->slope  = 1.;
+	this->power  = 1.;
+	return;
+}
+/*}}}*/
+/*FUNCTION PowerVariogram::PowerVariogram(Options* options){{{*/
+PowerVariogram::PowerVariogram(Options* options){
+
+	/*Defaults*/
+	this->nugget = 0.2;
+	this->slope  = 1.;
+	this->power  = 1.;
+
+	/*Overwrite from options*/
+	if(options->GetOption("nugget")) options->Get(&this->nugget,"nugget");
+	if(options->GetOption("slope"))  options->Get(&this->slope,"slope");
+	if(options->GetOption("power"))  options->Get(&this->power,"power");
+
+	/*Checks*/
+	if(power<=0 || power>=2) _error2_("power must be betwwen 0 and 2 (0 < power < 2)");
+	if(slope<=0) _error2_("slope must be positive");
+}
+/*}}}*/
+/*FUNCTION PowerVariogram::~PowerVariogram(){{{*/
+PowerVariogram::~PowerVariogram(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION PowerVariogram::Echo {{{*/
+void PowerVariogram::Echo(void){
+	_printLine_("PowerVariogram");
+	_printLine_("   nugget: " << this->nugget);
+	_printLine_("   slope : " << this->slope);
+	_printLine_("   power : " << this->power);
+}
+/*}}}*/
+
+/*Variogram function*/
+/*FUNCTION PowerVariogram::Covariance{{{*/
+double PowerVariogram::Covariance(double deltax,double deltay){
+	/*The covariance can be deduced from the variogram from the following
+	 * relationship:
+	 *    2 gamma = C(x,x) + C(y,y) -2 C(x,y)
+	 * so
+	 *    C(h) = sill - gamma                                            */
+	double h,cova;
+
+	/*Calculate length square*/
+	h=sqrt(pow(deltax,2.)+pow(deltay,2.));
+
+	/*return covariance*/
+	cova = 9999. - this->slope*pow(h,this->power);
+
+	return cova;
+}
+/*}}}*/
+/*FUNCTION PowerVariogram::SemiVariogram{{{*/
+double PowerVariogram::SemiVariogram(double deltax,double deltay){
+	/*http://en.wikipedia.org/wiki/Variogram*/
+	double h,gamma;
+
+	/*Calculate length square*/
+	h=sqrt(pow(deltax,2.)+pow(deltay,2.));
+
+	/*return semi-variogram*/
+	gamma = this->nugget + this->slope*pow(h,this->power);
+
+	//if(h>1000) _printLine_("gamma = " << gamma << " h=" << h);
+	return gamma;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/PowerVariogram.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/PowerVariogram.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/PowerVariogram.h	(revision 12878)
@@ -0,0 +1,35 @@
+/*! \file PowerVariogram.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _POWERVARIOGRAM_H_
+#define _POWERVARIOGRAM_H_
+
+/*Headers:*/
+#include "./Variogram.h"
+
+class PowerVariogram: public Variogram{
+
+	public:
+		double nugget; //The height of the jump of the semivariogram at the discontinuity at the origin
+		double slope;  
+		double power; 
+
+		/*PowerVariogram constructors, destructors*/
+		PowerVariogram();
+		PowerVariogram(Options* options);
+		~PowerVariogram();
+
+		/*Object virtual functions definitions*/
+		void  Echo();
+		void  DeepEcho(){_error2_("Not implemented yet");};
+		int   Id(){_error2_("Not implemented yet");}; 
+		int   MyRank(){_error2_("Not implemented yet");};
+		int   ObjectEnum(){_error2_("Not implemented yet");};
+		Object* copy(){_error2_("Not implemented yet");};
+
+		/*Variogram functions*/
+		double SemiVariogram(double deltax,double deltay);
+		double Covariance(double deltax,double deltay);
+};
+#endif  /* _POWERVARIOGRAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Quadtree.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Quadtree.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Quadtree.cpp	(revision 12878)
@@ -0,0 +1,607 @@
+#include "../objects.h"
+
+/*DOCUMENTATION What is a Quadtree? {{{
+ * 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)
+ }}}*/
+/*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
+ */
+//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 ))
+/*}}}*/
+
+	/*Constructors/Destructors*/
+/*FUNCTION Quadtree::Quadtree(){{{*/
+Quadtree::Quadtree(){
+	_error2_("Constructor not supported");
+
+}
+/*}}}*/
+/*FUNCTION Quadtree::Quadtree(double xmin,double xmax,double ymin,double ymax,int maxdepth){{{*/
+Quadtree::Quadtree(double xmin,double xmax,double ymin,double ymax,int maxdepth){
+
+	/*Intermediaries*/
+	double length;
+
+	/*Initialize fields*/
+	this->MaxDepth=maxdepth;
+	this->NbQuadtreeBox=0;
+	this->NbObs=0;
+
+	/*Create container*/
+	this->boxcontainer=new DataSet();
+
+	/*Create Root, pointer toward the main box*/
+	length=max(xmax-xmin,ymax-ymin);
+	this->root=NewQuadtreeBox(xmin+length/2,ymin+length/2,length);
+}
+/*}}}*/
+	/*FUNCTION Quadtree::~Quadtree(){{{*/
+	Quadtree::~Quadtree(){
+
+		delete boxcontainer;
+		root=NULL;
+
+	}
+	/*}}}*/
+
+	/*Methods*/
+/*FUNCTION Quadtree::Add{{{*/
+void  Quadtree::Add(Observation* observation){
+
+	/*Intermediaries*/
+	int          xi,yi,ij,level,levelbin;
+	QuadtreeBox **pbox    = NULL; // pointer toward current box b
+	QuadtreeBox **pmaster = NULL; // pointer toward master of b
+	QuadtreeBox  *box     = NULL; // current box b
+	QuadtreeBox  *slave   = NULL; // suslaveox of b (if necessary)
+	Observation  *obs[4];
+
+	/*Get integer coodinates*/
+	xi = observation->xi;
+	yi = observation->yi;
+
+	/*Initialize levels*/
+	level    = 0;
+	levelbin = (1L<<this->MaxDepth);// = 2^30
+
+	/*Get inital box (the largest)*/
+	pmaster = &root;
+	pbox    = &root;
+
+	/*Find the smallest box where the observation is located*/
+	while((box=*pbox) && (box->nbitems<0)){ 
+
+		/*Go down one level (levelbin = 00100 -> 00010)*/
+		levelbin>>=1; level+=1; _assert_(level<this->MaxDepth);
+
+		/*Get next box according to the bit value (levelbin)*/
+		pmaster = pbox;
+		pbox    = &box->box[IJ(xi,yi,levelbin)];
+	}
+	_assert_(levelbin>0);
+
+	/*Now, try to add the vertex, if the box is full (nbitems=4), we have to divide it in 4 new boxes*/
+	while((box=*pbox) && (box->nbitems==4)){
+
+		/*Copy the 4 observation in the current Quadtreebox*/
+		obs[0] = box->obs[0];
+		obs[1] = box->obs[1];
+		obs[2] = box->obs[2];
+		obs[3] = box->obs[3];
+
+		/*set nbitems as -1 (now holding boxes instead of observations)*/
+		box->nbitems = -1;
+		box->box[0]  = NULL;
+		box->box[1]  = NULL;
+		box->box[2]  = NULL;
+		box->box[3]  = NULL;
+
+		/*Go down one level (levelbin = 00010 -> 00001)*/
+		levelbin>>=1; level+=1; _assert_(level<this->MaxDepth);
+
+		/*Put the four observations in the new boxes*/
+		for (int k=0;k<4;k++){
+
+			/*Get box for observation number k*/
+			ij    = IJ(obs[k]->xi,obs[k]->yi,levelbin);
+			slave = box->box[ij];
+			if(!slave){
+				box->box[ij] = NewQuadtreeBox(box,ij);
+				slave        = box->box[ij];
+			}
+			slave->obs[slave->nbitems++] = obs[k];
+		}
+
+		/*Get the suslaveox where the current observation is located*/
+		ij      = IJ(xi,yi,levelbin);
+		pmaster = pbox;
+		pbox    = &box->box[ij];
+	}
+
+	/*alloc the QuadtreeBox if necessary and add current observation*/
+	box = *pbox;
+	if(!box){
+		ij  = IJ(xi,yi,levelbin);
+		box = *pbox = NewQuadtreeBox(*pmaster,ij);
+	}
+	box->obs[box->nbitems++]=observation;
+	NbObs++;
+
+}/*}}}*/
+/*FUNCTION Quadtree::AddAndAverage{{{*/
+void Quadtree::AddAndAverage(double x,double y,double value){
+
+	QuadtreeBox **pbox = NULL;
+	QuadtreeBox  *box  = NULL;
+	int           xi,yi;
+	int           level,levelbin;
+	int           index;
+	double        length,length2;
+
+	/*Get integer coodinates*/
+	this->IntergerCoordinates(&xi,&yi,x,y);
+
+	/*Initialize levels*/
+	level    = 0;
+	levelbin = (1L<<this->MaxDepth);// = 2^30
+
+	/*Get inital box (the largest)*/
+	pbox=&root;
+
+	/*Find the smallest box where this point is located*/
+	while((box=*pbox) && (box->nbitems<0)){ 
+
+		levelbin>>=1; level+=1; 
+
+		pbox = &box->box[IJ(xi,yi,levelbin)];
+	}
+
+	/*Add obervation in this box (should be full)*/
+	if(box && box->nbitems==4){
+		index  = 0;
+		length = pow(box->obs[0]->x - x,2.) + pow(box->obs[0]->y - y,2.);
+		for(int i=1;i<4;i++){
+			length2 = pow(box->obs[i]->x - x,2.) + pow(box->obs[i]->y - y,2.);
+			if(length2<length){
+				index  = i;
+				length = length2;
+			}
+		}
+
+		/*We found the closest observation, now average observation (do not change xi and yi to avoid round off errors*/
+		box->obs[index]->x = (box->obs[index]->weight*box->obs[index]->x + x)/(box->obs[index]->weight+1);
+		box->obs[index]->y = (box->obs[index]->weight*box->obs[index]->y + y)/(box->obs[index]->weight+1);
+		box->obs[index]->xi= int((box->obs[index]->weight*double(box->obs[index]->xi) + double(xi))/(box->obs[index]->weight+1));
+		box->obs[index]->yi= int((box->obs[index]->weight*double(box->obs[index]->yi) + double(yi))/(box->obs[index]->weight+1));
+		box->obs[index]->value   = (box->obs[index]->weight*box->obs[index]->value + value)/(box->obs[index]->weight+1);
+		box->obs[index]->weight += 1;
+	}
+	else{
+		_error2_("Box is not full");
+	}
+}/*}}}*/
+/*FUNCTION Quadtree::ClosestObs{{{*/
+void Quadtree::ClosestObs(int *pindex,double x,double y){
+
+	QuadtreeBox **pbox = NULL;
+	QuadtreeBox  *box  = NULL;
+	int           xi,yi;
+	int           level,levelbin;
+	int           index = -1;
+	double        length,length2;
+
+	/*Get integer coodinates*/
+	this->IntergerCoordinates(&xi,&yi,x,y);
+
+	/*Initialize levels*/
+	level    = 0;
+	levelbin = (1L<<this->MaxDepth);// = 2^30
+
+	/*Get inital box (the largest)*/
+	pbox=&root;
+
+	/*Find the smallest box where this point is located*/
+	while((box=*pbox) && (box->nbitems<0)){ 
+
+		levelbin>>=1; level+=1; 
+
+		pbox = &box->box[IJ(xi,yi,levelbin)];
+	}
+
+	/*Add obervation in this box (should be full)*/
+	if(box && box->nbitems>0){
+		index  = box->obs[0]->index;
+		length = pow(box->obs[0]->x - x,2.) + pow(box->obs[0]->y - y,2.);
+		for(int i=1;i<box->nbitems;i++){
+			length2 = pow(box->obs[i]->x - x,2.) + pow(box->obs[i]->y - y,2.);
+			if(length2<length){
+				index  = box->obs[i]->index;
+				length = length2;
+			}
+		}
+	}
+
+	*pindex=index;
+}/*}}}*/
+/*FUNCTION Quadtree::Echo{{{*/
+void  Quadtree::Echo(void){
+
+	_printLine_("Quadtree:");
+	_printLine_("   MaxDepth      = " << this->MaxDepth);
+	_printLine_("   NbQuadtreeBox = " << this->NbQuadtreeBox);
+	_printLine_("   NbObs         = " << this->NbObs);
+	_printLine_("   root          = " << this->root);
+
+}/*}}}*/
+/*FUNCTION Quadtree::DeepEcho{{{*/
+void  Quadtree::DeepEcho(void){
+
+	_printLine_("Quadtree:");
+	_printLine_("   MaxDepth      = " << this->MaxDepth);
+	_printLine_("   NbQuadtreeBox = " << this->NbQuadtreeBox);
+	_printLine_("   NbObs         = " << this->NbObs);
+	_printLine_("   root          = " << this->root);
+	boxcontainer->Echo();
+
+}/*}}}*/
+/*FUNCTION Quadtree::IntergerCoordinates{{{*/
+void  Quadtree::IntergerCoordinates(int *xi,int *yi,double x,double y){
+
+	/*Intermediaries*/
+	double coefficient;
+	double xmin,ymin;
+
+	/*Checks in debugging mode*/
+	_assert_(xi && yi);
+	_assert_(this->root);
+
+	/*coeffIcoor is the coefficient used for integer coordinates:
+	 *                (x-xmin)
+	 * xi = (2^30 -1) --------- 
+	 *                 length
+	 * coefficient = (2^30 -1)/length
+	 */
+	coefficient = double((1L<<this->MaxDepth)-1)/(this->root->length);
+	xmin        = this->root->xcenter - this->root->length/2;
+	ymin        = this->root->ycenter - this->root->length/2;
+
+	*xi=int(coefficient*(x - xmin));
+	*yi=int(coefficient*(y - ymin));
+}/*}}}*/
+/*FUNCTION Quadtree::NewQuadtreeBox(double xcenter,double ycenter,double length){{{*/
+Quadtree::QuadtreeBox* Quadtree::NewQuadtreeBox(double xcenter,double ycenter,double length){
+
+	/*Output*/
+	QuadtreeBox* newbox=NULL;
+
+	/*Create and initialize a new box*/
+	newbox=new QuadtreeBox();
+	newbox->nbitems=0;
+	newbox->xcenter=xcenter;
+	newbox->ycenter=ycenter;
+	newbox->length=length;
+	newbox->box[0]=NULL;
+	newbox->box[1]=NULL;
+	newbox->box[2]=NULL;
+	newbox->box[3]=NULL;
+
+	/*Add to container*/
+	this->boxcontainer->AddObject(newbox);
+	NbQuadtreeBox++;
+
+	/*currentbox now points toward next quadtree box*/
+	return newbox;
+}/*}}}*/
+/*FUNCTION Quadtree::NewQuadtreeBox(QuadtreeBox* master,int index) {{{*/
+Quadtree::QuadtreeBox* Quadtree::NewQuadtreeBox(QuadtreeBox* master,int index){
+
+	/*Output*/
+	QuadtreeBox* newbox=NULL;
+
+	/*Checks in debugging mode*/
+	_assert_(master);
+
+	/*Create and initialize a new box*/
+	newbox=new QuadtreeBox();
+	newbox->nbitems=0;
+	newbox->box[0]=NULL;
+	newbox->box[1]=NULL;
+	newbox->box[2]=NULL;
+	newbox->box[3]=NULL;
+	switch(index){
+		case 0:
+			newbox->xcenter=master->xcenter - master->length/4;
+			newbox->ycenter=master->ycenter - master->length/4;
+			break;
+		case 1:
+			newbox->xcenter=master->xcenter + master->length/4;
+			newbox->ycenter=master->ycenter - master->length/4;
+			break;
+		case 2:
+			newbox->xcenter=master->xcenter - master->length/4;
+			newbox->ycenter=master->ycenter + master->length/4;
+			break;
+		case 3:
+			newbox->xcenter=master->xcenter + master->length/4;
+			newbox->ycenter=master->ycenter + master->length/4;
+			break;
+		default:
+			_error2_("Case " << index << " not supported");
+	}
+	newbox->length=master->length/2;
+
+	/*Add to container*/
+	this->boxcontainer->AddObject(newbox);
+	NbQuadtreeBox++;
+
+	/*currentbox now points toward next quadtree box*/
+	return newbox;
+}/*}}}*/
+/*FUNCTION Quadtree::QuadtreeDepth{{{*/
+void Quadtree::QuadtreeDepth(int* A,int xi,int yi){
+
+	QuadtreeBox **pbox = NULL;
+	QuadtreeBox  *box  = NULL;
+	int           level,levelbin;
+
+	/*Initialize levels*/
+	level    = 0;
+	levelbin = (1L<<this->MaxDepth);// = 2^30
+
+	/*Get inital box (the largest)*/
+	pbox=&root;
+
+	/*Find the smallest box where this point is located*/
+	while((box=*pbox) && (box->nbitems<0)){ 
+
+		levelbin>>=1; level+=1; _assert_(level<this->MaxDepth);
+
+		pbox = &box->box[IJ(xi,yi,levelbin)];
+	}
+	if(box && box->nbitems>0){
+		/*This box is not empty, add one level*/
+		level+=1;
+	}
+
+	*A=level;
+}/*}}}*/
+/*FUNCTION Quadtree::QuadtreeDepth2{{{*/
+void Quadtree::QuadtreeDepth2(int* A,int xi,int yi){
+
+	QuadtreeBox **pbox = NULL;
+	QuadtreeBox  *box  = NULL;
+	int           level,levelbin;
+
+	/*Initialize levels*/
+	level    = 0;
+	levelbin = (1L<<this->MaxDepth);// = 2^30
+
+	/*Get inital box (the largest)*/
+	pbox=&root;
+
+	/*Find the smallest box where this point is located*/
+	while((box=*pbox) && (box->nbitems<0)){ 
+
+		levelbin>>=1; level+=1; 
+
+		pbox = &box->box[IJ(xi,yi,levelbin)];
+	}
+	if(box && box->nbitems>0){
+		/*This box is not empty, add one level*/
+		level+=1;
+	}
+
+	/*If we were to add the vertex, get level*/
+	if(box && box->nbitems==4){
+		int ij;
+		bool flag=true;
+		while(flag){
+
+			levelbin>>=1; level+=1;
+			if(level>this->MaxDepth){
+				level+=1;
+				break;
+			}
+
+			/*loop over the four observations*/
+			ij=IJ(box->obs[0]->xi,box->obs[0]->yi,levelbin);
+			for (int k=1;k<4;k++){
+				if(IJ(box->obs[k]->xi,box->obs[k]->yi,levelbin) != ij){
+					flag = false;
+				}
+			}
+			if(IJ(xi,yi,levelbin)!=ij){
+				flag = false;
+			}
+		}
+	}
+
+	*A=level;
+}/*}}}*/
+/*FUNCTION Quadtree::RangeSearch{{{*/
+void Quadtree::RangeSearch(int **pindices,int *pnobs,double x,double y,double range){
+
+	/*Intermediaries*/
+	int  nobs;
+	int *indices = NULL;
+
+	/*Allocate indices (maximum by default*/
+	if(this->NbObs) indices = xNew<int>(this->NbObs);
+	nobs = 0;
+
+	if(this->root) this->root->RangeSearch(indices,&nobs,x,y,range);
+
+	/*Clean-up and return*/
+	*pnobs=nobs;
+	*pindices=indices;
+
+}/*}}}*/
+
+/*QuadtreeBox methos*/
+/*FUNCTION QuadtreeBox::Echo{{{*/
+void  Quadtree::QuadtreeBox::Echo(void){
+
+	_printLine_("QuadtreeBox:");
+	_printLine_("   nbitems = " << this->nbitems);
+	_printLine_("   xcenter = " << this->xcenter);
+	_printLine_("   ycenter = " << this->ycenter);
+	_printLine_("   length  = " << this->length);
+
+}/*}}}*/
+/*FUNCTION QuadtreeBox::IsWithinRange{{{*/
+int Quadtree::QuadtreeBox::IsWithinRange(double x,double y,double range){
+
+	/*Return 0 if the 2 boxes do not overlap*/
+	if(this->xcenter+this->length/2 < x-range) return 0;
+	if(this->xcenter-this->length/2 > x+range) return 0;
+	if(this->ycenter+this->length/2 < y-range) return 0;
+	if(this->ycenter-this->length/2 > y+range) return 0;
+
+	/*Return 2 if the this box is included in the range*/
+	if(this->xcenter+this->length/2 <= x+range &&
+		this->ycenter+this->length/2 <= y+range &&
+		this->xcenter-this->length/2 >= x-range &&
+		this->ycenter-this->length/2 >= y-range) return 2;
+
+	/*This is a simple overlap*/
+	return 1;
+
+}/*}}}*/
+/*FUNCTION QuadtreeBox::RangeSearch{{{*/
+void Quadtree::QuadtreeBox::RangeSearch(int* indices,int *pnobs,double x,double y,double range){
+
+	/*Intermediaries*/
+	int i,nobs;
+
+	/*Recover current number of observations*/
+	nobs = *pnobs;
+
+	switch(this->IsWithinRange(x,y,range)){
+		case 0:
+			/*If this box is not within range, return*/
+			break;
+		case 2:
+			/*This box is included in range*/
+			this->WriteObservations(indices,&nobs);
+			break;
+		case 1:
+			/*This box is partly included*/
+			if(this->nbitems>0){
+				/*If this box has only observations, add indices that are within range*/
+				for(i=0;i<this->nbitems;i++){
+					if(fabs(this->obs[i]->x-x) <= range && fabs(this->obs[i]->y-y) <= range){
+						indices[nobs++]=this->obs[i]->index;
+					}
+				}
+			}
+			else{
+				/*This box points toward boxes*/
+				if(this->box[0]) this->box[0]->RangeSearch(indices,&nobs,x,y,range);
+				if(this->box[1]) this->box[1]->RangeSearch(indices,&nobs,x,y,range);
+				if(this->box[2]) this->box[2]->RangeSearch(indices,&nobs,x,y,range);
+				if(this->box[3]) this->box[3]->RangeSearch(indices,&nobs,x,y,range);
+			}
+			break;
+		default:
+			_error2_("Case " << this->IsWithinRange(x,y,range) << " not supported");
+	}
+
+	/*Assign output pointers: */
+	*pnobs=nobs;
+}/*}}}*/
+/*FUNCTION QuadtreeBox::WriteObservations{{{*/
+void Quadtree::QuadtreeBox::WriteObservations(int* indices,int *pnobs){
+
+	/*Intermediaries*/
+	int i,nobs;
+
+	/*Recover current number of observations*/
+	nobs = *pnobs;
+
+	if(this->nbitems>0){
+		/*If this box has only observations, add all indices*/
+		for(i=0;i<this->nbitems;i++){
+			indices[nobs++]=this->obs[i]->index;
+		}
+	}
+	else{
+		/*This box points toward boxes, */
+		if(this->box[0]) this->box[0]->WriteObservations(indices,&nobs);
+		if(this->box[1]) this->box[1]->WriteObservations(indices,&nobs);
+		if(this->box[2]) this->box[2]->WriteObservations(indices,&nobs);
+		if(this->box[3]) this->box[3]->WriteObservations(indices,&nobs);
+	}
+
+	/*Assign output pointers: */
+	*pnobs=nobs;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Quadtree.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Quadtree.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Quadtree.h	(revision 12878)
@@ -0,0 +1,66 @@
+
+#ifndef _QUADTREE_H
+#define _QUADTREE_H
+
+class Observation;
+
+class Quadtree{
+
+	private:
+		/* A quadtree box contains up to 4 points (locations). 4 new quadtree boxes are
+		 * created if a fifth point is added to the same box. A Quadtree box is therefore
+		 * composed of EITHER:
+		 * - up to 4 vertices
+		 * - 4 "sub" quadtree boxes*/
+
+		class QuadtreeBox: public Object{ 
+			public:
+				int    nbitems; // number of current vertices in the box
+				double xcenter; // x position of the center (double)
+				double ycenter; // x position of the center (double)
+				double length;  // width of the box
+				union{
+					QuadtreeBox *box[4];
+					Observation *obs[4];
+				};
+
+				/*Object functions (Needed because the Quadtree uses a Container*/
+				void    Echo();
+				void    DeepEcho()  {_error2_("not implemented yet"); };
+				int     Id()        {_error2_("not implemented yet"); };
+				int     MyRank()    {_error2_("not implemented yet"); };
+				int     ObjectEnum(){_error2_("not implemented yet"); };
+				Object *copy()      {_error2_("not implemented yet"); };
+
+				/*Methods*/
+				int          IsWithinRange(double  x,double y,double range);
+				void         RangeSearch(int *indices,int *pnobs,double x,double y,double range);
+				void         WriteObservations(int *indices,int *pnobs);
+
+		};
+
+		/*Quadtree private Fields*/
+		DataSet* boxcontainer;
+
+	public:
+		int          MaxDepth;          // maximum number of subdivision
+		QuadtreeBox *root;              // main box
+		int          NbQuadtreeBox;     // total number of boxes
+		int          NbObs;             // number of points
+
+		Quadtree();
+		Quadtree(double xmin,double xmax,double ymin,double ymax,int maxdepth_in);
+		~Quadtree();
+		void         Add(Observation *observation);
+		void         AddAndAverage(double x,double y,double value);
+		void         ClosestObs(int *pindex,double x,double y);
+		void         DeepEcho(void);
+		void         Echo(void);
+		void         IntergerCoordinates(int *xi,int *yi,double x,double y);
+		QuadtreeBox *NewQuadtreeBox(double xcenter,double ycenter,double length);
+		QuadtreeBox *NewQuadtreeBox(QuadtreeBox* master,int index);
+		void         QuadtreeDepth(int *A,int xi,int yi);
+		void         QuadtreeDepth2(int *A,int xi,int yi);
+		void         RangeSearch(int **pindices,int *pnobs,double x,double y,double range);
+};
+#endif //_QUADTREE_H
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/SphericalVariogram.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/SphericalVariogram.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/SphericalVariogram.cpp	(revision 12878)
@@ -0,0 +1,98 @@
+/*!\file SphericalVariogram.c
+ * \brief: implementation of the SphericalVariogram object
+ */
+
+#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 "../objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+
+/*SphericalVariogram constructors and destructor*/
+/*FUNCTION SphericalVariogram::SphericalVariogram(){{{*/
+SphericalVariogram::SphericalVariogram(){
+	this->nugget = 0.2;
+	this->sill   = 1;
+	this->range  = SQRT3;
+	return;
+}
+/*}}}*/
+/*FUNCTION SphericalVariogram::SphericalVariogram(Options* options){{{*/
+SphericalVariogram::SphericalVariogram(Options* options){
+
+	/*Defaults*/
+	this->nugget = 0.2;
+	this->sill   = 1;
+	this->range  = SQRT3;
+
+	/*Overwrite from options*/
+	if(options->GetOption("nugget")) options->Get(&this->nugget,"nugget");
+	if(options->GetOption("sill"))   options->Get(&this->sill,"sill");
+	if(options->GetOption("range"))  options->Get(&this->range,"range");
+
+	/*Checks*/
+	if(nugget==sill) _error2_("nugget and sill cannot be equal (constant semivariogram not allowed)");
+}
+/*}}}*/
+/*FUNCTION SphericalVariogram::~SphericalVariogram(){{{*/
+SphericalVariogram::~SphericalVariogram(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION SphericalVariogram::Echo {{{*/
+void SphericalVariogram::Echo(void){
+	_printLine_("SphericalVariogram");
+	_printLine_("   nugget: " << this->nugget);
+	_printLine_("   sill  : " << this->sill);
+	_printLine_("   range : " << this->range);
+}
+/*}}}*/
+
+/*Variogram function*/
+/*FUNCTION SphericalVariogram::Covariance{{{*/
+double SphericalVariogram::Covariance(double deltax,double deltay){
+	/*The covariance can be deduced from the variogram from the following
+	 * relationship:
+	 *    2 gamma = C(x,x) + C(y,y) -2 C(x,y)
+	 * so
+	 *    C(h) = sill - gamma                                            */
+	double h,cova;
+
+	/*Calculate length square*/
+	h=sqrt(pow(deltax,2.)+pow(deltay,2.));
+
+	/*return covariance*/
+	if(h<=range)
+	 cova = (sill-nugget)*(1 - (3*h)/(2*range) + pow(h,3.)/(2*pow(range,3.)) );
+	else
+	 cova = 0.;
+
+	return cova;
+}
+/*}}}*/
+/*FUNCTION SphericalVariogram::SemiVariogram{{{*/
+double SphericalVariogram::SemiVariogram(double deltax,double deltay){
+	/*http://en.wikipedia.org/wiki/Variogram*/
+	double h,gamma;
+
+	/*Calculate length square*/
+	h=sqrt(pow(deltax,2.)+pow(deltay,2.));
+
+	/*return semi-variogram*/
+	if(h<=range)
+	 gamma = (sill-nugget)*( (3*h)/(2*range) - pow(h,3.)/(2*pow(range,3.)) ) + nugget;
+	else
+	 gamma = sill;
+
+	return gamma;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/SphericalVariogram.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/SphericalVariogram.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/SphericalVariogram.h	(revision 12878)
@@ -0,0 +1,35 @@
+/*! \file SphericalVariogram.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _SPHERICALVARIOGRAM_H_
+#define _SPHERICALVARIOGRAM_H_
+
+/*Headers:*/
+#include "./Variogram.h"
+
+class SphericalVariogram: public Variogram{
+
+	public:
+		double nugget; //The height of the jump of the semivariogram at the discontinuity at the origin
+		double sill;   //Limit of the variogram tending to infinity lag distances
+		double range;  //The distance in which the difference of the variogram from the sill becomes negligible
+
+		/*SphericalVariogram constructors, destructors*/
+		SphericalVariogram();
+		SphericalVariogram(Options* options);
+		~SphericalVariogram();
+
+		/*Object virtual functions definitions*/
+		void  Echo();
+		void  DeepEcho(){_error2_("Not implemented yet");};
+		int   Id(){_error2_("Not implemented yet");}; 
+		int   MyRank(){_error2_("Not implemented yet");};
+		int   ObjectEnum(){_error2_("Not implemented yet");};
+		Object* copy(){_error2_("Not implemented yet");};
+
+		/*Variogram functions*/
+		double SemiVariogram(double deltax,double deltay);
+		double Covariance(double deltax,double deltay);
+};
+#endif  /* _SPHERICALVARIOGRAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Variogram.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Variogram.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/Variogram.h	(revision 12878)
@@ -0,0 +1,18 @@
+/*!\file:  Variogram.h
+ * \brief abstract class for Variogram object
+ */ 
+
+#ifndef _VARIOGRAM_H_
+#define _VARIOGRAM_H_
+
+#include "../objects/Object.h"
+
+class Variogram: public Object{
+
+	public: 
+		virtual ~Variogram(){};
+		virtual double SemiVariogram(double deltax,double deltay)=0;
+		virtual double Covariance(double deltax,double deltay)=0;
+
+};
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/kriging/krigingobjects.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/kriging/krigingobjects.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/kriging/krigingobjects.h	(revision 12878)
@@ -0,0 +1,17 @@
+/* \file krigingobjects.h
+ * \brief: prototype header for all kriging objects.
+ */
+
+#ifndef KRIGING_OBJECTS_H_
+#define KRIGING_OBJECTS_H_
+
+/*Kriging*/
+#include "./Variogram.h"
+#include "./GaussianVariogram.h"
+#include "./ExponentialVariogram.h"
+#include "./SphericalVariogram.h"
+#include "./PowerVariogram.h"
+#include "./Quadtree.h"
+#include "./Observation.h"
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementMatrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementMatrix.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementMatrix.cpp	(revision 12878)
@@ -0,0 +1,496 @@
+/*!\file ElementMatrix.cpp
+ * \brief: implementation of the ElementMatrix object, used to plug values from element into global stiffness matrix
+ */
+
+/*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"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*ElementMatrix constructors and destructor*/
+/*FUNCTION ElementMatrix::ElementMatrix(){{{*/
+ElementMatrix::ElementMatrix(){
+
+	this->nrows=0;
+	this->ncols=0;
+	this->values=NULL;
+	this->dofsymmetrical=false;
+
+	this->row_fsize=0;
+	this->row_flocaldoflist=NULL;
+	this->row_fglobaldoflist=NULL;
+	this->row_ssize=0;
+	this->row_slocaldoflist=NULL;
+	this->row_sglobaldoflist=NULL;
+
+	this->col_fsize=0;
+	this->col_flocaldoflist=NULL;
+	this->col_fglobaldoflist=NULL;
+	this->col_ssize=0;
+	this->col_slocaldoflist=NULL;
+	this->col_sglobaldoflist=NULL;
+
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::ElementMatrix(ElementMatrix* Ke){{{*/
+ElementMatrix::ElementMatrix(ElementMatrix* Ke){
+
+	if(!Ke) _error2_("Input Element Matrix is a NULL pointer");
+	this->Init(Ke);
+	return;
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2){{{*/
+ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2){
+
+	/*intermediaries*/
+	int i,j,counter;
+	int gsize,fsize,ssize;
+	int* P=NULL;
+	bool found;
+
+	/*If one of the two matrix is NULL, we copy the other one*/
+	if(!Ke1 && !Ke2){
+		_error2_("Two input element matrices are NULL");
+	}
+	else if(!Ke1){
+		this->Init(Ke2);
+		return;
+	}
+	else if(!Ke2){
+		this->Init(Ke1);
+		return;
+	}
+
+	/*General Case: Ke1 and Ke2 are not empty*/
+	if(!Ke1->dofsymmetrical || !Ke2->dofsymmetrical) _error2_("merging 2 non dofsymmetrical matrices not implemented yet");
+
+	/*Initialize itransformation matrix Ke[P[i]] = Ke2[i]*/
+	P=xNew<int>(Ke2->nrows);
+
+	/*1: Get the new numbering of Ke2 and get size of the new matrix*/
+	gsize=Ke1->nrows;
+	for(i=0;i<Ke2->nrows;i++){
+		found=false;
+		for(j=0;j<Ke1->nrows;j++){
+			if(Ke2->gglobaldoflist[i]==Ke1->gglobaldoflist[j]){
+				found=true; P[i]=j; break;
+			}
+		}
+		if(!found){
+			P[i]=gsize; gsize++;
+		}
+	}
+
+	/*2: Initialize static fields*/
+	this->nrows=gsize;
+	this->ncols=gsize;
+	this->dofsymmetrical=true;
+
+	/*Gset and values*/
+	this->gglobaldoflist=xNew<int>(this->nrows);
+	this->values=xNewZeroInit<IssmDouble>(this->nrows*this->ncols);
+	for(i=0;i<Ke1->nrows;i++){
+		for(j=0;j<Ke1->ncols;j++){
+			this->values[i*this->ncols+j] += Ke1->values[i*Ke1->ncols+j];
+		}
+		this->gglobaldoflist[i]=Ke1->gglobaldoflist[i];
+	}
+	for(i=0;i<Ke2->nrows;i++){
+		for(j=0;j<Ke2->ncols;j++){
+			this->values[P[i]*this->ncols+P[j]] += Ke2->values[i*Ke2->ncols+j];
+		}
+		this->gglobaldoflist[P[i]]=Ke2->gglobaldoflist[i];
+	}
+
+	/*Fset*/
+	fsize=Ke1->row_fsize;
+	for(i=0;i<Ke2->row_fsize;i++){
+		if(P[Ke2->row_flocaldoflist[i]] >= Ke1->nrows) fsize++;
+	}
+	this->row_fsize=fsize;
+	if(fsize){
+		this->row_flocaldoflist =xNew<int>(fsize);
+		this->row_fglobaldoflist=xNew<int>(fsize);
+		for(i=0;i<Ke1->row_fsize;i++){
+			this->row_flocaldoflist[i] =Ke1->row_flocaldoflist[i];
+			this->row_fglobaldoflist[i]=Ke1->row_fglobaldoflist[i];
+		}
+		counter=Ke1->row_fsize;
+		for(i=0;i<Ke2->row_fsize;i++){
+			if(P[Ke2->row_flocaldoflist[i]] >= Ke1->nrows){
+				this->row_flocaldoflist[counter] =P[Ke2->row_flocaldoflist[i]];
+				this->row_fglobaldoflist[counter]=Ke2->row_fglobaldoflist[i];
+				counter++;
+			}
+		}
+	}
+	else{
+		this->row_flocaldoflist=NULL;
+		this->row_fglobaldoflist=NULL;
+	}
+
+	/*Sset*/
+	ssize=Ke1->row_ssize;
+	for(i=0;i<Ke2->row_ssize;i++){
+		if(P[Ke2->row_slocaldoflist[i]] >= Ke1->nrows) ssize++;
+	}
+	this->row_ssize=ssize;
+	if(ssize){
+		this->row_slocaldoflist =xNew<int>(ssize);
+		this->row_sglobaldoflist=xNew<int>(ssize);
+		for(i=0;i<Ke1->row_ssize;i++){
+			this->row_slocaldoflist[i] =Ke1->row_slocaldoflist[i];
+			this->row_sglobaldoflist[i]=Ke1->row_sglobaldoflist[i];
+		}
+		counter=Ke1->row_ssize;
+		for(i=0;i<Ke2->row_ssize;i++){
+			if(P[Ke2->row_slocaldoflist[i]] >= Ke1->nrows){
+				this->row_slocaldoflist[counter] =P[Ke2->row_slocaldoflist[i]];
+				this->row_sglobaldoflist[counter]=Ke2->row_sglobaldoflist[i];
+				counter++;
+			}
+		}
+	}
+	else{
+		this->row_slocaldoflist=NULL;
+		this->row_sglobaldoflist=NULL;
+	}
+
+	/*don't do cols, we can pick them up from the rows: */
+	this->col_fsize=0;
+	this->col_flocaldoflist=NULL;
+	this->col_fglobaldoflist=NULL;
+	this->col_ssize=0;
+	this->col_slocaldoflist=NULL;
+	this->col_sglobaldoflist=NULL;
+
+	/*clean-up*/
+	xDelete<int>(P);
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2,ElementMatrix* Ke3){{{*/
+ElementMatrix::ElementMatrix(ElementMatrix* Ke1, ElementMatrix* Ke2,ElementMatrix* Ke3){
+
+	/*Concatenate all matrices*/
+	ElementMatrix* Ke12 =new ElementMatrix(Ke1,Ke2);
+	ElementMatrix* Ke123=new ElementMatrix(Ke12,Ke3);
+
+	/*Initialize current object with this matrix*/
+	this->Init(Ke123);
+
+	/*clean-up*/
+	delete Ke12;
+	delete Ke123;
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::ElementMatrix(Node** nodes,int numnodes,Parameters* parameters,int approximation){{{*/
+ElementMatrix::ElementMatrix(Node** nodes,int numnodes,Parameters* parameters,int approximation){
+
+	/*get Matrix size and properties*/
+	this->dofsymmetrical=true;
+	this->nrows=GetNumberOfDofs(nodes,numnodes,GsetEnum,approximation);
+	this->ncols=this->nrows;
+
+	/*fill values with 0: */
+	this->values=xNewZeroInit<IssmDouble>(this->nrows*this->ncols);
+
+	/*g list*/
+	this->gglobaldoflist=GetGlobalDofList(nodes,numnodes,GsetEnum,approximation);
+
+	/*get dof lists for f and s set: */
+	this->row_fsize=GetNumberOfDofs(nodes,numnodes,FsetEnum,approximation);
+	this->row_flocaldoflist =GetLocalDofList( nodes,numnodes,FsetEnum,approximation);
+	this->row_fglobaldoflist=GetGlobalDofList(nodes,numnodes,FsetEnum,approximation);
+	this->row_ssize=GetNumberOfDofs(nodes,numnodes,SsetEnum,approximation);
+	this->row_slocaldoflist =GetLocalDofList( nodes,numnodes,SsetEnum,approximation);
+	this->row_sglobaldoflist=GetGlobalDofList(nodes,numnodes,SsetEnum,approximation);
+
+	/*Because this matrix is "dofsymmetrical" don't do cols, we can pick them up from the rows: */
+	this->col_fsize=0;
+	this->col_flocaldoflist=NULL;
+	this->col_fglobaldoflist=NULL;
+	this->col_ssize=0;
+	this->col_slocaldoflist=NULL;
+	this->col_sglobaldoflist=NULL;
+
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::~ElementMatrix(){{{*/
+ElementMatrix::~ElementMatrix(){
+	
+	xDelete<IssmDouble>(this->values);
+	xDelete<int>(this->gglobaldoflist);
+	xDelete<int>(this->row_flocaldoflist);
+	xDelete<int>(this->row_fglobaldoflist);
+	xDelete<int>(this->row_slocaldoflist);
+	xDelete<int>(this->row_sglobaldoflist);
+	xDelete<int>(this->col_flocaldoflist);
+	xDelete<int>(this->col_fglobaldoflist);
+	xDelete<int>(this->col_slocaldoflist);
+	xDelete<int>(this->col_sglobaldoflist);
+}
+/*}}}*/
+
+/*ElementMatrix specific routines: */
+/*FUNCTION ElementMatrix::AddToGlobal(Matrix* Kff, Matrix* Kfs){{{*/
+void ElementMatrix::AddToGlobal(Matrix* Kff, Matrix* Kfs){
+
+	int i,j;
+	IssmDouble* localvalues=NULL;
+
+	/*If Kfs is not provided, call the other function*/
+	if(!Kfs){
+		this->AddToGlobal(Kff);
+		return;
+	}
+
+	/*In debugging mode, check consistency (no NaN, and values not too big)*/
+	this->CheckConsistency();
+
+	if(this->dofsymmetrical){
+		/*only use row dofs to add values into global matrices: */
+
+		if(this->row_fsize){
+			/*first, retrieve values that are in the f-set from the g-set values matrix: */
+			localvalues=xNew<IssmDouble>(this->row_fsize*this->row_fsize);
+			for(i=0;i<this->row_fsize;i++){
+				for(j=0;j<this->row_fsize;j++){
+					*(localvalues+this->row_fsize*i+j)=*(this->values+this->ncols*this->row_flocaldoflist[i]+this->row_flocaldoflist[j]);
+				}
+			}
+			/*add local values into global  matrix, using the fglobaldoflist: */
+			Kff->SetValues(this->row_fsize,this->row_fglobaldoflist,this->row_fsize,this->row_fglobaldoflist,localvalues,ADD_VAL);
+
+			/*Free ressources:*/
+			xDelete<IssmDouble>(localvalues);
+		}
+
+
+		if((this->row_ssize!=0) && (this->row_fsize!=0)){
+			/*first, retrieve values that are in the f and s-set from the g-set values matrix: */
+			localvalues=xNew<IssmDouble>(this->row_fsize*this->row_ssize);
+			for(i=0;i<this->row_fsize;i++){
+				for(j=0;j<this->row_ssize;j++){
+					*(localvalues+this->row_ssize*i+j)=*(this->values+this->ncols*this->row_flocaldoflist[i]+this->row_slocaldoflist[j]);
+				}
+			}
+			/*add local values into global  matrix, using the fglobaldoflist: */
+			Kfs->SetValues(this->row_fsize,this->row_fglobaldoflist,this->row_ssize,this->row_sglobaldoflist,localvalues,ADD_VAL);
+
+			/*Free ressources:*/
+			xDelete<IssmDouble>(localvalues);
+		}
+	}
+	else{
+		_error2_("non dofsymmetrical matrix AddToGlobal routine not support yet!");
+	}
+
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::AddToGlobal(Matrix* Jff){{{*/
+void ElementMatrix::AddToGlobal(Matrix* Jff){
+
+	int i,j;
+	IssmDouble* localvalues=NULL;
+
+	/*Check that Jff is not NULL*/
+	_assert_(Jff); 
+
+	/*In debugging mode, check consistency (no NaN, and values not too big)*/
+	this->CheckConsistency();
+
+	if(this->dofsymmetrical){
+		/*only use row dofs to add values into global matrices: */
+
+		if(this->row_fsize){
+			/*first, retrieve values that are in the f-set from the g-set values matrix: */
+			localvalues=xNew<IssmDouble>(this->row_fsize*this->row_fsize);
+			for(i=0;i<this->row_fsize;i++){
+				for(j=0;j<this->row_fsize;j++){
+					*(localvalues+this->row_fsize*i+j)=*(this->values+this->ncols*this->row_flocaldoflist[i]+this->row_flocaldoflist[j]);
+				}
+			}
+			/*add local values into global  matrix, using the fglobaldoflist: */
+			Jff->SetValues(this->row_fsize,this->row_fglobaldoflist,this->row_fsize,this->row_fglobaldoflist,localvalues,ADD_VAL);
+
+			/*Free ressources:*/
+			xDelete<IssmDouble>(localvalues);
+		}
+
+	}
+	else{
+		_error2_("non dofsymmetrical matrix AddToGlobal routine not support yet!");
+	}
+
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::CheckConsistency{{{*/
+void ElementMatrix::CheckConsistency(void){
+	/*Check element matrix values, only in debugging mode*/
+	#ifdef _ISSM_DEBUG_ 
+	for (int i=0;i<this->nrows;i++){
+		for(int j=0;j<this->ncols;j++){
+			if (xIsNan<IssmDouble>(this->values[i*this->ncols+j])) _error2_("NaN found in Element Matrix");
+			if (fabs(this->values[i*this->ncols+j])>1.e+50) _error2_("Element Matrix values exceeds 1.e+50");
+		}
+	}
+	#endif
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::Transpose{{{*/
+void ElementMatrix::Transpose(void){
+
+	/*Intermediaries*/
+	ElementMatrix* Ke_copy=new ElementMatrix(this);
+
+	/*Update sizes*/
+	this->nrows=Ke_copy->ncols;
+	this->ncols=Ke_copy->nrows;
+
+	/*Transpose values*/
+	for (int i=0;i<this->nrows;i++) for(int j=0;j<this->ncols;j++) this->values[i*this->ncols+j]=Ke_copy->values[j*Ke_copy->ncols+i];
+
+	/*Transpose indices*/
+	if(!dofsymmetrical){
+		_error2_("not supported yet");
+	}
+
+	/*Clean up and return*/
+	delete Ke_copy;
+	return;
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::Echo{{{*/
+void ElementMatrix::Echo(void){
+
+	int i,j;
+	_printLine_("Element Matrix echo:");
+	_printLine_("   nrows: " << nrows);
+	_printLine_("   ncols: " << nrows);
+	_printLine_("   dofsymmetrical: " << (dofsymmetrical?"true":"false"));
+
+	_printLine_("   values:");
+	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_(" ");
+
+	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_(" ");
+	}
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::Init{{{*/
+void ElementMatrix::Init(ElementMatrix* Ke){
+
+	_assert_(Ke);
+
+	this->nrows =Ke->nrows;
+	this->ncols =Ke->ncols;
+	this->dofsymmetrical=Ke->dofsymmetrical;
+
+	this->values=xNew<IssmDouble>(this->nrows*this->ncols);
+	xMemCpy<IssmDouble>(this->values,Ke->values,this->nrows*this->ncols);
+
+	this->gglobaldoflist=xNew<int>(this->nrows);
+	xMemCpy<int>(this->gglobaldoflist,Ke->gglobaldoflist,this->nrows);
+
+	this->row_fsize=Ke->row_fsize;
+	if(this->row_fsize){
+		this->row_flocaldoflist=xNew<int>(this->row_fsize);
+		xMemCpy<int>(this->row_flocaldoflist,Ke->row_flocaldoflist,this->row_fsize);
+		this->row_fglobaldoflist=xNew<int>(this->row_fsize);
+		xMemCpy<int>(this->row_fglobaldoflist,Ke->row_fglobaldoflist,this->row_fsize);
+	}
+	else{
+		this->row_flocaldoflist=NULL;
+		this->row_fglobaldoflist=NULL;
+	}
+
+	this->row_ssize=Ke->row_ssize;
+	if(this->row_ssize){
+		this->row_slocaldoflist=xNew<int>(this->row_ssize);
+		xMemCpy<int>(this->row_slocaldoflist,Ke->row_slocaldoflist,this->row_ssize);
+		this->row_sglobaldoflist=xNew<int>(this->row_ssize);
+		xMemCpy<int>(this->row_sglobaldoflist,Ke->row_sglobaldoflist,this->row_ssize);
+	}
+	else{
+		this->row_slocaldoflist=NULL;
+		this->row_sglobaldoflist=NULL;
+	}
+
+	this->col_fsize=Ke->col_fsize;
+	if(this->col_fsize){
+		this->col_flocaldoflist=xNew<int>(this->col_fsize);
+		xMemCpy<int>(this->col_flocaldoflist,Ke->col_flocaldoflist,this->col_fsize);
+		this->col_fglobaldoflist=xNew<int>(this->col_fsize);
+		xMemCpy<int>(this->col_fglobaldoflist,Ke->col_fglobaldoflist,this->col_fsize);
+	}
+	else{
+		this->col_flocaldoflist=NULL;
+		this->col_fglobaldoflist=NULL;
+	}
+
+	this->col_ssize=Ke->col_ssize;
+	if(this->col_ssize){
+		this->col_slocaldoflist=xNew<int>(this->col_ssize);
+		xMemCpy<int>(this->col_slocaldoflist,Ke->col_slocaldoflist,this->col_ssize);
+		this->col_sglobaldoflist=xNew<int>(this->col_ssize);
+		xMemCpy<int>(this->col_sglobaldoflist,Ke->col_sglobaldoflist,this->col_ssize);
+	}
+	else{
+		this->col_slocaldoflist=NULL;
+		this->col_sglobaldoflist=NULL;
+	}
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::SetDiag{{{*/
+void ElementMatrix::SetDiag(IssmDouble scalar){
+
+	int i;
+
+	if(this->nrows!=this->ncols)_error2_("need square matrix in input!");
+
+	for(i=0;i<this->nrows;i++){
+		this->values[this->ncols*i+i]=scalar;
+	}
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementMatrix.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementMatrix.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementMatrix.h	(revision 12878)
@@ -0,0 +1,70 @@
+/*!\file:  ElementMatrix.h
+ * \brief container for information needed to plug element matrix generated by elements 
+ * into the Kff and Kfs global matrices. 
+ * This object will hold the element matrix on the g-set, the local as well as global 
+ * dof lists in the f and s sets.
+ */ 
+
+#ifndef _ELEMENT_MATRIX_H_
+#define _ELEMENT_MATRIX_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../objects/Object.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+class Node;
+class Matrix;
+/*}}}*/
+
+class ElementMatrix{
+
+	public:
+	
+		int      nrows;
+		int      ncols;
+		bool     dofsymmetrical;
+		IssmDouble*  values;
+
+		//gset
+		int*     gglobaldoflist;
+
+		/*row wise: */
+		//fset
+		int      row_fsize;
+		int*     row_flocaldoflist;
+		int*     row_fglobaldoflist;
+		//sset
+		int      row_ssize;
+		int*     row_slocaldoflist;
+		int*     row_sglobaldoflist;
+
+		/*column wise: */
+		//fset
+		int      col_fsize;
+		int*     col_flocaldoflist;
+		int*     col_fglobaldoflist;
+		//sset
+		int      col_ssize;
+		int*     col_slocaldoflist;
+		int*     col_sglobaldoflist;
+
+		/*ElementMatrix constructors, destructors {{{*/
+		ElementMatrix();
+		ElementMatrix(ElementMatrix* Ke);
+		ElementMatrix(ElementMatrix* Ke1,ElementMatrix* Ke2);
+		ElementMatrix(ElementMatrix* Ke1,ElementMatrix* Ke2,ElementMatrix* Ke3);
+		ElementMatrix(Node** nodes,int numnodes,Parameters* parameters,int approximation=NoneApproximationEnum);
+		~ElementMatrix();
+		/*}}}*/
+		/*ElementMatrix specific routines {{{*/
+		void AddToGlobal(Matrix* Kff, Matrix* Kfs);
+		void AddToGlobal(Matrix* Jff);
+		void Echo(void);
+		void CheckConsistency(void);
+		void Transpose(void);
+		void Init(ElementMatrix* Ke);
+		void SetDiag(IssmDouble scalar);
+		/*}}}*/
+};
+#endif //#ifndef _ELEMENT_MATRIX_H_
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementVector.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementVector.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementVector.cpp	(revision 12878)
@@ -0,0 +1,276 @@
+/*!\file ElementVector.cpp
+ * \brief: implementation of the ElementVector object, used to plug values from element into global load
+ */
+
+/*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"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*ElementVector constructors and destructor*/
+/*FUNCTION ElementVector::ElementVector(){{{*/
+ElementVector::ElementVector(){
+
+	this->nrows=0;
+	this->values=NULL;
+	this->fsize=0;
+	this->flocaldoflist=NULL;
+	this->fglobaldoflist=NULL;
+
+}
+/*}}}*/
+/*FUNCTION ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2){{{*/
+ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2){
+
+	/*intermediaries*/
+	int i,j,counter;
+	int gsize,fsize,ssize;
+	int* P=NULL;
+	bool found;
+
+	/*If one of the two matrix is NULL, we copy the other one*/
+	if(!pe1 && !pe2){
+		_error2_("Two input element matrices are NULL");
+	}
+	else if(!pe1){
+		this->Init(pe2);
+		return;
+	}
+	else if(!pe2){
+		this->Init(pe1);
+		return;
+	}
+
+	/*Initialize itransformation matrix pe[P[i]] = pe2[i]*/
+	P=xNew<int>(pe2->nrows);
+
+	/*1: Get the new numbering of pe2 and get size of the new matrix*/
+	gsize=pe1->nrows;
+	for(i=0;i<pe2->nrows;i++){
+		found=false;
+		for(j=0;j<pe1->nrows;j++){
+			if(pe2->gglobaldoflist[i]==pe1->gglobaldoflist[j]){
+				found=true; P[i]=j; break;
+			}
+		}
+		if(!found){
+			P[i]=gsize; gsize++;
+		}
+	}
+
+	/*2: Initialize static fields*/
+	this->nrows=gsize;
+
+	/*Gset and values*/
+	this->gglobaldoflist=xNew<int>(this->nrows);
+	this->values=xNewZeroInit<IssmDouble>(this->nrows);
+	for(i=0;i<pe1->nrows;i++){
+		this->values[i] += pe1->values[i];
+		this->gglobaldoflist[i]=pe1->gglobaldoflist[i];
+	}
+	for(i=0;i<pe2->nrows;i++){
+		this->values[P[i]] += pe2->values[i];
+		this->gglobaldoflist[P[i]]=pe2->gglobaldoflist[i];
+	}
+
+	/*Fset*/
+	fsize=pe1->fsize;
+	for(i=0;i<pe2->fsize;i++){
+		if(P[pe2->flocaldoflist[i]] >= pe1->nrows) fsize++;
+	}
+	this->fsize=fsize;
+	if(fsize){
+		this->flocaldoflist =xNew<int>(fsize);
+		this->fglobaldoflist=xNew<int>(fsize);
+		for(i=0;i<pe1->fsize;i++){
+			this->flocaldoflist[i] =pe1->flocaldoflist[i];
+			this->fglobaldoflist[i]=pe1->fglobaldoflist[i];
+		}
+		counter=pe1->fsize;
+		for(i=0;i<pe2->fsize;i++){
+			if(P[pe2->flocaldoflist[i]] >= pe1->nrows){
+				this->flocaldoflist[counter] =P[pe2->flocaldoflist[i]];
+				this->fglobaldoflist[counter]=pe2->fglobaldoflist[i];
+				counter++;
+			}
+		}
+	}
+	else{
+		this->flocaldoflist=NULL;
+		this->fglobaldoflist=NULL;
+	}
+
+	/*clean-up*/
+	xDelete<int>(P);
+}
+/*}}}*/
+/*FUNCTION ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2,ElementVector* pe3){{{*/
+ElementVector::ElementVector(ElementVector* pe1, ElementVector* pe2,ElementVector* pe3){
+
+	/*Concatenate all matrices*/
+	ElementVector* pe12 =new ElementVector(pe1,pe2);
+	ElementVector* pe123=new ElementVector(pe12,pe3);
+
+	/*Initialize current object with this matrix*/
+	this->Init(pe123);
+
+	/*clean-up*/
+	delete pe12;
+	delete pe123;
+}
+/*}}}*/
+/*FUNCTION ElementVector::ElementVector(Node** nodes,int numnodes,Parameters* parameters,int approximation){{{*/
+ElementVector::ElementVector(Node** nodes,int numnodes,Parameters* parameters,int approximation){
+
+	/*get Vector size and properties*/
+	this->nrows=GetNumberOfDofs(nodes,numnodes,GsetEnum,approximation);
+
+	/*fill values with 0: */
+	this->values=xNewZeroInit<IssmDouble>(this->nrows);
+	
+	/*g list*/
+	this->gglobaldoflist=GetGlobalDofList(nodes,numnodes,GsetEnum,approximation);
+
+	/*Get fsize*/
+	this->fsize=GetNumberOfDofs(nodes,numnodes,FsetEnum,approximation);
+	this->flocaldoflist =GetLocalDofList( nodes,numnodes,FsetEnum,approximation);
+	this->fglobaldoflist=GetGlobalDofList(nodes,numnodes,FsetEnum,approximation);
+}
+/*}}}*/
+/*FUNCTION ElementVector::~ElementVector(){{{*/
+ElementVector::~ElementVector(){
+	
+	xDelete<IssmDouble>(this->values);
+	xDelete<int>(this->gglobaldoflist);
+	xDelete<int>(this->flocaldoflist);
+	xDelete<int>(this->fglobaldoflist);
+}
+/*}}}*/
+
+/*ElementVector specific routines: */
+/*FUNCTION ElementVector::AddToGlobal(Vector* pf){{{*/
+void ElementVector::AddToGlobal(Vector* pf){
+
+	int i;
+	IssmDouble* localvalues=NULL;
+
+	/*In debugging mode, check consistency (no NaN, and values not too big)*/
+	this->CheckConsistency();
+
+	if(this->fsize){
+		/*first, retrieve values that are in the f-set from the g-set values vector: */
+		localvalues=xNew<IssmDouble>(this->fsize);
+		for(i=0;i<this->fsize;i++){
+			localvalues[i]=this->values[this->flocaldoflist[i]];
+		}
+		/*add local values into global  vector, using the fglobaldoflist: */
+		pf->SetValues(this->fsize,this->fglobaldoflist,localvalues,ADD_VAL);
+
+		/*Free ressources:*/
+		xDelete<IssmDouble>(localvalues);
+	}
+	
+}
+/*}}}*/
+/*FUNCTION ElementVector::InsertIntoGlobal(Vector* pf){{{*/
+void ElementVector::InsertIntoGlobal(Vector* pf){
+
+	int i;
+	IssmDouble* localvalues=NULL;
+
+	if(this->fsize){
+		/*first, retrieve values that are in the f-set from the g-set values vector: */
+		localvalues=xNew<IssmDouble>(this->fsize);
+		for(i=0;i<this->fsize;i++){
+			localvalues[i]=this->values[this->flocaldoflist[i]];
+		}
+		/*add local values into global  vector, using the fglobaldoflist: */
+		pf->SetValues(this->fsize,this->fglobaldoflist,localvalues,INS_VAL);
+
+		/*Free ressources:*/
+		xDelete<IssmDouble>(localvalues);
+	}
+
+}
+/*}}}*/
+/*FUNCTION ElementVector::CheckConsistency{{{*/
+void ElementVector::CheckConsistency(void){
+	/*Check element matrix values, only in debugging mode*/
+#ifdef _ISSM_DEBUG_ 
+	for (int i=0;i<this->nrows;i++){
+		if (xIsNan<IssmDouble>(this->values[i])) _error2_("NaN found in Element Vector");
+		if (fabs( this->values[i])>1.e+50) _error2_("Element Vector values exceeds 1.e+50");
+	}
+#endif
+}
+/*}}}*/
+/*FUNCTION ElementVector::Echo{{{*/
+void ElementVector::Echo(void){
+
+	int i,j;
+	_printLine_("Element Vector echo:");
+	_printLine_("   nrows: " << nrows);
+	_printLine_("   values:");
+	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_(" ");
+}
+/*}}}*/
+/*FUNCTION ElementVector::Init{{{*/
+void ElementVector::Init(ElementVector* pe){
+
+	_assert_(pe);
+
+	this->nrows =pe->nrows;
+
+	this->values=xNew<IssmDouble>(this->nrows);
+	xMemCpy<IssmDouble>(this->values,pe->values,this->nrows);
+
+	this->gglobaldoflist=xNew<int>(this->nrows);
+	xMemCpy<int>(this->gglobaldoflist,pe->gglobaldoflist,this->nrows);
+
+	this->fsize=pe->fsize;
+	if(this->fsize){
+		this->flocaldoflist=xNew<int>(this->fsize);
+		xMemCpy<int>(this->flocaldoflist,pe->flocaldoflist,this->fsize);
+		this->fglobaldoflist=xNew<int>(this->fsize);
+		xMemCpy<int>(this->fglobaldoflist,pe->fglobaldoflist,this->fsize);
+	}
+	else{
+		this->flocaldoflist=NULL;
+		this->fglobaldoflist=NULL;
+	}
+}
+/*}}}*/
+/*FUNCTION ElementVector::SetValue{{{*/
+void ElementVector::SetValue(IssmDouble scalar){
+
+	int i;
+
+	for(i=0;i<this->nrows;i++)this->values[i]=scalar;
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementVector.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementVector.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/ElementVector.h	(revision 12878)
@@ -0,0 +1,52 @@
+/*!\file:  ElementVector.h
+ * \brief container for information needed to plug element vector generated by elements 
+ * into the pf global load vector. 
+ * This object will hold the element vector on the g-set, the local as well as global 
+ * dof lists in the f set
+ */ 
+
+#ifndef _ELEMENT_VECTOR_H_
+#define _ELEMENT_VECTOR_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../objects/Object.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+class Node;
+class Vector;
+/*}}}*/
+
+class ElementVector{
+
+	public:
+	
+		int      nrows;
+		IssmDouble*  values;
+		
+		//gset
+		int*     gglobaldoflist;
+
+		//fset
+		int      fsize;
+		int*     flocaldoflist;
+		int*     fglobaldoflist;
+		
+		/*ElementVector constructors, destructors {{{*/
+		ElementVector();
+		ElementVector(ElementVector* pe1,ElementVector* pe2);
+		ElementVector(ElementVector* pe1,ElementVector* pe2,ElementVector* pe3);
+		ElementVector(Node** nodes,int numnodes,Parameters* parameters,int approximation=NoneApproximationEnum);
+		~ElementVector();
+		/*}}}*/
+		/*ElementVector specific routines {{{*/
+		void AddToGlobal(Vector* pf);
+		void InsertIntoGlobal(Vector* pf);
+		void Echo(void);
+		void CheckConsistency(void);
+		void Init(ElementVector* pe);
+		void SetValue(IssmDouble scalar);
+		/*}}}*/
+};
+#endif //#ifndef _ELEMENT_VECTOR_H_
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Matrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Matrix.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Matrix.cpp	(revision 12878)
@@ -0,0 +1,323 @@
+/*!\file Matrix.cpp
+ * \brief: implementation of the Matrix 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"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "./Matrix.h"
+	
+/*}}}*/
+
+/*Matrix constructors and destructor*/
+/*FUNCTION Matrix::Matrix(){{{*/
+Matrix::Matrix(){
+
+	pmatrix=NULL;
+	smatrix=NULL;
+
+	type=PetscMatType; //default
+	#ifndef _HAVE_PETSC_
+	type=SeqMatType;
+	#endif
+	
+}
+/*}}}*/
+/*FUNCTION Matrix::Matrix(int M,int N,int type){{{*/
+Matrix::Matrix(int M,int N,int in_type){
+
+	pmatrix=NULL;
+	smatrix=NULL;
+	type=in_type;
+
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		this->pmatrix=new PetscMat(M,N);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		this->smatrix=new SeqMat(M,N);
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Matrix::Matrix(int M,int N,IssmDouble sparsity,int type){{{*/
+Matrix::Matrix(int M,int N,IssmDouble sparsity,int in_type){
+
+	pmatrix=NULL;
+	smatrix=NULL;
+	type=in_type;
+
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		this->pmatrix=new PetscMat(M,N,sparsity);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		this->smatrix=new SeqMat(M,N,sparsity);
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Matrix::Matrix(IssmDouble* serial_mat, int M,int N,IssmDouble sparsity,int type){{{*/
+Matrix::Matrix(IssmDouble* serial_mat, int M,int N,IssmDouble sparsity,int in_type){
+
+	pmatrix=NULL;
+	smatrix=NULL;
+	type=in_type;
+
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		this->pmatrix=new PetscMat(serial_mat,M,N,sparsity);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		this->smatrix=new SeqMat(serial_mat,M,N,sparsity);
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+	
+}
+/*}}}*/
+/*FUNCTION Matrix::Matrix(int M,int N,int connectivity,int numberofdofspernode,int type){{{*/
+Matrix::Matrix(int M,int N,int connectivity,int numberofdofspernode,int in_type){
+
+	pmatrix=NULL;
+	smatrix=NULL;
+	type=in_type;
+
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		this->pmatrix=new PetscMat(M,N,connectivity,numberofdofspernode);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		this->smatrix=new SeqMat(M,N,connectivity,numberofdofspernode);
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+	
+}
+/*}}}*/
+/*FUNCTION Matrix::~Matrix(){{{*/
+Matrix::~Matrix(){
+
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		delete this->pmatrix;
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		delete this->smatrix;
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+
+/*Matrix specific routines: */
+/*FUNCTION Matrix::Echo{{{*/
+void Matrix::Echo(void){
+
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		this->pmatrix->Echo();
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		this->smatrix->Echo();
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Matrix::Assemble{{{*/
+void Matrix::Assemble(void){
+
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		this->pmatrix->Assemble();
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		this->smatrix->Assemble();
+	}
+	else{
+		_error2_("Matrix type: " << type << " not supported yet!");
+	}
+}
+/*}}}*/
+/*FUNCTION Matrix::Norm{{{*/
+IssmDouble Matrix::Norm(NormMode norm_type){
+	
+	IssmDouble norm=0;
+
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		norm=this->pmatrix->Norm(norm_type);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		norm=this->smatrix->Norm(norm_type);
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+
+	return norm;
+}
+/*}}}*/
+/*FUNCTION Matrix::GetSize{{{*/
+void Matrix::GetSize(int* pM,int* pN){
+
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		this->pmatrix->GetSize(pM,pN);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		this->smatrix->GetSize(pM,pN);
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+	
+}
+/*}}}*/
+/*FUNCTION Matrix::GetLocalSize{{{*/
+void Matrix::GetLocalSize(int* pM,int* pN){
+	
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		this->pmatrix->GetLocalSize(pM,pN);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		this->smatrix->GetLocalSize(pM,pN);
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Matrix::MatMult{{{*/
+void Matrix::MatMult(Vector* X,Vector* AX){
+
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		this->pmatrix->MatMult(X->pvector,AX->pvector);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		this->smatrix->MatMult(X->svector,AX->svector);
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Matrix::Duplicate{{{*/
+Matrix* Matrix::Duplicate(void){
+
+	Matrix* output=NULL;
+
+	output=new Matrix();
+
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		output->pmatrix=this->pmatrix->Duplicate();
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		output->smatrix=this->smatrix->Duplicate();
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+	
+	return output;
+}
+/*}}}*/
+/*FUNCTION Matrix::ToSerial{{{*/
+IssmDouble* Matrix::ToSerial(void){
+
+	IssmDouble* output=NULL;
+	
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		output=this->pmatrix->ToSerial();
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		output=this->smatrix->ToSerial();
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+
+
+	return output;
+}
+/*}}}*/
+/*FUNCTION Matrix::SetValues{{{*/
+void Matrix::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);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		this->smatrix->SetValues(m,idxm,n,idxn,values,mode);
+	}
+	else _error2_("Matrix type: " << type << " not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Matrix::Convert{{{*/
+void Matrix::Convert(MatrixType newtype){
+
+	if(type==PetscMatType){
+		#ifdef _HAVE_PETSC_
+		this->pmatrix->Convert(newtype);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqMatType){
+		this->smatrix->Convert(newtype);
+	}
+	else{
+		_error2_("Matrix type: " << type << " not supported yet!");
+	}
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Matrix.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Matrix.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Matrix.h	(revision 12878)
@@ -0,0 +1,54 @@
+/*!\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"
+/*}}}*/
+class Vector;
+enum matrixtype{PetscMatType, SeqMatType};
+
+class Matrix{
+
+	public:
+
+		#ifdef _HAVE_PETSC_
+		PetscMat *pmatrix;
+		#endif
+		SeqMat   *smatrix;
+		int       type;
+
+		/*Matrix constructors, destructors {{{*/
+		Matrix();
+		Matrix(int M,int N,int type=PetscMatType);
+		Matrix(int M,int N,IssmDouble sparsity,int type=PetscMatType);
+		Matrix(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity,int type=PetscMatType);
+		Matrix(int M,int N,int connectivity,int numberofdofspernode,int type=PetscMatType);
+		~Matrix();
+		/*}}}*/
+		/*Matrix specific routines {{{*/
+		void        Echo(void);
+		void        Assemble(void);
+		IssmDouble  Norm(NormMode norm_type);
+		void        GetSize(int *pM,int*pN);
+		void        GetLocalSize(int *pM,int*pN);
+		void        MatMult(Vector *X,Vector*AX);
+		Matrix     *Duplicate(void);
+		IssmDouble *ToSerial(void);
+		void        SetValues(int m,int *idxm,int n,int*idxn,IssmDouble*values,InsMode mode);
+		void        Convert(MatrixType newtype);
+		/*}}}*/
+};
+
+#endif //#ifndef _MATRIX_H_
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Vector.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Vector.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Vector.cpp	(revision 12878)
@@ -0,0 +1,429 @@
+/*!\file Vector.cpp
+ * \brief: implementation of the Vector 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"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "./Vector.h"
+/*}}}*/
+
+/*Vector constructors and destructor*/
+/*FUNCTION Vector::Vector(){{{*/
+Vector::Vector(){
+
+	this->pvector=NULL;
+	this->svector=NULL;
+	
+	type=PetscVecType; //default
+	#ifndef _HAVE_PETSC_
+	type=SeqVecType;
+	#endif
+
+}
+/*}}}*/
+/*FUNCTION Vector::Vector(int M,bool fromlocalsize,int type){{{*/
+Vector::Vector(int M,bool fromlocalsize,int in_type){
+	
+	pvector=NULL;
+	svector=NULL;
+	type=in_type;
+
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector=new PetscVec(M,fromlocalsize);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector=new SeqVec(M,fromlocalsize);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Vector::Vector(IssmDouble* serial_vec,int M,int type){{{*/
+Vector::Vector(IssmDouble* serial_vec,int M,int in_type){
+
+	pvector=NULL;
+	svector=NULL;
+	type=in_type;
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector=new PetscVec(serial_vec,M);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector=new SeqVec(serial_vec,M);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Vector::~Vector(){{{*/
+Vector::~Vector(){
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		delete this->pvector;
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		delete this->svector;
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+}
+/*}}}*/
+
+/*Vector specific routines: */
+/*FUNCTION Vector::Echo{{{*/
+void Vector::Echo(void){
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->Echo();
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->Echo();
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Vector::Assemble{{{*/
+void Vector::Assemble(void){
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->Assemble();
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->Assemble();
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Vector::SetValues{{{*/
+void Vector::SetValues(int ssize, int* list, IssmDouble* values, InsMode mode){
+		
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->SetValues(ssize,list,values,mode);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->SetValues(ssize,list,values,mode);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+		
+
+}
+/*}}}*/
+/*FUNCTION Vector::SetValue{{{*/
+void Vector::SetValue(int dof, IssmDouble value, InsMode mode){
+	
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->SetValue(dof,value,mode);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->SetValue(dof,value,mode);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Vector::GetValue{{{*/
+void Vector::GetValue(IssmDouble* pvalue,int dof){
+		
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->GetValue(pvalue,dof);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->GetValue(pvalue,dof);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Vector::GetSize{{{*/
+void Vector::GetSize(int* pM){
+	
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->GetSize(pM);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->GetSize(pM);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Vector::IsEmpty{{{*/
+bool Vector::IsEmpty(void){
+
+	int M;
+
+	this->GetSize(&M);
+
+	if(M==0) 
+	 return true;
+	else
+	 return false;
+}
+/*}}}*/
+/*FUNCTION Vector::GetLocalSize{{{*/
+void Vector::GetLocalSize(int* pM){
+		
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->GetLocalSize(pM);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->GetLocalSize(pM);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Vector::Duplicate{{{*/
+Vector* Vector::Duplicate(void){
+	
+	Vector* output=NULL;
+
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		output=new Vector();
+		output->pvector=this->pvector->Duplicate();
+		#else
+		_error2_("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 _error2_("Vector type: " << type << " not supported yet!");
+
+	return output;
+
+}
+/*}}}*/
+/*FUNCTION Vector::Set{{{*/
+void Vector::Set(IssmDouble value){
+	
+	
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->Set(value);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->Set(value);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Vector::AXPY{{{*/
+void Vector::AXPY(Vector* X, IssmDouble a){
+	
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->AXPY(X->pvector,a);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->AXPY(X->svector,a);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Vector::AYPX{{{*/
+void Vector::AYPX(Vector* X, IssmDouble a){
+	
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->AYPX(X->pvector,a);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->AYPX(X->svector,a);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+
+}
+/*}}}*/
+/*FUNCTION Vector::ToMPISerial{{{*/
+IssmDouble* Vector::ToMPISerial(void){
+
+	IssmDouble* vec_serial=NULL;
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		vec_serial=this->pvector->ToMPISerial();
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		vec_serial=this->svector->ToMPISerial();
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+	return vec_serial;
+
+}
+/*}}}*/
+/*FUNCTION Vector::Copy{{{*/
+void Vector::Copy(Vector* to){
+
+	
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->Copy(to->pvector);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->Copy(to->svector);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+
+}
+/*}}}*/
+/*FUNCTION Vector::Norm{{{*/
+IssmDouble Vector::Norm(NormMode norm_type){
+	
+	IssmDouble norm=0;
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		norm=this->pvector->Norm(norm_type);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		norm=this->svector->Norm(norm_type);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+	return norm;
+}
+/*}}}*/
+/*FUNCTION Vector::Scale{{{*/
+void Vector::Scale(IssmDouble scale_factor){
+	
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->Scale(scale_factor);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->Scale(scale_factor);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Vector::Dot{{{*/
+IssmDouble Vector::Dot(Vector* vector){
+
+	IssmDouble dot;
+	
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		dot=this->pvector->Dot(vector->pvector);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		dot=this->svector->Dot(vector->svector);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+	return dot;
+}
+/*}}}*/
+/*FUNCTION Vector::PointwiseDivide{{{*/
+void Vector::PointwiseDivide(Vector* x,Vector* y){
+
+
+	if(type==PetscVecType){
+		#ifdef _HAVE_PETSC_
+		this->pvector->PointwiseDivide(x->pvector,y->pvector);
+		#else
+		_error2_("Petsc matrix format not usable, as Petsc has not been compiled!");
+		#endif
+	}
+	else if(type==SeqVecType){
+		this->svector->PointwiseDivide(x->svector,y->svector);
+	}
+	else _error2_("Vector type: " << type << " not supported yet!");
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Vector.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Vector.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/Vector.h	(revision 12878)
@@ -0,0 +1,63 @@
+/*!\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 };
+
+class Vector{
+
+	public:
+
+		#ifdef _HAVE_PETSC_
+		PetscVec* pvector;
+		#endif
+		SeqVec* svector; 
+		int     type;
+	
+
+		/*Vector constructors, destructors {{{*/
+		Vector();
+		Vector(int M,bool fromlocalsize=false,int type=PetscVecType);
+		Vector(IssmDouble* serial_vec,int pM,int type=PetscVecType);
+		~Vector();
+		/*}}}*/
+		/*Vector specific routines {{{*/
+		void    Echo(void);
+		void    AXPY(Vector *X, IssmDouble a);
+		void    AYPX(Vector *X, IssmDouble a);
+		void    Assemble(void);
+		void    Copy(Vector *to);
+		IssmDouble  Dot(Vector *vector);
+		Vector *Duplicate(void);
+		void    GetValue(IssmDouble *pvalue, int dof);
+		void    GetSize(int *pM);
+		void    GetLocalSize(int *pM);
+		bool    IsEmpty(void);
+		IssmDouble  Norm(NormMode norm_type);
+		void    PointwiseDivide(Vector  *x,Vector*y);
+		void    Scale(IssmDouble scale_factor);
+		void    Set(IssmDouble value);
+		void    SetValues(int ssize, int *list, IssmDouble*values, InsMode mode);
+		void    SetValue(int dof, IssmDouble value, InsMode mode);
+		IssmDouble *ToMPISerial(void);
+		/*}}}*/
+};
+
+
+#endif //#ifndef _VECTOR_H_
Index: /issm/branches/trunk-jpl-damage/src/c/classes/matrix/matrixobjects.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/matrix/matrixobjects.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/matrix/matrixobjects.h	(revision 12878)
@@ -0,0 +1,16 @@
+/* \file matrixobjects.h
+ * \brief: prototype header for all matrix objects.
+ */
+
+#ifndef ALL_MATRIX_OBJECTS_H_
+#define ALL_MATRIX_OBJECTS_H_
+
+
+/*Numerics:*/
+#include "./ElementMatrix.h"
+#include "./ElementVector.h"
+#include "./Vector.h"
+#include "./Matrix.h"
+
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects.h	(revision 12878)
@@ -0,0 +1,68 @@
+/* \file objects.h
+ * \brief: prototype header for all objects.
+ */
+
+#ifndef ALL_OBJECTS_H_
+#define ALL_OBJECTS_H_
+
+/*Abstract classes: */
+#include "./objects/objects.h"
+
+/*Objects: */
+#include "./Hook.h"
+#include "./DofIndexing.h"
+#include "./IoModel.h"
+#include "./Patch.h"
+#include "./Update.h"
+
+/*Gauss*/
+#include "./gauss/GaussTria.h"
+#include "./gauss/GaussPenta.h"
+
+/*Numerics:*/
+#include "./matrix/ElementMatrix.h"
+#include "./matrix/ElementVector.h"
+#include "./matrix/Vector.h"
+#include "./matrix/Matrix.h"
+
+/*C objects: */
+#include "./FemModel.h"
+#include "./OptArgs.h"
+#include "./OptPars.h"
+
+/*Bamg: */
+#include "./bamg/BamgOpts.h"
+#include "./bamg/BamgGeom.h"
+#include "./bamg/BamgMesh.h"
+#include "./bamg/Metric.h"
+#include "./bamg/DoubleAndInt.h"
+#include "./bamg/Direction.h"
+#include "./bamg/BamgVertex.h"
+#include "./bamg/AdjacentTriangle.h"
+#include "./bamg/Edge.h"
+#include "./bamg/GeomVertex.h"
+#include "./bamg/GeomEdge.h"
+#include "./bamg/Curve.h"
+#include "./bamg/Triangle.h"
+#include "./bamg/ListofIntersectionTriangles.h"
+#include "./bamg/GeomSubDomain.h"
+#include "./bamg/SubDomain.h"
+#include "./bamg/VertexOnGeom.h"
+#include "./bamg/VertexOnVertex.h"
+#include "./bamg/VertexOnEdge.h"
+#include "./bamg/CrackedEdge.h"
+#include "./bamg/Mesh.h"
+#include "./bamg/Geometry.h"
+#include "./bamg/BamgQuadtree.h"
+#include "./bamg/SetOfE4.h"
+
+/*Kriging*/
+#include "./kriging/Variogram.h"
+#include "./kriging/GaussianVariogram.h"
+#include "./kriging/ExponentialVariogram.h"
+#include "./kriging/SphericalVariogram.h"
+#include "./kriging/PowerVariogram.h"
+#include "./kriging/Quadtree.h"
+#include "./kriging/Observation.h"
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/Constraint.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/Constraint.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/Constraint.h	(revision 12878)
@@ -0,0 +1,28 @@
+/*!\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 "../Object.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/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcDynamic.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcDynamic.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcDynamic.cpp	(revision 12878)
@@ -0,0 +1,141 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../Container/Container.h"
+#include "../objects.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){
+
+	_printLine_("SpcDynamic:");
+	_printLine_("   sid: " << sid);
+	_printLine_("   nodeid: " << nodeid);
+	_printLine_("   dof: " << dof);
+	_printLine_("   value: " << value);
+	_printLine_("   isset: " <<(isset?"true":"false"));
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	return;
+}
+/*}}}*/
+/*FUNCTION SpcDynamic::DeepEcho {{{*/
+void SpcDynamic::DeepEcho(void){
+
+	this->Echo();
+	return;
+}		
+/*}}}*/
+/*FUNCTION SpcDynamic::Id {{{*/
+int    SpcDynamic::Id(void){ return sid; }
+/*}}}*/
+/*FUNCTION SpcDynamic::MyRank {{{*/
+int    SpcDynamic::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcDynamic.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcDynamic.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcDynamic.h	(revision 12878)
@@ -0,0 +1,52 @@
+/*!\file SpcDynamic.h
+ * \brief: header file for spc object
+ */
+
+#ifndef _SPCDynamic_H_
+#define _SPCDynamic_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../Object.h"
+class DataSet;
+/*}}}*/
+
+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   MyRank();
+		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/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcStatic.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcStatic.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcStatic.cpp	(revision 12878)
@@ -0,0 +1,129 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../Container/Container.h"
+#include "../objects.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){
+
+	_printLine_("SpcStatic:");
+	_printLine_("   sid: " << sid);
+	_printLine_("   nodeid: " << nodeid);
+	_printLine_("   dof: " << dof);
+	_printLine_("   value: " << value);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	return;
+}
+/*}}}*/
+/*FUNCTION SpcStatic::DeepEcho {{{*/
+void SpcStatic::DeepEcho(void){
+
+	_printLine_("SpcStatic:");
+	_printLine_("   sid: " << sid);
+	_printLine_("   nodeid: " << nodeid);
+	_printLine_("   dof: " << dof);
+	_printLine_("   value: " << value);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	return;
+}		
+/*}}}*/
+/*FUNCTION SpcStatic::Id {{{*/
+int    SpcStatic::Id(void){ return sid; }
+/*}}}*/
+/*FUNCTION SpcStatic::MyRank {{{*/
+int    SpcStatic::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcStatic.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcStatic.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcStatic.h	(revision 12878)
@@ -0,0 +1,50 @@
+/*!\file SpcStatic.h
+ * \brief: header file for spc object
+ */
+
+#ifndef _SPCStatic_H_
+#define _SPCStatic_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../Object.h"
+class DataSet;
+/*}}}*/
+
+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   MyRank();
+		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/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcTransient.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcTransient.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcTransient.cpp	(revision 12878)
@@ -0,0 +1,176 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../Container/Container.h"
+#include "../objects.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;
+	_printLine_("SpcTransient:");
+	_printLine_("   sid: " << sid);
+	_printLine_("   nodeid: " << nodeid);
+	_printLine_("   dof: " << dof);
+	_printLine_("   nsteps: " << nsteps);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	_printLine_("   steps|times|values");
+	for(i=0;i<nsteps;i++){
+		_printLine_(i << "-" << times[i] << ":" << values[i]);
+	}
+	return;
+}
+/*}}}*/
+/*FUNCTION SpcTransient::DeepEcho {{{*/
+void SpcTransient::DeepEcho(void){
+	this->Echo();
+}		
+/*}}}*/
+/*FUNCTION SpcTransient::Id {{{*/
+int    SpcTransient::Id(void){ return sid; }
+/*}}}*/
+/*FUNCTION SpcTransient::MyRank {{{*/
+int    SpcTransient::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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)_error2_("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/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcTransient.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcTransient.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Constraints/SpcTransient.h	(revision 12878)
@@ -0,0 +1,52 @@
+/*!\file SpcTransient.h
+ * \brief: header file for spc object
+ */
+
+#ifndef _SPCTRANSIENT_H_
+#define _SPCTRANSIENT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../Object.h"
+class DataSet;
+/*}}}*/
+
+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   MyRank();
+		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/branches/trunk-jpl-damage/src/c/classes/objects/Contour.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Contour.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Contour.cpp	(revision 12878)
@@ -0,0 +1,95 @@
+/*! \file Contour.c
+ *  \sa Contour.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 "./objects.h"
+#include "../../include/include.h"
+#include "../../io/io.h"
+
+/*Contour constructors and destructors:*/
+/*FUNCTION Contour::Contour() default constructor {{{*/
+Contour::Contour(){
+	this->id=0;
+	this->nods=0;
+	this->x=NULL;
+	this->y=NULL;
+	this->closed=false;
+}
+/*}}}*/
+/*FUNCTION Contour::Contour(int pid, int nods, IssmDouble* x, IssmDouble* y,bool closed) {{{*/
+Contour::Contour(int pid,int pnods, IssmDouble* px, IssmDouble* py,bool pclosed){
+	
+	this->id=pid;
+	this->nods=pnods;
+	this->closed=pclosed;
+	if(nods){
+		this->x=xNew<IssmDouble>(nods);
+		xMemCpy<IssmDouble>(this->x,px,nods);
+		this->y=xNew<IssmDouble>(nods);
+		xMemCpy<IssmDouble>(this->y,py,nods);
+	}
+}
+/*}}}*/
+/*FUNCTION Contour::Contour() default constructor {{{*/
+Contour::~Contour(){
+	xDelete<IssmDouble>(this->x);
+	xDelete<IssmDouble>(this->y);
+}
+/*}}}*/
+
+
+/*Object virtual function resolutoin: */
+/*FUNCTION Contour::Echo(){{{*/
+void Contour::Echo(void){
+
+	int i;
+
+	_printLine_("Contour: " << id);
+	_printLine_("   nods: " << nods);
+	_printLine_("   closed: " << (closed?"true":"false"));
+	if(nods){
+	        _printLine_("   x,y:");
+		for(i=0;i<nods;i++){
+		        _printLine_(i << ": " << x[i] << "|" << y[i]);
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Contour::DeepEcho(){{{*/
+void Contour::DeepEcho(void){
+	this->Echo();
+}
+/*}}}*/
+/*FUNCTION Contour::Id(){{{*/
+int Contour::Id(void){
+	return id;
+}
+/*}}}*/
+/*FUNCTION Contour::MyRank{{{*/
+int    Contour::MyRank(void){ 
+	extern int my_rank;
+
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION Contour::ObjectEnum{{{*/
+int Contour::ObjectEnum(void){
+
+	return ContourEnum;
+
+}
+/*}}}*/
+/*FUNCTION Contour::copy {{{*/
+Object* Contour::copy() {
+
+	return new Contour(*this); 
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Contour.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Contour.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Contour.h	(revision 12878)
@@ -0,0 +1,43 @@
+/*!\file Contour.h
+ * \brief: header file for Contour object
+ */
+
+#ifndef _CONTOUR_H_
+#define _CONTOUR_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Object.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../toolkits/toolkits.h"
+#include "../../include/include.h"
+/*}}}*/
+
+class Contour: public Object{
+
+	public: 
+
+		int     id;
+		int	  nods;  //number of vertices in the contour
+		IssmDouble* x;
+		IssmDouble* y;
+		bool    closed; //is this contour closed?
+
+		/*Contour constructors, destructors {{{*/
+		Contour();
+		Contour(int id, int nods, IssmDouble* x, IssmDouble* y,bool closed);
+		~Contour();
+		/*}}}*/
+		/*Object virtual functions{{{*/
+		void  Echo(void);
+		void  DeepEcho(void);
+		int   Id(void);
+		int   MyRank(void);
+		int   ObjectEnum(void);
+		Object* copy(void);
+		/*}}}*/
+
+
+};
+
+#endif  /* _CONTOUR_H_ */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/BoolElementResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/BoolElementResult.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/BoolElementResult.cpp	(revision 12878)
@@ -0,0 +1,136 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "./ElementResultLocal.h"
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("BoolElementResult:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: "<<(this->value?"true":"false"));
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+}
+/*}}}*/
+/*FUNCTION BoolElementResult::Id{{{*/
+int    BoolElementResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION BoolElementResult::MyRank{{{*/
+int    BoolElementResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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::ProcessUnits{{{*/
+void BoolElementResult::ProcessUnits(Parameters* parameters){
+// no op
+}
+/*}}}*/
+/*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* vector,int* doflist,int* connectivitylist,int numdofs){
+
+	_error2_("cannot return vector on vertices");
+} /*}}}*/
+/*FUNCTION BoolElementResult::GetElementVectorFromResults{{{*/
+void BoolElementResult::GetElementVectorFromResults(Vector* vector,int dof){
+
+	vector->SetValue(dof,value,INS_VAL);
+} /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/BoolElementResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/BoolElementResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/BoolElementResult.h	(revision 12878)
@@ -0,0 +1,54 @@
+/*! \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"
+#include "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ElementResult virtual functions definitions: {{{*/
+		ElementResult* SpawnTriaElementResult(int* indices);
+		IssmDouble  GetTime(void){return time;};
+		int     GetStep(void){return step;};
+		void    ProcessUnits(Parameters* parameters);
+		int     NumberOfNodalValues(void);
+		void    PatchFill(int row, Patch* patch);
+		/*}}}*/
+		/*BoolElementResult management: {{{*/
+		int   InstanceEnum();
+		void GetVectorFromResults(Vector* vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vector* vector,int dof);
+		/*}}}*/
+};
+#endif  /* _BOOLELEMENTRESULT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/DoubleElementResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/DoubleElementResult.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/DoubleElementResult.cpp	(revision 12878)
@@ -0,0 +1,137 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "./ElementResultLocal.h"
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("DoubleElementResult:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " << this->value);
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+}
+/*}}}*/
+/*FUNCTION DoubleElementResult::Id{{{*/
+int    DoubleElementResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleElementResult::MyRank{{{*/
+int    DoubleElementResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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::ProcessUnits{{{*/
+void DoubleElementResult::ProcessUnits(Parameters* parameters){
+	
+	this->value=UnitConversion(this->value,IuToExtEnum,this->enum_type);
+
+}
+/*}}}*/
+/*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* vector,int* doflist,int* connectivitylist,int numdofs){
+
+	_error_("cannot return vector on vertices");
+} /*}}}*/
+/*FUNCTION DoubleElementResult::GetElementVectorFromResults{{{1*/
+void DoubleElementResult::GetElementVectorFromResults(Vector* vector,int dof){
+
+	vector->SetValue(dof,value,INS_VAL);
+} /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/DoubleElementResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/DoubleElementResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/DoubleElementResult.h	(revision 12878)
@@ -0,0 +1,54 @@
+/*! \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"
+#include "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ElementResult virtual functions definitions: {{{*/
+		ElementResult* SpawnTriaElementResult(int* indices);
+		IssmDouble  GetTime(void){return time;};
+		int     GetStep(void){return step;};
+		void    ProcessUnits(Parameters* parameters);
+		int     NumberOfNodalValues(void);
+		void    PatchFill(int row, Patch* patch);
+		/*}}}*/
+		/*DoubleElementResult management: {{{*/
+		int   InstanceEnum();
+		void GetVectorFromResults(Vector* vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vector* vector,int dof);
+		/*}}}*/
+};
+#endif  /* _DOUBLEELEMENTRESULT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/ElementResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/ElementResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/ElementResult.h	(revision 12878)
@@ -0,0 +1,32 @@
+/*!\file:  ElementResult.h
+ * \brief abstract class for ElementResult object
+ */ 
+
+
+#ifndef _ELEMENTRESULT_H_
+#define _ELEMENTRESULT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../Object.h"
+/*}}}*/
+
+class ElementResult:public Object{
+
+	public: 
+		
+		virtual        ~ElementResult(){};
+		
+		virtual         ElementResult* SpawnTriaElementResult(int* indices)=0;
+		virtual IssmDouble  GetTime(void)=0;
+		virtual int     GetStep(void)=0;
+		virtual void    ProcessUnits(Parameters* parameters)=0;
+		virtual int     NumberOfNodalValues(void)=0;
+		virtual void    PatchFill(int row, Patch* patch)=0;
+		virtual int     InstanceEnum()=0;
+		virtual void    GetVectorFromResults(Vector* vector,int* doflist,int* connectivitylist,int numdof)=0;
+		virtual void    GetElementVectorFromResults(Vector* vector,int dof)=0;
+
+};
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/ElementResultLocal.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/ElementResultLocal.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/ElementResultLocal.h	(revision 12878)
@@ -0,0 +1,11 @@
+/*!\file: ElementResultLocal.h
+ * \brief prototypes for ElementResultLocal.h
+ */ 
+
+#ifndef _ELEMENTRESULTLOCAL_H_
+#define  _ELEMENTRESULTLOCAL_H_
+
+class Parameters;
+
+#endif //ifndef _ELEMENTRESULTLOCAL_H_
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp	(revision 12878)
@@ -0,0 +1,153 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "./ElementResultLocal.h"
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("PentaP1ElementResult:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   values: [" << this->values[0] << " " << this->values[1] << " " << this->values[2] << " " << this->values[3] << " " << this->values[4] << " " << this->values[5] << "]");
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+
+}
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::Id{{{*/
+int    PentaP1ElementResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION PentaP1ElementResult::MyRank{{{*/
+int    PentaP1ElementResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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::ProcessUnits{{{*/
+void PentaP1ElementResult::ProcessUnits(Parameters* parameters){
+	
+	UnitConversion(this->values,6,IuToExtEnum,this->enum_type);
+
+}
+/*}}}*/
+/*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* vector,int* doflist,int* connectivitylist,int numdofs){
+
+	IssmDouble data[6];
+
+	if(numdofs!=6)_error2_("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* vector,int dof){
+
+	_error2_("Result " << EnumToStringx(enum_type) << " is a PentaP1ElementResult and should not write vector of size numberofelemenrs");
+} /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/PentaP1ElementResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/PentaP1ElementResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/PentaP1ElementResult.h	(revision 12878)
@@ -0,0 +1,54 @@
+/*! \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"
+#include "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ElementResult virtual functions definitions: {{{*/
+		ElementResult* SpawnTriaElementResult(int* indices);
+		IssmDouble  GetTime(void){return time;};
+		int     GetStep(void){return step;};
+		void    ProcessUnits(Parameters* parameters);
+		int     NumberOfNodalValues(void);
+		void    PatchFill(int row, Patch* patch);
+		/*}}}*/
+		/*PentaP1ElementResult management: {{{*/
+		int   InstanceEnum();
+		void GetVectorFromResults(Vector* vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vector* vector,int dof);
+		/*}}}*/
+
+};
+#endif  /* _PENTAP1ELEMENTRESULT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp	(revision 12878)
@@ -0,0 +1,140 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "./ElementResultLocal.h"
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+		
+	_printLine_("TriaP1ElementResult:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   values: [" << this->values[0] << " " << this->values[1] << " " << this->values[2] << "]");
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+}
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::Id{{{*/
+int    TriaP1ElementResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION TriaP1ElementResult::MyRank{{{*/
+int    TriaP1ElementResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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::ProcessUnits{{{*/
+void TriaP1ElementResult::ProcessUnits(Parameters* parameters){
+	
+	UnitConversion(this->values,3,IuToExtEnum,this->enum_type);
+
+}
+/*}}}*/
+/*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* vector,int* doflist,int* connectivitylist,int numdofs){
+
+	IssmDouble data[3];
+
+	if(numdofs!=3)_error2_("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* vector,int dof){
+	_error2_("Result " << EnumToStringx(enum_type) << " is a TriaP1ElementResult and should not write vector of size numberofelemenrs");
+} /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/TriaP1ElementResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/TriaP1ElementResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ElementResults/TriaP1ElementResult.h	(revision 12878)
@@ -0,0 +1,53 @@
+/*! \file TriaP1ElementResult.h 
+ *  \brief: header file for TriaP1ElementResult object
+ */
+
+
+#ifndef _TRIAP1ELEMENTRESULT_H_
+#define _TRIAP1ELEMENTRESULT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../Inputs/Input.h"
+#include "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ElementResult virtual functions definitions: {{{*/
+		ElementResult* SpawnTriaElementResult(int* indices);
+		IssmDouble  GetTime(void){return time;};
+		int     GetStep(void){return step;};
+		void    ProcessUnits(Parameters* parameters);
+		int     NumberOfNodalValues(void);
+		void    PatchFill(int row, Patch* patch);
+		/*}}}*/
+		/*TriaP1ElementResult management: {{{*/
+		int   InstanceEnum();
+		void GetVectorFromResults(Vector* vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vector* vector,int dof);
+		/*}}}*/
+
+};
+#endif  /* _TRIAP1ELEMENTRESULT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Element.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Element.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Element.h	(revision 12878)
@@ -0,0 +1,117 @@
+/*!\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 "../Object.h"
+
+class DataSet;
+class Parameters;
+class Patch;
+class Matrix;
+class Vector;
+
+#include "../../../toolkits/toolkits.h"
+/*}}}*/
+
+class Element: public Object,public Update{
+
+	public: 
+		
+		virtual        ~Element(){};
+	
+		virtual void   Configure(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters)=0;
+		virtual void   SetCurrentConfiguration(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters)=0;
+		virtual void   CreateKMatrix(Matrix* Kff, Matrix*  Kfs,Vector* df)=0;
+		virtual void   CreatePVector(Vector* pf)=0;
+		virtual void   CreateJacobianMatrix(Matrix* Jff)=0;
+		virtual void   GetSolutionFromInputs(Vector* solution)=0;
+		virtual int    GetNodeIndex(Node* node)=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* sigma_b)=0;
+		virtual void   ComputeStrainRate(Vector* 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   ProcessResultsUnits(void)=0;
+		virtual void   RequestedOutput(int output_enum,int step,IssmDouble time)=0;
+		
+		virtual int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum,bool process_units)=0;
+		virtual void   InputScale(int enum_type,IssmDouble scale_factor)=0;
+		virtual void   GetVectorFromInputs(Vector* vector, int name_enum)=0;
+		virtual void   GetVectorFromResults(Vector* vector,int id,int enum_in,int interp)=0;
+		virtual void   InputArtificialNoise(int enum_type,IssmDouble min,IssmDouble max)=0;
+		virtual bool   InputConvergence(IssmDouble* eps, int* enums,int num_enums,int* criterionenums,IssmDouble* criterionvalues,int num_criterionenums)=0;
+		virtual void   AverageOntoPartition(Vector* partition_contributions,Vector* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part)=0;
+		virtual int*   GetHorizontalNeighboorSids(void)=0;
+		virtual IssmDouble TimeAdapt()=0;
+		virtual void   MigrateGroundingLine(IssmDouble* old_floating_ice,IssmDouble* sheet_ungrounding)=0;
+		virtual void   PotentialSheetUngrounding(Vector* potential_sheet_ungrounding)=0;
+		virtual void   PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm)=0;
+		virtual void   Delta18oParameterization(void)=0;
+		virtual void   SmbGradients()=0;
+		virtual int    UpdatePotentialSheetUngrounding(IssmDouble* potential_sheet_ungrounding,Vector* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf)=0;
+		virtual void   ResetCoordinateSystem()=0;
+		virtual void   SmearFunction(Vector* smearedvector,IssmDouble (*WeightFunction)(IssmDouble distance,IssmDouble radius),IssmDouble radius)=0;
+
+		#ifdef _HAVE_RESPONSES_
+		virtual void   MinVel(IssmDouble* pminvel, bool process_units)=0;
+		virtual void   MaxVel(IssmDouble* pmaxvel, bool process_units)=0;
+		virtual void   MinVx(IssmDouble* pminvx, bool process_units)=0;
+		virtual void   MaxVx(IssmDouble* pmaxvx, bool process_units)=0;
+		virtual void   MaxAbsVx(IssmDouble* pmaxabsvx, bool process_units)=0;
+		virtual void   MinVy(IssmDouble* pminvy, bool process_units)=0;
+		virtual void   MaxVy(IssmDouble* pmaxvy, bool process_units)=0;
+		virtual void   MaxAbsVy(IssmDouble* pmaxabsvy, bool process_units)=0;
+		virtual void   MinVz(IssmDouble* pminvz, bool process_units)=0;
+		virtual void   MaxVz(IssmDouble* pmaxvz, bool process_units)=0;
+		virtual void   MaxAbsVz(IssmDouble* pmaxabsvz, bool process_units)=0;
+		virtual IssmDouble MassFlux(IssmDouble* segment,bool process_units)=0;
+		virtual void   ElementResponse(IssmDouble* presponse,int response_enum,bool process_units)=0;
+		virtual IssmDouble IceVolume(void)=0;
+		virtual IssmDouble TotalSmb(void)=0;
+		#endif
+
+		#ifdef _HAVE_CONTROL_
+		virtual void   Gradj(Vector* gradient,int control_type,int control_index)=0;
+		virtual IssmDouble ThicknessAbsMisfit(bool process_units  ,int weight_index)=0;
+		virtual IssmDouble SurfaceAbsVelMisfit(bool process_units ,int weight_index)=0;
+		virtual IssmDouble SurfaceRelVelMisfit(bool process_units ,int weight_index)=0;
+		virtual IssmDouble SurfaceLogVelMisfit(bool process_units ,int weight_index)=0;
+		virtual IssmDouble SurfaceLogVxVyMisfit(bool process_units,int weight_index)=0;
+		virtual IssmDouble SurfaceAverageVelMisfit(bool process_units,int weight_index)=0;
+		virtual IssmDouble ThicknessAbsGradient(bool process_units,int weight_index)=0;
+		virtual IssmDouble RheologyBbarAbsGradient(bool process_units,int weight_index)=0;
+		virtual IssmDouble DragCoefficientAbsGradient(bool process_units,int weight_index)=0;
+		virtual void   ControlInputGetGradient(Vector* 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* 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
+};
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Penta.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Penta.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Penta.cpp	(revision 12878)
@@ -0,0 +1,8784 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../../../Container/Container.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES   6
+#define NUMVERTICES2D 3
+
+/*Constructors/destructor/copy*/
+/*FUNCTION Penta::Penta(){{{*/
+Penta::Penta(){
+
+	int i;
+
+	this->nodes=NULL;
+	this->matice=NULL;
+	this->matpar=NULL;
+	this->verticalneighbors=NULL;
+	this->inputs=NULL;
+	this->parameters=NULL;
+	this->results=NULL;
+	for(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)
+	,PentaHook(nummodels,index+1,iomodel) //index+1: matice 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])) penta_elements_ids[1]=this->id; //upper penta is the same penta
+	else                                    penta_elements_ids[1]=(int)(iomodel->Data(MeshUpperelementsEnum)[index]);
+	if (xIsNan<IssmDouble>(iomodel->Data(MeshLowerelementsEnum)[index])) penta_elements_ids[0]=this->id; //lower penta is the same penta
+	else                                    penta_elements_ids[0]=(int)(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]=(int)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->matice=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 PentaHook mother class
+	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->hmatice=(Hook*)this->hmatice->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->matice=(Matice*)penta->hmatice->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::AverageOntoPartition {{{*/
+void  Penta::AverageOntoPartition(Vector* partition_contributions,Vector* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){
+	_error2_("Not supported yet!");
+}
+/*}}}*/
+/*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,ig;
+	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(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* sigma_b){
+
+	int         i,j,ig;
+	int         dofv[3]={0,1,2};
+	int         dofp[1]={3};
+	int         analysis_type,approximation;
+	int         doflist[NUMVERTICES];
+	IssmDouble      xyz_list[NUMVERTICES][3];
+	IssmDouble      xyz_list_tria[3][3];
+	IssmDouble      rho_ice,gravity,stokesreconditioning;
+	IssmDouble      pressure,viscosity,bed,Jdet2d;
+	IssmDouble      bed_normal[3];
+	IssmDouble      basalforce[3];
+	IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble      devstresstensor[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) _error2_("Not supported yet!");
+	if (approximation!=StokesApproximationEnum) _error2_("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], nodes, 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 (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);
+		matice->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* eps){
+
+	_error2_("Not implemented yet");
+
+}
+/*}}}*/
+/*FUNCTION Penta::ComputeStressTensor {{{*/
+void  Penta::ComputeStressTensor(){
+
+	int         iv;
+	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], nodes, 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);
+		matice->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, DataSet* 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];
+
+	/*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->hmatice->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->matice=(Matice*)this->hmatice->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* Kff, Matrix* Kfs,Vector* df){
+
+	/*retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	ElementVector* De=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging {{{*/
+	_assert_(this->nodes && this->matice && 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(); De=CreateDVectorDiagnosticHoriz();
+			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=CreateKMatrixSlope();
+			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
+		default:
+			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+	/*Add to global Vector*/
+	if(De){
+		De->InsertIntoGlobal(df);
+		delete De;
+	}
+}
+/*}}}*/
+/*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->matice; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixSlope {{{*/
+ElementMatrix* Penta::CreateKMatrixSlope(void){
+
+	if (!IsOnBed()) return NULL;
+
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixSlope();
+	delete tria->matice; delete tria;
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVector {{{*/
+void  Penta::CreatePVector(Vector* 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->matice && 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
+		default:
+			_error2_("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->matice; 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->matice; delete tria;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateJacobianMatrix{{{*/
+void  Penta::CreateJacobianMatrix(Matrix* Jff){
+
+	/*retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging {{{*/
+	_assert_(this->nodes && this->matice && 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:
+			_error2_("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){
+
+	int i;
+	
+	_printLine_("Penta:");
+	_printLine_("   id: " << id);
+	nodes[0]->DeepEcho();
+	nodes[1]->DeepEcho();
+	nodes[2]->DeepEcho();
+	nodes[3]->DeepEcho();
+	nodes[4]->DeepEcho();
+	nodes[5]->DeepEcho();
+	matice->DeepEcho();
+	matpar->DeepEcho();
+	_printLine_("   neighbor ids: " << verticalneighbors[0]->Id() << "-" << verticalneighbors[1]->Id());
+	_printLine_("   parameters");
+	parameters->DeepEcho();
+	_printLine_("   inputs");
+	inputs->DeepEcho();
+	_printLine_("   results");
+	results->DeepEcho();
+	_printLine_("neighboor sids: ");
+	_printLine_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2]);
+
+	return;
+}
+/*}}}*/
+/*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){
+
+	IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+	IssmDouble TemperaturesPresentday[NUMVERTICES][12],TemperaturesLgm[NUMVERTICES][12];
+	IssmDouble PrecipitationsPresentday[NUMVERTICES][12];
+	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);
+			monthlyprec[iv][month]=monthlyprec[iv][month]*yts; // convertion to m/yr
+		}
+	}
+
+	/*Recover delta18o and Delta18oSurface at present day, lgm and at time t*/
+	this->parameters->FindParam(&Delta18oPresent,SurfaceforcingsDelta18oEnum,finaltime*yts);
+	this->parameters->FindParam(&Delta18oLgm,SurfaceforcingsDelta18oEnum,(finaltime-21000)*yts);
+	this->parameters->FindParam(&Delta18oTime,SurfaceforcingsDelta18oEnum,time*yts);
+	this->parameters->FindParam(&Delta18oSurfacePresent,SurfaceforcingsDelta18oSurfaceEnum,finaltime*yts);
+	this->parameters->FindParam(&Delta18oSurfaceLgm,SurfaceforcingsDelta18oSurfaceEnum,(finaltime-21000)*yts);
+	this->parameters->FindParam(&Delta18oSurfaceTime,SurfaceforcingsDelta18oSurfaceEnum,time*yts);
+
+	/*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(int iv=0;iv<NUMVERTICES;iv++) {
+			PentaP1Input* newmonthinput1 = new PentaP1Input(SurfaceforcingsMonthlytemperaturesEnum,&monthlytemperatures[iv][imonth]);
+			NewTemperatureInput->AddTimeInput(newmonthinput1,imonth/12.*yts);
+			PentaP1Input* newmonthinput2 = new PentaP1Input(SurfaceforcingsPrecipitationEnum,&monthlyprec[iv][imonth]);
+			NewPrecipitationInput->AddTimeInput(newmonthinput2,imonth/12.*yts);
+		}
+	}
+	this->inputs->AddInput(NewTemperatureInput);
+	this->inputs->AddInput(NewPrecipitationInput);
+
+	/*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,j,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::GetDofList1 {{{*/
+void  Penta::GetDofList1(int* doflist){
+
+	int i;
+	for(i=0;i<6;i++) doflist[i]=nodes[i]->GetDofList1();
+
+}
+/*}}}*/
+/*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],nodes,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;
+	}
+	_error2_("Node provided not found among element nodes");
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetInputListOnVertices(IssmDouble* pvalue,int enumtype) {{{*/
+void Penta::GetInputListOnVertices(IssmDouble* pvalue,int enumtype){
+
+	/*Intermediaries*/
+	IssmDouble     value[NUMVERTICES];
+	GaussPenta *gauss              = NULL;
+
+	/*Recover input*/
+	Input* input=inputs->GetInput(enumtype);
+	if (!input) _error2_("Input " << EnumToStringx(enumtype) << " not found in element");
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	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){
+
+	/*Intermediaries*/
+	IssmDouble     value[NUMVERTICES];
+	GaussPenta *gauss              = NULL;
+
+	/*Recover input*/
+	Input* input=inputs->GetInput(enumtype);
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	if (input){
+		gauss=new GaussPenta();
+		for (int iv=0;iv<NUMVERTICES;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&pvalue[iv],gauss);
+		}
+	}
+	else{
+		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
+	}
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*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) _error2_("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::GetSidList{{{*/
+void  Penta::GetSidList(int* sidlist){
+
+	int i;
+	for(i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->GetSidList();
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputs{{{*/
+void  Penta::GetSolutionFromInputs(Vector* 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);
+		break;
+	#endif
+	#ifdef _HAVE_THERMAL_
+	case ThermalAnalysisEnum:
+		GetSolutionFromInputsThermal(solution);
+		break;
+	case EnthalpyAnalysisEnum:
+		GetSolutionFromInputsEnthalpy(solution);
+		break;
+	#endif
+	default:
+		_error2_("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){
+		_error2_("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){
+		_error2_("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* vector,int input_enum){
+
+	int doflist1[NUMVERTICES];
+
+	/*Get out if this is not an element input*/
+	if (!IsInput(input_enum)) return;
+
+	/*Prepare index list*/
+	this->GetDofList1(&doflist1[0]);
+
+	/*Get input (either in element or material)*/
+	Input* input=inputs->GetInput(input_enum);
+	if(!input) _error2_("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,&doflist1[0]);
+}
+/*}}}*/
+/*FUNCTION Penta::GetVectorFromResults{{{*/
+void  Penta::GetVectorFromResults(Vector* 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 %i is %s, when %s was expected",offset,EnumToStringx(elementresult->InstanceEnum()),EnumToStringx(enum_in));
+	}  
+	if(interp==P1Enum){
+		int doflist1[NUMVERTICES];
+		int connectivity[NUMVERTICES];
+		this->GetSidList(&doflist1[0]);
+		this->GetConnectivityList(&connectivity[0]);
+		elementresult->GetVectorFromResults(vector,&doflist1[0],&connectivity[0],NUMVERTICES);
+	}
+	else if(interp==P0Enum){
+		elementresult->GetElementVectorFromResults(vector,sid);
+	}
+	else{
+		_printLine_("Interpolation " << EnumToStringx(interp) << " not supported");
+	}
+}
+/*}}}*/
+/*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], nodes, 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)_error2_("could not find old input with enum: " << EnumToStringx(enum_type));
+
+	/*ArtificialNoise: */
+	input->ArtificialNoise(min,max);
+}
+/*}}}*/
+/*FUNCTION Penta::InputConvergence{{{*/
+bool Penta::InputConvergence(IssmDouble* eps, int* enums,int num_enums,int* criterionenums,IssmDouble* criterionvalues,int num_criterionenums){
+
+	int i;
+	bool    converged=true;
+	Input** new_inputs=NULL;
+	Input** old_inputs=NULL;
+
+	new_inputs=xNew<Input*>(num_enums/2); //half the enums are for the new inputs
+	old_inputs=xNew<Input*>(num_enums/2); //half the enums are for the old inputs
+
+	for(i=0;i<num_enums/2;i++){
+		new_inputs[i]=(Input*)this->inputs->GetInput(enums[2*i+0]);
+		old_inputs[i]=(Input*)this->inputs->GetInput(enums[2*i+1]);
+		if(!new_inputs[i])_error2_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
+		if(!old_inputs[i])_error2_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
+	}
+
+	/*ok, we've got the inputs (new and old), now loop throught the number of criterions and fill the eps array:*/
+	for(i=0;i<num_criterionenums;i++){
+		IsInputConverged(eps+i,new_inputs,old_inputs,num_enums/2,criterionenums[i]);
+		if(eps[i]>criterionvalues[i]) converged=false; 
+	}
+
+	/*clean up*/
+	xDelete<Input*>(new_inputs);
+	xDelete<Input*>(old_inputs);
+
+	/*Return output*/
+	return converged;
+}
+/*}}}*/
+/*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,(bool)scalar));
+	}
+	else if ((code==6) || (code==2)){ //integer
+		this->inputs->AddInput(new IntInput(name,(int)scalar));
+	}
+	else if ((code==7) || (code==3)){ //IssmDouble
+		this->inputs->AddInput(new DoubleInput(name,(IssmDouble)scalar));
+	}
+	else _error2_("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,j,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]=(int)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];
+
+			/*process units: */
+			UnitConversion(&nodeinputs[0], 6 ,ExtToIuEnum, vector_enum);
+
+			/*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];
+				}
+
+				/*process units: */
+				UnitConversion(&nodeinputs[0], 6 ,ExtToIuEnum, vector_enum);
+
+				/*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 _error2_("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,(bool)vector[index]));
+			}
+			else if (code==6){ //integer
+				this->inputs->AddInput(new IntInput(vector_enum,(int)vector[index]));
+			}
+			else if (code==7){ //IssmDouble
+				this->inputs->AddInput(new DoubleInput(vector_enum,(IssmDouble)vector[index]));
+			}
+			else _error2_("could not recognize nature of vector from code " << code);
+		}
+		else {
+			_error2_("transient elementary inputs not supported yet!");
+		}
+	}
+	else{
+		_error2_("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->matice->inputs->GetInput(enum_type);
+		else
+		 _error2_("object " << EnumToStringx(object_enum) << " not supported yet");
+		if(!original_input) _error2_("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
+			 _error2_("object " << EnumToStringx(original_input->ObjectEnum()) << " not supported yet");
+		}
+
+		/*Step2: Create element thickness input*/
+		GetVerticesCoordinates(&xyz_list[0][0],penta->nodes,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->matice->inputs->AddInput((Input*)depth_averaged_input);
+	else
+	 _error2_("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*)matice->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{
+		_error2_("object of type " << EnumToStringx(object_type) << " not supported yet");
+	}
+	for(i=0;i<num_inputs;i++){
+		if(!base_inputs[i]) _error2_("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->matice->inputs->AddInput((Input*)copy);
+			}
+			else if(object_type==NodeEnum){
+				penta->nodes[i+3]->inputs->AddInput((Input*)copy); //change only the three upper nodes
+			}
+			else{
+				_error2_("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)_error2_("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){
+
+	int    i;
+	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->matice->inputs->GetInput(MaterialsRheologyBEnum);
+	else input=this->inputs->GetInput(enum_type);
+	//if (!input) _error2_("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]=(int)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((int)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:
+					/*Matice will take care of it*/ break;
+				default:
+					_error2_("Control " << EnumToStringx((int)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)==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{
+			_error2_("Approximation type " << EnumToStringx((int)*(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
+	default: 
+		_error2_("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])) _error2_("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 _error2_("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])) _error2_("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])) _error2_("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){
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*Penta update B in InputUpdateFromSolutionThermal, so don't look for B update here.*/
+
+	switch(type){
+
+		case VertexEnum:
+
+			/*New PentaVertexInpu*/
+			IssmDouble values[6];
+
+			/*Get values on the 6 vertices*/
+			for (int i=0;i<6;i++){
+				values[i]=vector[this->nodes[i]->GetVertexDof()];
+			}
+
+			/*update input*/
+			this->inputs->AddInput(new PentaP1Input(name,values));
+			return;
+
+		default:
+
+			_error2_("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){
+	_error2_("not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromVector(bool* vector, int name, int type);{{{*/
+void  Penta::InputUpdateFromVector(bool* vector, int name, int type){
+	_error2_("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==GradientEnum ||
+				name==OldGradientEnum  ||
+				name==ConvergedEnum || 
+				name==QmuVxEnum ||
+				name==QmuVyEnum ||
+				name==QmuPressureEnum ||
+				name==QmuBedEnum ||
+				name==QmuThicknessEnum ||
+				name==QmuSurfaceEnum ||
+				name==QmuTemperatureEnum ||
+				name==QmuMeltingEnum
+				) {
+		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 (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::MigrateGroundingLine{{{*/
+void  Penta::MigrateGroundingLine(IssmDouble* old_floating_ice,IssmDouble* sheet_ungrounding){
+
+	int     i,migration_style,unground;
+	bool    elementonshelf = false;
+	IssmDouble  bed_hydro,yts,gl_melting_rate;
+	IssmDouble  rho_water,rho_ice,density;
+	IssmDouble  melting[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(&yts,ConstantsYtsEnum);
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&s[0],SurfaceEnum);
+	GetInputListOnVertices(&b[0],BedEnum);
+	GetInputListOnVertices(&ba[0],BathymetryEnum);
+	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(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){
+					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 && 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));
+				}
+			}
+		}
+	}
+
+	/*If at least one vertex is now floating, the element is now floating*/
+	for(i=0;i<NUMVERTICES;i++){
+		if(nodes[i]->IsFloating()){
+			elementonshelf=true;
+			break;
+		}
+	}
+	
+   /*Add basal melting rate if element just ungrounded*/
+	if(!this->IsFloating() && elementonshelf==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,elementonshelf));
+
+	/*Extrude inputs*/
+	this->InputExtrude(SurfaceEnum,ElementEnum);
+	this->InputExtrude(BedEnum,ElementEnum);
+	this->InputExtrude(MaskElementonfloatingiceEnum,ElementEnum);
+	this->InputExtrude(MaskVertexonfloatingiceEnum,NodeEnum);
+	this->InputExtrude(MaskVertexongroundediceEnum,NodeEnum);
+}
+/*}}}*/
+/*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::MyRank {{{*/
+int    Penta::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION Penta::NodalValue {{{*/
+int    Penta::NodalValue(IssmDouble* pvalue, int index, int natureofdataenum,bool process_units){
+
+	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==nodes[i]->GetVertexId()){
+			/*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]=nodes[i]->GetVertexId(); //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;
+
+   /*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();
+
+   /*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);
+   }
+
+   /*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::PotentialSheetUngrounding{{{*/
+void  Penta::PotentialSheetUngrounding(Vector* potential_sheet_ungrounding){
+
+	int     i;
+	IssmDouble  h[NUMVERTICES],ba[NUMVERTICES];
+	IssmDouble  bed_hydro;
+	IssmDouble  rho_water,rho_ice,density;
+	bool    elementonshelf = false;
+
+	/*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_sheet_ungrounding->SetValue(nodes[i]->Sid(),1,INS_VAL);
+			}
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::ProcessResultsUnits{{{*/
+void  Penta::ProcessResultsUnits(void){
+
+	int i;
+
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		elementresult->ProcessUnits(this->parameters);
+	}
+}
+/*}}}*/
+/*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){
+
+	_error2_("not implemented yet");
+}
+/*}}}*/
+/*FUNCTION Penta::SetCurrentConfiguration {{{*/
+void  Penta::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, DataSet* 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::SpawnTria {{{*/
+Tria*  Penta::SpawnTria(int g0, int g1, int g2){
+
+	int   i,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<TriaHook*>(tria),&indices[0]);
+
+	/*Spawn matice*/
+	tria->matice=NULL;
+	tria->matice=(Matice*)this->matice->copy();
+	delete tria->matice->inputs;
+	tria->matice->inputs=(Inputs*)this->matice->inputs->SpawnTriaInputs(indices);
+
+	/*recover nodes, matice and matpar: */
+	tria->nodes=(Node**)tria->hnodes[analysis_counter]->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 a_pos[NUMVERTICES];				// Hs-SMB relation parameter 
+	IssmDouble b_pos[NUMVERTICES];				// Hs-SMB relation parameter
+	IssmDouble a_neg[NUMVERTICES];				// Hs-SMB relation parameter
+	IssmDouble b_neg[NUMVERTICES];				// Hs-SMB relation paremeter
+	IssmDouble Hc[NUMVERTICES];					// elevation of transition between accumulation regime and ablation regime
+	IssmDouble smb_pos_max[NUMVERTICES];		// maximum SMB value in the accumulation regime
+	IssmDouble smb_pos_min[NUMVERTICES];		// minimum SMB value in the accumulation regime
+   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(&Hc[0],SurfaceforcingsHcEnum);
+	GetInputListOnVertices(&smb_pos_max[0],SurfaceforcingsSmbPosMaxEnum);
+	GetInputListOnVertices(&smb_pos_min[0],SurfaceforcingsSmbPosMinEnum);
+	GetInputListOnVertices(&a_pos[0],SurfaceforcingsAPosEnum);
+	GetInputListOnVertices(&b_pos[0],SurfaceforcingsBPosEnum);
+	GetInputListOnVertices(&a_neg[0],SurfaceforcingsANegEnum);
+	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(s[i]>Hc[i]){
+	    smb[i]=a_pos[i]+b_pos[i]*s[i];
+		 if(smb[i]>smb_pos_max[i]){smb[i]=smb_pos_max[i];}
+		 if(smb[i]<smb_pos_min[i]){smb[i]=smb_pos_min[i];}
+	  }
+	  else{
+	    smb[i]=a_neg[i]+b_neg[i]*s[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->matice; 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->matice; 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,false);
+	this->MaxAbsVy(&maxabsvy,false);
+	this->MaxAbsVz(&maxabsvz,false);
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], this->nodes, 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*/
+	IssmInt i,j;
+	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]=(int)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+(int)iomodel->Data(MeshElementsEnum)[6*index+i]; //ids for vertices are in the elements array from Matlab
+	}
+
+	/*hooks: */
+	this->SetHookNodes(penta_node_ids,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]/yts*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]/yts*(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]/yts*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]/yts*(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));
+			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 _error2_("temperature and waterfraction required for the enthalpy solution");
+			break;
+
+		default:
+			/*No update for other solution types*/
+			break;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::UpdatePotentialSheetUngrounding{{{*/
+int Penta::UpdatePotentialSheetUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){
+
+	int i;
+	int nflipped=0;
+
+	/*Go through nodes, and whoever is on the potential_sheet_ungrounding, ends up in nodes_on_iceshelf: */
+	for(i=0;i<NUMVERTICES;i++){
+		if (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;
+}
+/*}}}*/
+/*FUNCTION Penta::ViscousHeatingCreateInput {{{*/
+void Penta::ViscousHeatingCreateInput(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries*/
+	int    iv;
+	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], nodes, 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);
+		matice->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;
+}
+/*}}}*/
+/*FUNCTION Penta::SmearFunction {{{*/
+void  Penta::SmearFunction(Vector* smearedvector,IssmDouble (*WeightFunction)(IssmDouble distance,IssmDouble radius),IssmDouble radius){
+	_error2_("not implemented yet");
+}
+/*}}}*/
+
+#ifdef _HAVE_RESPONSES_
+/*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], nodes, 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, bool process_units){
+
+	/*Get minimum:*/
+	IssmDouble minvel=this->inputs->Min(VelEnum);
+
+	/*process units if requested: */
+	if(process_units) minvel=UnitConversion(minvel,IuToExtEnum,VelEnum);
+
+	/*Assign output pointers:*/
+	*pminvel=minvel;
+}
+/*}}}*/
+/*FUNCTION Penta::MinVx{{{*/
+void  Penta::MinVx(IssmDouble* pminvx, bool process_units){
+
+	/*Get minimum:*/
+	IssmDouble minvx=this->inputs->Min(VxEnum);
+
+	/*process units if requested: */
+	if(process_units) minvx=UnitConversion(minvx,IuToExtEnum,VxEnum);
+
+	/*Assign output pointers:*/
+	*pminvx=minvx;
+}
+/*}}}*/
+/*FUNCTION Penta::MinVy{{{*/
+void  Penta::MinVy(IssmDouble* pminvy, bool process_units){
+
+	/*Get minimum:*/
+	IssmDouble minvy=this->inputs->Min(VyEnum);
+
+	/*process units if requested: */
+	if(process_units) minvy=UnitConversion(minvy,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pminvy=minvy;
+}
+/*}}}*/
+/*FUNCTION Penta::MinVz{{{*/
+void  Penta::MinVz(IssmDouble* pminvz, bool process_units){
+
+	/*Get minimum:*/
+	IssmDouble minvz=this->inputs->Min(VzEnum);
+
+	/*process units if requested: */
+	if(process_units) minvz=UnitConversion(minvz,IuToExtEnum,VzEnum);
+
+	/*Assign output pointers:*/
+	*pminvz=minvz;
+}
+/*}}}*/
+/*FUNCTION Penta::MassFlux {{{*/
+IssmDouble Penta::MassFlux( IssmDouble* segment,bool process_units){
+
+	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,process_units);
+	delete tria->matice; 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, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxabsvx=this->inputs->MaxAbs(VxEnum);
+
+	/*process units if requested: */
+	if(process_units) maxabsvx=UnitConversion(maxabsvx,IuToExtEnum,VxEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvx=maxabsvx;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxAbsVy{{{*/
+void  Penta::MaxAbsVy(IssmDouble* pmaxabsvy, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxabsvy=this->inputs->MaxAbs(VyEnum);
+
+	/*process units if requested: */
+	if(process_units) maxabsvy=UnitConversion(maxabsvy,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvy=maxabsvy;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxAbsVz{{{*/
+void  Penta::MaxAbsVz(IssmDouble* pmaxabsvz, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxabsvz=this->inputs->MaxAbs(VzEnum);
+
+	/*process units if requested: */
+	if(process_units) maxabsvz=UnitConversion(maxabsvz,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvz=maxabsvz;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxVel{{{*/
+void  Penta::MaxVel(IssmDouble* pmaxvel, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxvel=this->inputs->Max(VelEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvel=UnitConversion(maxvel,IuToExtEnum,VelEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvel=maxvel;
+
+}
+/*}}}*/
+/*FUNCTION Penta::MaxVx{{{*/
+void  Penta::MaxVx(IssmDouble* pmaxvx, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxvx=this->inputs->Max(VxEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvx=UnitConversion(maxvx,IuToExtEnum,VxEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvx=maxvx;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxVy{{{*/
+void  Penta::MaxVy(IssmDouble* pmaxvy, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxvy=this->inputs->Max(VyEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvy=UnitConversion(maxvy,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvy=maxvy;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxVz{{{*/
+void  Penta::MaxVz(IssmDouble* pmaxvz, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxvz=this->inputs->Max(VzEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvz=UnitConversion(maxvz,IuToExtEnum,VzEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvz=maxvz;
+}
+/*}}}*/
+/*FUNCTION Penta::ElementResponse{{{*/
+void Penta::ElementResponse(IssmDouble* presponse,int response_enum,bool process_units){
+
+	switch(response_enum){
+		case MaterialsRheologyBbarEnum:
+			*presponse=this->matice->GetBbar();
+			break;
+		case VelEnum:
+
+			/*Get input:*/
+			IssmDouble vel;
+			Input* vel_input;
+
+			vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+			vel_input->GetInputAverage(&vel);
+
+			/*process units if requested: */
+			if(process_units) vel=UnitConversion(vel,IuToExtEnum,VelEnum);
+
+			/*Assign output pointers:*/
+			*presponse=vel;
+		default:  
+			_error2_("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], nodes, 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
+	
+	/*Process units: */
+	Total_Smb=UnitConversion(Total_Smb,IuToExtEnum,TotalSmbEnum);// smb on element in GigaTon yr-1
+	
+	/*Return: */
+	return Total_Smb;
+}
+/*}}}*/
+#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,ig,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], nodes, 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 (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(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(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(dt){
+			GetNodalFunctionsP1(&L[0], gauss);
+			D_scalar_trans=gauss->weight*Jdet;
+			D_scalar_trans=D_scalar_trans;
+
+			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(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(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,ig;
+	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], nodes, 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 (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(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->matice; 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,ig,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], nodes, 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 (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(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(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(dt){
+			GetNodalFunctionsP1(&L[0], gauss);
+			D_scalar_trans=gauss->weight*Jdet;
+			D_scalar_trans=D_scalar_trans;
+
+			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(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(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,ig;
+	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], nodes, 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 (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(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,ig,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], nodes, 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(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 (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);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		GetPhi(&phi, &epsilon[0], viscosity);
+
+		scalar_def=phi/rho_ice*Jdet*gauss->weight;
+		if(dt) scalar_def=scalar_def*dt;
+
+		for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_def*L[i];
+
+		/* Build transient now */
+		if(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(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,ig;
+	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], nodes, 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(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(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,ig;
+	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], nodes, 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(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(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,ig,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], nodes, 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 (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 (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);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		GetPhi(&phi, &epsilon[0], viscosity);
+
+		scalar_def=phi/(rho_ice*heatcapacity)*Jdet*gauss->weight;
+		if(dt) scalar_def=scalar_def*dt;
+
+		for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_def*L[i];
+
+		/* Build transient now */
+		if(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(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,ig;
+	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], nodes, 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(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(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,ig;
+	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], nodes, 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(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(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* 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* 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])) _error2_("NaN found in solution vector");
+		//if(values[i]<0)      _printLine_("temperature < 0°K found in solution vector");
+		//if(values[i]>275)    _printLine_("temperature > 275°K found in solution vector (Paterson's rheology associated is negative)");
+	}
+
+	/*Get all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, 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->matice->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),
+							matice->GetN());
+				for(i=0;i<numdof;i++) B[i]=B_average;
+				this->matice->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				break;
+			default:
+				_error2_("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])) _error2_("NaN found in solution vector");
+	}
+
+	/*Get all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, 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) _error2_("Negative water fraction found in solution vector");
+			//if(waterfraction[i]>1) _error2_("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->matice->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),
+							matice->GetN());
+				for(i=0;i<numdof;i++) B[i]=B_average;
+				this->matice->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				break;
+			default:
+				_error2_("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* gradient,int enum_type,int control_index){
+
+	int doflist1[NUMVERTICES];
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		if(!IsOnBed()) return;
+		input=(Input*)matice->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error2_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&doflist1[0],control_index);
+	((ControlInput*)input)->GetGradient(gradient,&doflist1[0]);
+
+}/*}}}*/
+/*FUNCTION Penta::ControlInputScaleGradient{{{*/
+void Penta::ControlInputScaleGradient(int enum_type,IssmDouble scale){
+
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error2_("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    doflist1[NUMVERTICES];
+	IssmDouble grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error2_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&doflist1[0],control_index);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[doflist1[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:
+			_error2_("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 Averaging B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*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->matice; delete tria;
+
+	/*Delete B averaged*/
+	this->matice->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixAdjointPattyn{{{*/
+ElementMatrix* Penta::CreateKMatrixAdjointPattyn(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	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], nodes, 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 (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);
+		matice->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,ig;
+	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     phi[NUMVERTICES];
+	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], nodes, 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 (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);
+		matice->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:
+			_error2_("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->matice; 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->matice; 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->matice; 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->nodes[i]->GetVertexDof() + control_index;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Penta::Gradj {{{*/
+void  Penta::Gradj(Vector* 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:
+					_error2_("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:
+					_error2_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
+
+		default:
+			_error2_("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->matice; 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->matice; delete tria;
+			break;
+		default:
+			_error2_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+	}
+	xDelete<int>(responses);
+}
+/*}}}*/
+/*FUNCTION Penta::GradjDragMacAyeal {{{*/
+void  Penta::GradjDragMacAyeal(Vector* 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->matice; delete tria;
+
+} /*}}}*/
+/*FUNCTION Penta::GradjDragPattyn {{{*/
+void  Penta::GradjDragPattyn(Vector* gradient,int control_index){
+
+	int        i,j,ig;
+	int        analysis_type;
+	int        doflist1[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(&doflist1[0],control_index);
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, 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 (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,doflist1,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+}
+/*}}}*/
+/*FUNCTION Penta::GradjDragStokes {{{*/
+void  Penta::GradjDragStokes(Vector* gradient,int control_index){
+
+	int        i,j,ig;
+	int        analysis_type;
+	int        doflist1[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], nodes, NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	GradientIndexing(&doflist1[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(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,doflist1,grade_g,ADD_VAL);
+
+	delete friction;
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::GradjBbarMacAyeal {{{*/
+void  Penta::GradjBbarMacAyeal(Vector* 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->matice; delete tria;
+
+	/*delete Average B*/
+	this->matice->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+
+} /*}}}*/
+/*FUNCTION Penta::GradjBbarPattyn {{{*/
+void  Penta::GradjBbarPattyn(Vector* 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->matice; delete tria;
+
+	/*delete Average B*/
+	this->matice->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+} /*}}}*/
+/*FUNCTION Penta::GradjBbarStokes {{{*/
+void  Penta::GradjBbarStokes(Vector* 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->matice; delete tria;
+
+	/*delete Average B*/
+	this->matice->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*)matice->inputs->GetInput(MaterialsRheologyBEnum); _assert_(input);
+		}
+		else{
+			input=(Input*)this->inputs->GetInput(control_type[i]); _assert_(input);
+		}
+
+		if (input->ObjectEnum()!=ControlInputEnum) _error2_("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);
+		}
+	}
+
+	/*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])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambday[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambdaz[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambdap[i])) _error2_("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]))       _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambday[i]))       _error2_("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(bool process_units,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(process_units,weight_index);
+		delete tria->matice; 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(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceAbsVelMisfit {{{*/
+IssmDouble Penta::SurfaceAbsVelMisfit(bool process_units,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(process_units,weight_index);
+		delete tria->matice; 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(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceLogVelMisfit {{{*/
+IssmDouble Penta::SurfaceLogVelMisfit(bool process_units,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(process_units,weight_index);
+		delete tria->matice; 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(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceLogVxVyMisfit {{{*/
+IssmDouble Penta::SurfaceLogVxVyMisfit(bool process_units,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(process_units,weight_index);
+		delete tria->matice; 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(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceRelVelMisfit {{{*/
+IssmDouble Penta::SurfaceRelVelMisfit(bool process_units,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(process_units,weight_index);
+		delete tria->matice; 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(process_units,weight_index);
+		delete tria->matice; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::ThicknessAbsGradient{{{*/
+IssmDouble Penta::ThicknessAbsGradient(bool process_units,int weight_index){
+
+	_error2_("Not implemented yet");
+}
+/*}}}*/
+/*FUNCTION Penta::ThicknessAbsMisfit {{{*/
+IssmDouble Penta::ThicknessAbsMisfit(bool process_units,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;
+	_error2_("Not implemented yet");
+
+	tria=(Tria*)SpawnTria(0,1,2);
+	J=tria->ThicknessAbsMisfit(process_units,weight_index);
+	delete tria->matice; delete tria;
+	return J;
+}
+/*}}}*/
+/*FUNCTION Penta::DragCoefficientAbsGradient{{{*/
+IssmDouble Penta::DragCoefficientAbsGradient(bool process_units,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(process_units,weight_index);
+	delete tria->matice; delete tria;
+	return J;
+}
+/*}}}*/
+/*FUNCTION Penta::RheologyBbarAbsGradient{{{*/
+IssmDouble Penta::RheologyBbarAbsGradient(bool process_units,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(process_units,weight_index);
+	delete tria->matice; delete tria;
+	return J;
+}
+/*}}}*/
+/*FUNCTION Penta::GetVectorFromControlInputs{{{*/
+void  Penta::GetVectorFromControlInputs(Vector* vector,int control_enum,int control_index,const char* data){
+
+	int doflist1[NUMVERTICES];
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&doflist1[0],control_index);
+
+	/*Get input (either in element or material)*/
+	Input* input=inputs->GetInput(control_enum);
+	if(!input) _error2_("Input " << EnumToStringx(control_enum) << " not found in element");
+
+	/*Check that it is a ControlInput*/
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error2_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->GetVectorFromInputs(vector,&doflist1[0],data);
+}
+/*}}}*/
+/*FUNCTION Penta::SetControlInputsFromVector{{{*/
+void  Penta::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){
+
+	IssmDouble  values[NUMVERTICES];
+	int     doflist1[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(&doflist1[0],control_index);
+
+	/*Get values on vertices*/
+	for (int i=0;i<NUMVERTICES;i++){
+		values[i]=vector[doflist1[i]];
+	}
+	new_input = new PentaP1Input(control_enum,values);
+
+
+	if(control_enum==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->inputs->GetInput(control_enum); _assert_(input);
+	}
+	else{
+		input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	}
+
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error2_("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->nodes[i]->GetSidList()]; //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:
+			_error2_("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){
+	_error2_("not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromVectorDakota(bool* vector, int name, int type);{{{*/
+void  Penta::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+	_error2_("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->nodes[i]->GetSidList();
+					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:
+			_error2_("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,ig;
+	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], nodes, 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 (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);
+		matice->GetViscosity3d(&viscosity, &epsilon[0]);
+		matice->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->matice; 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,ig,analysis_type;
+	IssmDouble    Jdet2d,slope_magnitude,alpha2;
+	IssmDouble    xyz_list[NUMVERTICES][3];
+	IssmDouble    xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	IssmDouble    slope[3]={0.0,0.0,0.0};
+	IssmDouble    MAXSLOPE=.06; // 6 %
+	IssmDouble    MOUNTAINKEXPONENT=10;
+	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], nodes, 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* 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);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/*Friction: */
+		friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum);
+
+		// If we have a slope > 6% for this element,  it means  we are on a mountain. In this particular case, 
+		//velocity should be = 0. To achieve this result, we set alpha2_list to a very high value: */
+		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+		slope_magnitude=sqrt(pow(slope[0],2)+pow(slope[1],2));
+
+		if (slope_magnitude>MAXSLOPE){
+			alpha2=pow((IssmDouble)10,MOUNTAINKEXPONENT);
+		}
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		GetL(&L[0][0], gauss,NDOF2);
+
+		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,ig;
+	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], nodes, 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 (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);
+		matice->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->matice; 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,ig;
+	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], nodes, 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 (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);
+		matice->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 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:
+			_error2_("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 Averaging B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*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->matice; delete tria;
+
+	/*Delete B averaged*/
+	this->matice->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+
+	/*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,ig,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]; //stiffness matrix evaluated at the gaussian point.
+	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], nodes,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 (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);
+			matice->GetViscosity3d(&viscosity, &epsilon[0]);
+			matice->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);
+			matice->GetViscosity3dStokes(&newviscosity,&epsilons[0]);
+		}
+		else _error2_("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->matice;
+	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->matice; 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::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,ig;
+	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], nodes, 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 (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);
+		matice->GetViscosity3d(&viscosity, &epsilon[0]);
+		matice->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,ig;
+	int       analysis_type;
+	IssmDouble    xyz_list[NUMVERTICES][3];
+	IssmDouble    xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	IssmDouble    slope_magnitude,alpha2,Jdet;
+	IssmDouble    slope[3]={0.0,0.0,0.0};
+	IssmDouble    MAXSLOPE=.06; // 6 %
+	IssmDouble    MOUNTAINKEXPONENT=10;
+	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], nodes, 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* 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);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(0,1,2,2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetTriaJacobianDeterminant(&Jdet, &xyz_list_tria[0][0],gauss);
+		GetL(&L[0][0], gauss,NDOF2);
+
+		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+		friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum); 
+		slope_magnitude=sqrt(pow(slope[0],2)+pow(slope[1],2));
+
+		// If we have a slope > 6% for this element,  it means  we are on a mountain. In this particular case, 
+		//velocity should be = 0. To achieve this result, we set alpha2_list to a very high value: */
+		if (slope_magnitude>MAXSLOPE){
+			alpha2=pow((IssmDouble)10,MOUNTAINKEXPONENT);
+		}
+		
+		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,j,ig,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], nodes, 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 (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);
+		matice->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,ig;
+	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], nodes, 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 (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);
+		matice->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 */
+	int         i,j,ig;
+	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], nodes, NUMVERTICES);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,2);
+	for (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,ig;
+	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], nodes, 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 (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,ig;
+	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], nodes, 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 (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);
+		matice->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,ig;
+	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], nodes, 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(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);
+		matice->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,j,ig;
+	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], nodes, 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 (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);
+		matice->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,ig;
+	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], nodes, 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(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);
+		matice->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 HutterApproximationEnum:
+			return NULL;
+		case NoneApproximationEnum:
+			return NULL;
+		case StokesApproximationEnum:
+			return CreatePVectorDiagnosticStokes();
+		case MacAyealPattynApproximationEnum:
+			return CreatePVectorDiagnosticMacAyealPattyn();
+		case MacAyealStokesApproximationEnum:
+			return CreatePVectorDiagnosticMacAyealStokes();
+		case PattynStokesApproximationEnum:
+			return CreatePVectorDiagnosticPattynStokes();
+		default:
+			_error2_("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){
+
+	/*Constants*/
+	const int numdofs=NDOF2*NUMVERTICES;
+
+	/*Intermediaries*/
+	int          i,j,k,ig;
+	int          node0,node1;
+	int          connectivity[2];
+	IssmDouble       Jdet;
+	IssmDouble       xyz_list[NUMVERTICES][3];
+	IssmDouble       xyz_list_segment[2][3];
+	IssmDouble       z_list[NUMVERTICES];
+	IssmDouble       z_segment[2],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], nodes, NUMVERTICES);
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+	n=matice->GetN();
+	B=matice->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(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->matice; 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,ig;
+	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], nodes, 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 (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,ig;
+	int        approximation;
+	IssmDouble     Jdet,viscosity;
+	IssmDouble     gravity,rho_ice,stokesreconditioning;
+	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 
+	IssmDouble     Ke_gaussian[numdofbubble][3];
+	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], nodes, 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 (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);
+		matice->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+
+		for(i=0;i<NUMVERTICES+1;i++){
+			Pe_gaussian[i*NDOF4+2]+=-rho_ice*gravity*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,ig;
+	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], nodes, 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(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        i,ig;
+	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], nodes, 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 (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 (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,ig;
+	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], nodes, 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(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:
+			_error2_("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 Averaging B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*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->matice; delete tria;
+
+	/*Delete B averaged*/
+	this->matice->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateJacobianDiagnosticPattyn{{{*/
+ElementMatrix* Penta::CreateJacobianDiagnosticPattyn(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	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)*/
+	ElementMatrix* Ke=CreateKMatrixDiagnosticPattyn();
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, 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 (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);
+		matice->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,ig;
+	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     phi[NUMVERTICES];
+	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], nodes, 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 (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);
+		matice->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* 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* 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* 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* 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::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;
+		}
+	}
+	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])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error2_("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->nodes,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], nodes, 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])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error2_("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], nodes, 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]))       _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i]))       _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vzstokes[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(pressure[i])) _error2_("NaN found in solution vector");
+	}
+
+	/*Get Vz*/
+	Input* vzmacayeal_input=inputs->GetInput(VzMacAyealEnum);
+	if (vzmacayeal_input){
+		if (vzmacayeal_input->ObjectEnum()!=PentaP1InputEnum){
+			_error2_("Cannot compute Vel as VzMacAyeal is of type " << EnumToStringx(vzmacayeal_input->ObjectEnum()));
+		}
+		GetInputListOnVertices(&vzmacayeal[0],VzMacAyealEnum);
+	}
+	else{
+		_error2_("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::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], nodes, 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])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error2_("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], nodes, 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]))       _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i]))       _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vzstokes[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(pressure[i])) _error2_("NaN found in solution vector");
+	}
+
+	/*Get Vz*/
+	Input* vzpattyn_input=inputs->GetInput(VzPattynEnum);
+	if (vzpattyn_input){
+		if (vzpattyn_input->ObjectEnum()!=PentaP1InputEnum){
+			_error2_("Cannot compute Vel as VzPattyn is of type " << EnumToStringx(vzpattyn_input->ObjectEnum()));
+		}
+		GetInputListOnVertices(&vzpattyn[0],VzPattynEnum);
+	}
+	else{
+		_error2_("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], nodes, 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])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error2_("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], nodes, 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])) _error2_("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) _error2_("Cannot compute Vel as VzStokes is of type " << EnumToStringx(vzstokes_input->ObjectEnum()));
+			GetInputListOnVertices(&vzstokes[0],VzStokesEnum);
+		}
+		else _error2_("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) _error2_("Cannot compute Vel as VzStokes is of type " << EnumToStringx(vzstokes_input->ObjectEnum()));
+			GetInputListOnVertices(&vzstokes[0],VzStokesEnum);
+		}
+		else _error2_("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]))       _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i]))       _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vz[i]))       _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(pressure[i])) _error2_("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->matice; 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->matice; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+#endif
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Penta.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Penta.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Penta.h	(revision 12878)
@@ -0,0 +1,317 @@
+/*! \file Penta.h 
+ *  \brief: header file for penta object
+ */
+
+#ifndef _PENTA_H_
+#define _PENTA_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Element.h"
+#include "./PentaHook.h"
+#include "./PentaRef.h"
+class  Object;
+class Parameters;
+class Inputs;
+class IoModel;
+class Node;
+class Matice;
+class Matpar;
+class Tria;
+class ElementMatrix;
+class ElementVector;
+
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+/*}}}*/
+
+class Penta: public Element,public PentaHook,public PentaRef{
+
+	public:
+
+		int          id;
+		int          sid;
+
+		Node       **nodes;        // 6 nodes
+		Matice      *matice;       // 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(); 
+		int		  MyRank();
+		/*}}}*/
+		/*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   AverageOntoPartition(Vector* partition_contributions,Vector* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
+		void   BasalFrictionCreateInput(void);
+		void   ComputeBasalStress(Vector* sigma_b);
+		void   ComputeStrainRate(Vector* eps);
+		void   ComputeStressTensor();
+		void   Configure(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters);
+		void   SetCurrentConfiguration(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters);
+		void   CreateKMatrix(Matrix* Kff, Matrix* Kfs,Vector* df);
+		void   CreatePVector(Vector* pf);
+		void   CreateJacobianMatrix(Matrix* Jff);
+		void   Delta18oParameterization(void);
+		void   DeleteResults(void);
+		int    GetNodeIndex(Node* node);
+		void   GetSolutionFromInputs(Vector* solution);
+		IssmDouble GetZcoord(GaussPenta* gauss);
+		void   GetVectorFromInputs(Vector* vector,int name_enum);
+		void   GetVectorFromResults(Vector* vector,int offset,int name_enum,int interp);
+		
+		int    Sid();
+		void   InputArtificialNoise(int enum_type,IssmDouble min, IssmDouble max);
+		bool   InputConvergence(IssmDouble* eps, int* enums,int num_enums,int* criterionenums,IssmDouble* criterionvalues,int num_criterionenums);
+		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   MigrateGroundingLine(IssmDouble* old_floating_ice,IssmDouble* sheet_ungrounding);
+		void   PotentialSheetUngrounding(Vector* potential_sheet_ungrounding);
+		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   ProcessResultsUnits(void);
+		void   ResetCoordinateSystem(void);
+		void   SmbGradients();
+		IssmDouble SurfaceArea(void);
+		void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type);
+		int    UpdatePotentialSheetUngrounding(IssmDouble* potential_sheet_ungrounding,Vector* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf);
+		int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum,bool process_units);
+		IssmDouble TimeAdapt();
+		int*   GetHorizontalNeighboorSids(void);
+		void   ViscousHeatingCreateInput(void);
+		void   SmearFunction(Vector* smearedvector,IssmDouble (*WeightFunction)(IssmDouble distance,IssmDouble radius),IssmDouble radius);
+
+		 #ifdef _HAVE_RESPONSES_
+		IssmDouble IceVolume(void);
+		IssmDouble TotalSmb(void);
+		void   MinVel(IssmDouble* pminvel, bool process_units);
+		void   MinVx(IssmDouble* pminvx, bool process_units);
+		void   MinVy(IssmDouble* pminvy, bool process_units);
+		void   MinVz(IssmDouble* pminvz, bool process_units);
+		IssmDouble MassFlux(IssmDouble* segment,bool process_units);
+		void   MaxAbsVx(IssmDouble* pmaxabsvx, bool process_units);
+		void   MaxAbsVy(IssmDouble* pmaxabsvy, bool process_units);
+		void   MaxAbsVz(IssmDouble* pmaxabsvz, bool process_units);
+		void   MaxVel(IssmDouble* pmaxvel, bool process_units);
+		void   ElementResponse(IssmDouble* presponse,int response_enum,bool process_units);
+		void   MaxVx(IssmDouble* pmaxvx, bool process_units);
+		void   MaxVy(IssmDouble* pmaxvy, bool process_units);
+		void   MaxVz(IssmDouble* pmaxvz, bool process_units);
+		#endif
+
+		#ifdef _HAVE_CONTROL_
+		IssmDouble DragCoefficientAbsGradient(bool process_units,int weight_index);
+		void   GradientIndexing(int* indexing,int control_index);
+		void   Gradj(Vector* gradient,int control_type,int control_index);
+		void   GradjDragMacAyeal(Vector* gradient,int control_index);
+		void   GradjDragPattyn(Vector* gradient,int control_index);
+		void   GradjDragStokes(Vector* gradient,int control_index);
+		void   GradjBbarMacAyeal(Vector* gradient,int control_index);
+		void   GradjBbarPattyn(Vector* gradient,int control_index);
+		void   GradjBbarStokes(Vector* gradient,int control_index);
+		void   GetVectorFromControlInputs(Vector* gradient,int control_enum,int control_index,const char* data);
+		void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
+		void   ControlInputGetGradient(Vector* 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(bool process_units,int weight_index);
+		IssmDouble ThicknessAbsMisfit(     bool process_units,int weight_index);
+		IssmDouble SurfaceAbsVelMisfit(    bool process_units,int weight_index);
+		IssmDouble SurfaceRelVelMisfit(    bool process_units,int weight_index);
+		IssmDouble SurfaceLogVelMisfit(    bool process_units,int weight_index);
+		IssmDouble SurfaceLogVxVyMisfit(   bool process_units,int weight_index);
+		IssmDouble SurfaceAverageVelMisfit(bool process_units,int weight_index);
+		IssmDouble ThicknessAbsGradient(bool process_units,int weight_index);
+		void   InputControlUpdate(IssmDouble scalar,bool save_parameter);
+		#endif
+		/*}}}*/
+		/*Penta specific routines:{{{*/
+		void	  BedNormal(IssmDouble* bed_normal, IssmDouble xyz_list[3][3]);
+		ElementMatrix* CreateKMatrixPrognostic(void);
+		ElementMatrix* CreateKMatrixSlope(void);
+		ElementVector* CreatePVectorPrognostic(void);
+		ElementVector* CreatePVectorSlope(void);
+		void	  GetDofList(int** pdoflist,int approximation_enum,int setenum);
+		void	  GetDofList1(int* doflist);
+		void    GetSidList(int* sidlist);
+		void    GetConnectivityList(int* connectivity);
+		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* 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]);
+
+		#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* 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           InputUpdateFromSolutionDiagnosticPattyn( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticPattynStokes( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticHutter( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticVert( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticStokes( IssmDouble* solutiong);
+		void	         GetSolutionFromInputsDiagnosticHoriz(Vector* solutiong);
+		void	         GetSolutionFromInputsDiagnosticHutter(Vector* solutiong);
+		void	         GetSolutionFromInputsDiagnosticStokes(Vector* solutiong);
+		void	         GetSolutionFromInputsDiagnosticVert(Vector* 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* CreatePVectorDiagnosticPattyn(void);
+		ElementVector* CreatePVectorDiagnosticPattynStokes(void);
+		ElementVector* CreatePVectorDiagnosticStokes(void);
+		ElementVector* CreatePVectorDiagnosticStokesViscous(void);
+		ElementVector* CreatePVectorDiagnosticStokesShelf(void);
+		ElementVector* CreatePVectorDiagnosticVert(void);
+		ElementVector* CreatePVectorDiagnosticVertVolume(void);
+		ElementVector* CreatePVectorDiagnosticVertBase(void);
+		#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_
+		void    CreateHydrologyWaterVelocityInput(void);
+		#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* 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/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaHook.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaHook.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaHook.cpp	(revision 12878)
@@ -0,0 +1,104 @@
+/*!\file PentaHook.c
+ * \brief: implementation of the PentaHook 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 "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION PentaHook::PentaHook(){{{*/
+PentaHook::PentaHook(){
+	numanalyses=UNDEF;
+	this->hnodes=NULL;
+	this->hmatice=NULL;
+	this->hmatpar=NULL;
+	this->hneighbors=NULL;
+}
+/*}}}*/
+/*FUNCTION PentaHook::~PentaHook(){{{*/
+PentaHook::~PentaHook(){
+
+	int i;
+
+	for(i=0;i<this->numanalyses;i++){
+		if (this->hnodes[i]) delete this->hnodes[i];
+	}
+	delete [] this->hnodes;
+	delete hmatice;
+	delete hmatpar;
+	delete hneighbors;
+}
+/*}}}*/
+/*FUNCTION PentaHook::PentaHook(int in_numanalyses,int matice_id, int matpar_id){{{*/
+PentaHook::PentaHook(int in_numanalyses,int matice_id, IoModel* iomodel){
+
+	/*intermediary: */
+	int matpar_id;
+	
+	/*retrieve parameters: */
+	iomodel->Constant(&matpar_id,MeshNumberofelementsEnum); matpar_id++;
+
+	this->numanalyses=in_numanalyses;
+	this->hnodes=new Hook*[in_numanalyses];
+	this->hmatice=new Hook(&matice_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;
+	}
+
+}
+/*}}}*/
+
+/*FUNCTION PentaHook::SetHookNodes{{{*/
+void PentaHook::SetHookNodes(int* node_ids,int analysis_counter){
+	this->hnodes[analysis_counter]= new Hook(node_ids,6);
+
+}
+/*}}}*/
+/*FUNCTION PentaHook::InitHookNeighbors{{{*/
+void PentaHook::InitHookNeighbors(int* element_ids){
+	this->hneighbors=new Hook(element_ids,2);
+
+}
+/*}}}*/
+/*FUNCTION PentaHook::SpawnTriaHook{{{*/
+void PentaHook::SpawnTriaHook(TriaHook* 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 hmatice. matice will be taken care of by Penta
+	triahook->hmatice=NULL;
+	triahook->hmatpar=(Hook*)this->hmatpar->copy();
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaHook.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaHook.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaHook.h	(revision 12878)
@@ -0,0 +1,33 @@
+/*!\file: PentaHook.h
+ * \brief prototypes for PentaHook.h
+ */ 
+
+#ifndef _PENTAHOOK_H_
+#define  _PENTAHOOK_H_
+
+class Hook;
+class TriaHook;
+class IoModel;
+
+class PentaHook{
+
+	public: 
+		int   numanalyses; //number of analysis types
+		Hook** hnodes; // 6 nodes for each analysis type
+		Hook*  hmatice; // 1 ice material
+		Hook*  hmatpar; // 1 material parameter
+		Hook*  hneighbors; // 2 elements, first down, second up
+
+		/*FUNCTION constructors, destructors {{{*/
+		PentaHook();
+		PentaHook(int in_numanalyses,int matice_id, IoModel* iomodel);
+		~PentaHook();
+		void SetHookNodes(int* node_ids,int analysis_counter);
+		void SpawnTriaHook(TriaHook* triahook,int* indices);
+		void InitHookNeighbors(int* element_ids);
+		/*}}}*/
+};
+
+
+#endif //ifndef _PENTAHOOK_H_
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaRef.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaRef.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaRef.cpp	(revision 12878)
@@ -0,0 +1,1267 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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::GetL{{{*/
+void PentaRef::GetL(IssmDouble* L, GaussPenta* gauss, int numdof){
+	/*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: 
+	 **       numdof=1: 
+	 **                 Li=h;
+	 **       numdof=2:
+	 **                 Li=[ h   0 ]
+	 **                    [ 0   h ]
+	 ** where h is the interpolation function for node i.
+	 **
+	 ** We assume L has been allocated already, of size: NUMNODESP1 (numdof=1), or numdofx(numdof*NUMNODESP1) (numdof=2)
+	 **/
+
+	int i;
+	IssmDouble l1l6[6];
+
+	/*Get l1l6 in actual coordinate system: */
+	GetNodalFunctionsP1(l1l6,gauss);
+
+	/*Build L: */
+	if(numdof==1){
+		for (i=0;i<NUMNODESP1;i++){
+			L[i]=l1l6[i]; 
+		}
+	}
+	else{
+		for (i=0;i<NUMNODESP1;i++){
+			*(L+numdof*NUMNODESP1*0+numdof*i)=l1l6[i]; 
+			*(L+numdof*NUMNODESP1*0+numdof*i+1)=0;
+			*(L+numdof*NUMNODESP1*1+numdof*i)=0;
+			*(L+numdof*NUMNODESP1*1+numdof*i+1)=l1l6[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){
+
+	int i,j;
+
+	/*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) _error2_("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) _error2_("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) _error2_("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::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;
+
+	/*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) _error2_("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];
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaRef.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaRef.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/PentaRef.h	(revision 12878)
@@ -0,0 +1,63 @@
+/*!\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 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 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 GetL(IssmDouble* L, GaussPenta* gauss,int numdof);
+		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){_error2_("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){_error2_("only PentaGauss are supported");};
+
+};
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Tria.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Tria.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Tria.cpp	(revision 12878)
@@ -0,0 +1,5729 @@
+/*!\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"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMVERTICES 3
+
+/*Constructors/destructor/copy*/
+/*FUNCTION Tria::Tria(){{{*/
+Tria::Tria(){
+
+	int i;
+
+	this->nodes=NULL;
+	this->matice=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)
+	,TriaHook(nummodels,index+1,iomodel){
+		
+		int i;
+		/*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->matice=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 TriaHook 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->hmatice=(Hook*)this->hmatice->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->matice=(Matice*)tria->hmatice->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::AverageOntoPartition {{{*/
+void  Tria::AverageOntoPartition(Vector* partition_contributions,Vector* 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;
+	IssmDouble    values[3];
+
+	/*First, get the area: */
+	area=this->GetArea();
+
+	/*Figure out the average for this element: */
+	this->GetSidList(&offsetsid[0]);
+	this->GetDofList1(&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::CreateKMatrix {{{*/
+void  Tria::CreateKMatrix(Matrix* Kff, Matrix* Kfs,Vector* df){
+
+	/*retreive parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging mode{{{*/
+	_assert_(this->nodes && this->matice && 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 AdjointHorizAnalysisEnum:
+			Ke=CreateKMatrixAdjointMacAyeal();
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			Ke=CreateKMatrixDiagnosticHutter();
+			break;
+		 #endif
+		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+			Ke=CreateKMatrixSlope();
+			break;
+		case PrognosticAnalysisEnum:
+			Ke=CreateKMatrixPrognostic();
+			break;
+		#ifdef _HAVE_HYDROLOGY_
+		case HydrologyAnalysisEnum:
+			Ke=CreateKMatrixHydrology();
+			break;
+		#endif
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixBalancethickness();
+			break;
+		#endif
+		#ifdef _HAVE_CONTROL_
+		case AdjointBalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixAdjointBalancethickness();
+			break;
+		#endif
+		default:
+			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixMelting {{{*/
+ElementMatrix* Tria::CreateKMatrixMelting(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	IssmDouble     heatcapacity,latentheat;
+	IssmDouble     Jdet,D_scalar;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     L[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], nodes, NUMVERTICES);
+	latentheat=matpar->GetLatentHeat();
+	heatcapacity=matpar->GetHeatCapacity();
+
+	/* Start looping on the number of gauss  (nodes on the bedrock) */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0], gauss);
+
+		D_scalar=latentheat/heatcapacity*gauss->weight*Jdet;
+
+		TripleMultiply(&L[0],numdof,1,0,
+					&D_scalar,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixPrognostic {{{*/
+ElementMatrix* Tria::CreateKMatrixPrognostic(void){
+
+	switch(GetElementType()){
+		case P1Enum:
+			return CreateKMatrixPrognostic_CG();
+		case P1DGEnum:
+			return CreateKMatrixPrognostic_DG();
+		default:
+			_error2_("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        i,j,ig,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     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};
+	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], nodes, 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: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		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( &L[0],1,numdof,1,
+					&DL_scalar,1,1,0,
+					&L[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(pow(vx,2.)+pow(vy,2.))+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        i,j,ig,dim;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     Jdettria,dt,vx,vy;
+	IssmDouble     L[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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		DL_scalar=gauss->weight*Jdettria;
+
+		TripleMultiply( &L[0],1,numdof,1,
+					&DL_scalar,1,1,0,
+					&L[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::CreateKMatrixSlope {{{*/
+ElementMatrix* Tria::CreateKMatrixSlope(void){
+
+	/*constants: */
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/* Intermediaries */
+	int        i,j,ig;
+	IssmDouble     DL_scalar,Jdet;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     L[1][3];
+	GaussTria *gauss = NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	GetVerticesCoordinates(&xyz_list[0][0],nodes,NUMVERTICES);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		DL_scalar=gauss->weight*Jdet;
+
+		GetL(&L[0][0], &xyz_list[0][0], gauss,NDOF1);
+
+		TripleMultiply(&L[0][0],1,3,1,
+					&DL_scalar,1,1,0,
+					&L[0][0],1,3,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVector {{{*/
+void  Tria::CreatePVector(Vector* 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->matice && 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 HydrologyAnalysisEnum:
+			pe=CreatePVectorHydrology();
+			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:
+			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorPrognostic{{{*/
+ElementVector* Tria::CreatePVectorPrognostic(void){
+
+	switch(GetElementType()){
+		case P1Enum:
+			return CreatePVectorPrognostic_CG();
+		case P1DGEnum:
+			return CreatePVectorPrognostic_DG();
+		default:
+			_error2_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorPrognostic_CG {{{*/
+ElementVector* Tria::CreatePVectorPrognostic_CG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	IssmDouble     Jdettria,dt;
+	IssmDouble     surface_mass_balance_g,basal_melting_g,basal_melting_correction_g,thickness_g;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     L[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], nodes, 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(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		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(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))*L[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 */
+	int        i,j,ig;
+	IssmDouble     Jdettria,dt;
+	IssmDouble     surface_mass_balance_g,basal_melting_g,thickness_g;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     L[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], nodes, 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(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		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(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(thickness_g+dt*(surface_mass_balance_g-basal_melting_g))*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorSlope {{{*/
+ElementVector* Tria::CreatePVectorSlope(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+	
+	/*Intermediaries */
+	int        i,j,ig;
+	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], nodes, 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(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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* Jff){
+
+	/*retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging {{{*/
+	_assert_(this->nodes && this->matice && 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:
+			_error2_("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* eps){
+	_error2_("Not Implemented yet");
+}
+/*}}}*/
+/*FUNCTION Tria::ComputeStrainRate {{{*/
+void  Tria::ComputeStrainRate(Vector* eps){
+	_error2_("Not Implemented yet");
+}
+/*}}}*/
+/*FUNCTION Tria::ComputeStressTensor {{{*/
+void  Tria::ComputeStressTensor(){
+
+	int         iv;
+	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], nodes, 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);
+		matice->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 TriaP1Input(StressTensorxxEnum,&sigma_xx[0]));
+	this->inputs->AddInput(new TriaP1Input(StressTensorxyEnum,&sigma_xy[0]));
+	this->inputs->AddInput(new TriaP1Input(StressTensorxzEnum,&sigma_xz[0]));
+	this->inputs->AddInput(new TriaP1Input(StressTensoryyEnum,&sigma_yy[0]));
+	this->inputs->AddInput(new TriaP1Input(StressTensoryzEnum,&sigma_yz[0]));
+	this->inputs->AddInput(new TriaP1Input(StressTensorzzEnum,&sigma_zz[0]));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::Configure {{{*/
+void  Tria::Configure(Elements* elementsin, Loads* loadsin, DataSet* 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];
+
+	/*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->hmatice->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->matice=(Matice*)this->hmatice->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){
+
+	_printLine_("Tria:");
+	_printLine_("   id: " << id);
+	if(nodes){
+		nodes[0]->DeepEcho();
+		nodes[1]->DeepEcho();
+		nodes[2]->DeepEcho();
+	}
+	else _printLine_("nodes = NULL");
+
+	if (matice) matice->DeepEcho();
+	else _printLine_("matice = NULL");
+
+	if (matpar) matpar->DeepEcho();
+	else _printLine_("matpar = NULL");
+
+	_printLine_("   parameters");
+	if (parameters) parameters->DeepEcho();
+	else _printLine_("parameters = NULL");
+
+	_printLine_("   inputs");
+	if (inputs) inputs->DeepEcho();
+	else _printLine_("inputs=NULL");
+
+	if (results) results->DeepEcho();
+	else _printLine_("results=NULL");
+
+	_printLine_("neighboor sids: ");
+	_printLine_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2]);
+	
+	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 temp[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++) temp[i]=TemperaturesPresentday[i][imonth];
+		TriaP1Input* newmonthinput1 = new TriaP1Input(SurfaceforcingsMonthlytemperaturesEnum,&temp[0]);
+		//TriaP1Input* newmonthinput1 = new TriaP1Input(SurfaceforcingsMonthlytemperaturesEnum,&monthlytemperatures[0][imonth]);
+		NewTemperatureInput->AddTimeInput(newmonthinput1,time+imonth/12.*yts);
+		for(i=0;i<NUMVERTICES;i++) temp[i]=monthlyprec[i][imonth];
+		TriaP1Input* newmonthinput2 = new TriaP1Input(SurfaceforcingsPrecipitationEnum,&temp[0]);
+		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){
+	_printLine_("Tria:");
+	_printLine_("   id: " << id);
+	if(nodes){
+		nodes[0]->Echo();
+		nodes[1]->Echo();
+		nodes[2]->Echo();
+	}
+	else _printLine_("nodes = NULL");
+
+	if (matice) matice->Echo();
+	else _printLine_("matice = NULL");
+
+	if (matpar) matpar->Echo();
+	else _printLine_("matpar = NULL");
+
+	_printLine_("   parameters");
+	if (parameters) parameters->Echo();
+	else _printLine_("parameters = NULL");
+
+	_printLine_("   inputs");
+	if (inputs) inputs->Echo();
+	else _printLine_("inputs=NULL");
+
+	if (results) results->Echo();
+	else _printLine_("results=NULL");
+
+	_printLine_("neighboor sids: ");
+	_printLine_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2]);
+}
+/*}}}*/
+/*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], nodes, 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::GetDofList1 {{{*/
+void  Tria::GetDofList1(int* doflist){
+
+	int i;
+	for(i=0;i<3;i++) doflist[i]=nodes[i]->GetDofList1();
+
+}
+/*}}}*/
+/*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::GetNodeIndex {{{*/
+int Tria::GetNodeIndex(Node* node){
+
+	_assert_(nodes);
+	for(int i=0;i<NUMVERTICES;i++){
+		if(node==nodes[i])
+		 return i;
+	}
+	_error2_("Node provided not found among element nodes");
+}
+/*}}}*/
+/*FUNCTION Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype) {{{*/
+void Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype){
+
+	/*Intermediaries*/
+	IssmDouble     value[NUMVERTICES];
+	GaussTria *gauss              = NULL;
+
+	/*Recover input*/
+	Input* input=inputs->GetInput(enumtype);
+	if (!input) _error2_("Input " << EnumToStringx(enumtype) << " not found in element");
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	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){
+
+	IssmDouble     value[NUMVERTICES];
+	GaussTria *gauss = NULL;
+	Input     *input = inputs->GetInput(enumtype);
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	if (input){
+		gauss=new GaussTria();
+		for (int iv=0;iv<NUMVERTICES;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&pvalue[iv],gauss);
+		}
+	}
+	else{
+		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
+	}
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*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){
+
+	IssmDouble     value[NUMVERTICES];
+	GaussTria *gauss = NULL;
+	Input     *input = inputs->GetInput(enumtype);
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	if (input){
+		gauss=new GaussTria();
+		for (int iv=0;iv<NUMVERTICES;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&pvalue[iv],gauss,index);
+		}
+	}
+	else{
+		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
+	}
+
+	/*clean-up*/
+	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) _error2_("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::GetSidList {{{*/
+void  Tria::GetSidList(int* sidlist){
+	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->GetSidList();
+}
+/*}}}*/
+/*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* 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 HydrologyAnalysisEnum:
+		GetSolutionFromInputsHydrology(solution);
+		break;
+	#endif
+	default:
+		_error2_("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){
+		_error2_("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* vector,int input_enum){
+
+	int doflist1[NUMVERTICES];
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(input_enum)) return;
+
+	/*Prepare index list*/
+	this->GetDofList1(&doflist1[0]);
+
+	/*Get input (either in element or material)*/
+	Input* input=inputs->GetInput(input_enum);
+	if(!input) _error2_("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,&doflist1[0]);
+}
+/*}}}*/
+/*FUNCTION Tria::GetVectorFromResults{{{*/
+void  Tria::GetVectorFromResults(Vector* 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 %i is %s, when %s was expected",offset,EnumToStringx(elementresult->InstanceEnum()),EnumToStringx(enum_in));
+	}
+	if(interp==P1Enum){
+		int doflist1[NUMVERTICES];
+		int connectivity[NUMVERTICES];
+		this->GetSidList(&doflist1[0]);
+		this->GetConnectivityList(&connectivity[0]);
+		elementresult->GetVectorFromResults(vector,&doflist1[0],&connectivity[0],NUMVERTICES);
+	}
+	else if(interp==P0Enum){
+		elementresult->GetElementVectorFromResults(vector,sid);
+	}
+	else{
+		_printLine_("Interpolation " << EnumToStringx(interp) << " not supported");
+	}
+}
+/*}}}*/
+/*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)_error2_("could not find old input with enum: " << EnumToStringx(enum_type));
+
+	/*ArtificialNoise: */
+	input->ArtificialNoise(min,max);
+}
+/*}}}*/
+/*FUNCTION Tria::InputConvergence{{{*/
+bool Tria::InputConvergence(IssmDouble* eps, int* enums,int num_enums,int* criterionenums,IssmDouble* criterionvalues,int num_criterionenums){
+
+	bool    converged=true;
+	int     i;
+	Input** new_inputs=NULL;
+	Input** old_inputs=NULL;
+
+	new_inputs=xNew<Input*>(num_enums/2); //half the enums are for the new inputs
+	old_inputs=xNew<Input*>(num_enums/2); //half the enums are for the old inputs
+
+	for(i=0;i<num_enums/2;i++){
+		new_inputs[i]=(Input*)this->inputs->GetInput(enums[2*i+0]);
+		old_inputs[i]=(Input*)this->inputs->GetInput(enums[2*i+1]);
+		if(!new_inputs[i])_error2_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
+		if(!old_inputs[i])_error2_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
+	}
+
+	/*ok, we've got the inputs (new and old), now loop throught the number of criterions and fill the eps array:*/
+	for(i=0;i<num_criterionenums;i++){
+		IsInputConverged(eps+i,new_inputs,old_inputs,num_enums/2,criterionenums[i]);
+		if(eps[i]>criterionvalues[i]) converged=false; 
+	}
+
+	/*clean up and return*/
+	xDelete<Input*>(new_inputs);
+	xDelete<Input*>(old_inputs);
+	return converged;
+}
+/*}}}*/
+/*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->matice->inputs->GetInput(enum_type);
+	else
+	 _error2_("object " << EnumToStringx(object_enum) << " not supported yet");
+	if(!oldinput)_error2_("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->matice->inputs->AddInput((Input*)newinput);
+	else
+	 _error2_("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)_error2_("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){
+
+	int    i;
+	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->matice->inputs->GetInput(enum_type);
+	else input=this->inputs->GetInput(enum_type);
+	//if (!input) _error2_("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((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]/yts;
+						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,TriaP1InputEnum,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]/yts;
+						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,TriaP1InputEnum,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]/yts;
+						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,TriaP1InputEnum,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,TriaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case MaterialsRheologyBbarEnum:
+					/*Matice will take care of it*/ break;
+				default:
+					_error2_("Control " << EnumToStringx((int)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 TriaP1Input(InversionCostFunctionsCoefficientsEnum,nodeinputs));
+		}
+
+		/*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 HydrologyAnalysisEnum:
+			InputUpdateFromSolutionHydrology(solution);
+			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:
+			_error2_("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])) _error2_("NaN found in solution vector");
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new TriaP1Input(enum_type,values));
+
+	/*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])) _error2_("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 _error2_("Hydrostatic adjustment " << hydroadjustment << " (" << EnumToStringx(hydroadjustment) << ") not supported yet");
+		}
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new TriaP1Input(ThicknessEnum,newthickness));
+	this->inputs->AddInput(new TriaP1Input(SurfaceEnum,newsurface));
+	this->inputs->AddInput(new TriaP1Input(BedEnum,newbed));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVector(IssmDouble* vector, int name, int type);{{{*/
+void  Tria::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum: {
+
+			/*New TriaP1Input*/
+			IssmDouble values[3];
+
+			/*Get values on the 3 vertices*/
+			for (int i=0;i<3;i++){
+				values[i]=vector[this->nodes[i]->GetVertexDof()];
+			}
+
+			/*update input*/
+			if (name==MaterialsRheologyBbarEnum || name==MaterialsRheologyBEnum){
+				matice->inputs->AddInput(new TriaP1Input(name,values));
+			}
+			else{
+				this->inputs->AddInput(new TriaP1Input(name,values));
+			}
+			return;
+		}
+		default:
+			_error2_("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){
+	_error2_("not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVector(bool* vector, int name, int type);{{{*/
+void  Tria::InputUpdateFromVector(bool* vector, int name, int type){
+	_error2_("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 _error2_("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];
+
+			/*process units: */
+			UnitConversion(&nodeinputs[0], 3 ,ExtToIuEnum, vector_enum);
+
+			/*create static input: */
+			this->inputs->AddInput(new TriaP1Input(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<3;i++){
+					row=tria_vertex_ids[i]-1;
+					nodeinputs[i]=(IssmDouble)vector[N*row+t];
+				}
+
+				/*process units: */
+				UnitConversion(&nodeinputs[0], 3 ,ExtToIuEnum, vector_enum);
+
+				/*time? :*/
+				time=(IssmDouble)vector[(M-1)*N+t]*yts;
+
+				if(t==0) transientinput=new TransientInput(vector_enum);
+				transientinput->AddTimeInput(new TriaP1Input(vector_enum,nodeinputs),time);
+			}
+			this->inputs->AddInput(transientinput);
+		}
+		else _error2_("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 _error2_("could not recognize nature of vector from code " << code);
+		}
+		else {
+			_error2_("transient elementary inputs not supported yet!");
+		}
+	}
+	else{
+		_error2_("Cannot add input for vector type " << vector_type << " (not supported)");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::IsInput{{{*/
+bool Tria::IsInput(int name){
+	if (
+				name==ThicknessEnum ||
+				name==SurfaceEnum ||
+				name==BedEnum ||
+				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==GradientEnum ||
+				name==OldGradientEnum ||
+				name==QmuVxEnum ||
+				name==QmuVyEnum ||
+				name==QmuPressureEnum ||
+				name==QmuBedEnum ||
+				name==QmuThicknessEnum ||
+				name==QmuSurfaceEnum ||
+				name==QmuTemperatureEnum ||
+				name==QmuMeltingEnum
+		){
+		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::MigrateGroundingLine{{{*/
+void  Tria::MigrateGroundingLine(IssmDouble* old_floating_ice,IssmDouble* sheet_ungrounding){
+
+	int     i,migration_style,unground;
+	bool    elementonshelf = false;
+	IssmDouble  bed_hydro,yts,gl_melting_rate;
+	IssmDouble  rho_water,rho_ice,density;
+	IssmDouble  melting[NUMVERTICES];
+	IssmDouble  h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],ba[NUMVERTICES];
+
+	/*Recover info at the vertices: */
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&yts,ConstantsYtsEnum);
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&s[0],SurfaceEnum);
+	GetInputListOnVertices(&b[0],BedEnum);
+	GetInputListOnVertices(&ba[0],BathymetryEnum);
+	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){
+					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));
+				}
+			}
+		}
+	}
+
+	/*If at least one vertex is now floating, the element is now floating*/
+	for(i=0;i<NUMVERTICES;i++){
+		if(nodes[i]->IsFloating()){
+			elementonshelf=true;
+			break;
+		}
+	}
+	
+   /*Add basal melting rate if element just ungrounded*/
+	if(!this->IsFloating() && elementonshelf==true){
+		for(i=0;i<NUMVERTICES;i++)melting[i]=gl_melting_rate/yts;
+		this->inputs->AddInput(new TriaP1Input(BasalforcingsMeltingRateEnum,&melting[0]));
+	} 
+
+	/*Update inputs*/
+   this->inputs->AddInput(new BoolInput(MaskElementonfloatingiceEnum,elementonshelf));
+
+	/*Update inputs*/    
+	this->inputs->AddInput(new TriaP1Input(SurfaceEnum,&s[0]));
+	this->inputs->AddInput(new TriaP1Input(BedEnum,&b[0]));
+}
+/*}}}*/
+/*FUNCTION Tria::MyRank {{{*/
+int    Tria::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION Tria::NodalValue {{{*/
+int    Tria::NodalValue(IssmDouble* pvalue, int index, int natureofdataenum,bool process_units){
+
+	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==nodes[i]->GetVertexId()){
+			/*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]=nodes[i]->GetVertexId(); //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::PotentialSheetUngrounding{{{*/
+void  Tria::PotentialSheetUngrounding(Vector* potential_sheet_ungrounding){
+
+	int     i;
+	IssmDouble  h[NUMVERTICES],ba[NUMVERTICES];
+	IssmDouble  bed_hydro;
+	IssmDouble  rho_water,rho_ice,density;
+	bool    elementonshelf = false;
+
+	/*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_sheet_ungrounding->SetValue(nodes[i]->Sid(),1,INS_VAL);
+			}
+		}
+	}
+}
+/*}}}*/
+/*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;
+
+   /*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();
+
+  //if(id==1) printf(" monthlytemperatures %f\n",monthlytemperatures[1][0]);
+  //if(id==1) printf("monthlyprec %f\n",monthlyprec[1][0]);
+
+   /*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);
+   }
+
+   /*Update inputs*/    
+   this->inputs->AddInput(new TriaP1Input(SurfaceforcingsMassBalanceEnum,&agd[0]));
+   // this->inputs->AddInput(new TriaVertexInput(ThermalSpcTemperatureEnum,&Tsurf[0]));
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::ProcessResultsUnits{{{*/
+void  Tria::ProcessResultsUnits(void){
+
+	int i;
+
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		elementresult->ProcessUnits(this->parameters);
+	}
+}
+/*}}}*/
+/*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){
+
+	_error2_("not implemented yet");
+}
+/*}}}*/
+/*FUNCTION Tria::SmearFunction {{{*/
+void  Tria::SmearFunction(Vector*  smearedvector,IssmDouble (*WeightFunction)(IssmDouble distance,IssmDouble radius),IssmDouble radius){
+	_error2_("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 a_pos[NUMVERTICES];				// Hs-SMB relation parameter 
+	IssmDouble b_pos[NUMVERTICES];				// Hs-SMB relation parameter
+	IssmDouble a_neg[NUMVERTICES];				// Hs-SMB relation parameter
+	IssmDouble b_neg[NUMVERTICES];				// Hs-SMB relation paremeter
+	IssmDouble Hc[NUMVERTICES];					// elevation of transition between accumulation regime and ablation regime
+	IssmDouble smb_pos_max[NUMVERTICES];		// maximum SMB value in the accumulation regime
+	IssmDouble smb_pos_min[NUMVERTICES];		// minimum SMB value in the accumulation regime
+   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(&Hc[0],SurfaceforcingsHcEnum);
+	GetInputListOnVertices(&smb_pos_max[0],SurfaceforcingsSmbPosMaxEnum);
+	GetInputListOnVertices(&smb_pos_min[0],SurfaceforcingsSmbPosMinEnum);
+	GetInputListOnVertices(&a_pos[0],SurfaceforcingsAPosEnum);
+	GetInputListOnVertices(&b_pos[0],SurfaceforcingsBPosEnum);
+	GetInputListOnVertices(&a_neg[0],SurfaceforcingsANegEnum);
+	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(s[i]>Hc[i]){
+	    smb[i]=a_pos[i]+b_pos[i]*s[i];
+		 if(smb[i]>smb_pos_max[i]){smb[i]=smb_pos_max[i];}
+		 if(smb[i]<smb_pos_min[i]){smb[i]=smb_pos_min[i];}
+	  }
+	  else{
+	    smb[i]=a_neg[i]+b_neg[i]*s[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 TriaP1Input(SurfaceforcingsMassBalanceEnum,&smb[0]));
+}
+/*}}}*/
+/*FUNCTION Tria::SetCurrentConfiguration {{{*/
+void  Tria::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, DataSet* 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){
+
+	int    i;
+	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], nodes, NUMVERTICES);
+
+	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];
+
+	S = 0.5 * sqrt(pow(normal[0],(IssmDouble)2)+pow(normal[1],(IssmDouble)2)+pow(normal[2],(IssmDouble)2));
+
+	/*Return: */
+	return S;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceNormal{{{*/
+void Tria::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],(IssmDouble)2)+pow(normal[1],(IssmDouble)2)+pow(normal[2],(IssmDouble)2) );
+
+	*(surface_normal)=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,false);
+	this->MaxAbsVy(&maxabsvy,false);
+	#else
+		_error2_("ISSM was not compiled with responses compiled in, exiting!");
+	#endif
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], this->nodes, 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,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 TriaP1Input(VxEnum,nodeinputs));
+				if(dakota_analysis) this->inputs->AddInput(new TriaP1Input(QmuVxEnum,nodeinputs));
+			}
+			if(!iomodel->Data(VyEnum)){
+				for(i=0;i<3;i++)nodeinputs[i]=0;
+				this->inputs->AddInput(new TriaP1Input(VyEnum,nodeinputs));
+				if(dakota_analysis) this->inputs->AddInput(new TriaP1Input(QmuVyEnum,nodeinputs));
+			}
+			if(!iomodel->Data(VzEnum)){
+				for(i=0;i<3;i++)nodeinputs[i]=0;
+				this->inputs->AddInput(new TriaP1Input(VzEnum,nodeinputs));
+				if(dakota_analysis) this->inputs->AddInput(new TriaP1Input(QmuVzEnum,nodeinputs));
+			}
+			if(!iomodel->Data(PressureEnum)){
+				for(i=0;i<3;i++)nodeinputs[i]=0;
+				if(dakota_analysis){
+					this->inputs->AddInput(new TriaP1Input(PressureEnum,nodeinputs));
+					this->inputs->AddInput(new TriaP1Input(QmuPressureEnum,nodeinputs));
+				}
+			}
+			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::UpdatePotentialSheetUngrounding{{{*/
+int Tria::UpdatePotentialSheetUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){
+
+	int i;
+	int nflipped=0;
+
+	/*Go through nodes, and whoever is on the potential_sheet_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;
+}
+/*}}}*/
+
+#ifdef _HAVE_RESPONSES_
+/*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], nodes, 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,bool process_units){
+
+	const int    numdofs=2;
+
+	int        i,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 ((int)*(segment+4)!=this->id)_error2_("error message: segment with id " << (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], nodes, 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.0)+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]
+				);
+
+	/*Process units: */
+	mass_flux=UnitConversion(mass_flux,IuToExtEnum,MassFluxEnum);
+
+	/*clean up and return:*/
+	delete gauss_1;
+	delete gauss_2;
+	return mass_flux;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxAbsVx{{{*/
+void  Tria::MaxAbsVx(IssmDouble* pmaxabsvx, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxabsvx=this->inputs->MaxAbs(VxEnum);
+
+	/*process units if requested: */
+	if(process_units) maxabsvx=UnitConversion(maxabsvx,IuToExtEnum,VxEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvx=maxabsvx;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxAbsVy{{{*/
+void  Tria::MaxAbsVy(IssmDouble* pmaxabsvy, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxabsvy=this->inputs->MaxAbs(VyEnum);
+
+	/*process units if requested: */
+	if(process_units) maxabsvy=UnitConversion(maxabsvy,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvy=maxabsvy;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxAbsVz{{{*/
+void  Tria::MaxAbsVz(IssmDouble* pmaxabsvz, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxabsvz=this->inputs->MaxAbs(VzEnum);
+
+	/*process units if requested: */
+	if(process_units) maxabsvz=UnitConversion(maxabsvz,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxabsvz=maxabsvz;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxVel{{{*/
+void  Tria::MaxVel(IssmDouble* pmaxvel, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxvel=this->inputs->Max(VelEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvel=UnitConversion(maxvel,IuToExtEnum,VelEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvel=maxvel;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxVx{{{*/
+void  Tria::MaxVx(IssmDouble* pmaxvx, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxvx=this->inputs->Max(VxEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvx=UnitConversion(maxvx,IuToExtEnum,VxEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvx=maxvx;
+}
+/*}}}*/
+/*FUNCTION Tria::MaxVy{{{*/
+void  Tria::MaxVy(IssmDouble* pmaxvy, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxvy=this->inputs->Max(VyEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvy=UnitConversion(maxvy,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvy=maxvy;
+
+}
+/*}}}*/
+/*FUNCTION Tria::MaxVz{{{*/
+void  Tria::MaxVz(IssmDouble* pmaxvz, bool process_units){
+
+	/*Get maximum:*/
+	IssmDouble maxvz=this->inputs->Max(VzEnum);
+
+	/*process units if requested: */
+	if(process_units) maxvz=UnitConversion(maxvz,IuToExtEnum,VzEnum);
+
+	/*Assign output pointers:*/
+	*pmaxvz=maxvz;
+}
+/*}}}*/
+/*FUNCTION Tria::MinVel{{{*/
+void  Tria::MinVel(IssmDouble* pminvel, bool process_units){
+
+	/*Get minimum:*/
+	IssmDouble minvel=this->inputs->Min(VelEnum);
+
+	/*process units if requested: */
+	if(process_units) minvel=UnitConversion(minvel,IuToExtEnum,VelEnum);
+
+	/*Assign output pointers:*/
+	*pminvel=minvel;
+}
+/*}}}*/
+/*FUNCTION Tria::MinVx{{{*/
+void  Tria::MinVx(IssmDouble* pminvx, bool process_units){
+
+	/*Get minimum:*/
+	IssmDouble minvx=this->inputs->Min(VxEnum);
+
+	/*process units if requested: */
+	if(process_units) minvx=UnitConversion(minvx,IuToExtEnum,VxEnum);
+
+	/*Assign output pointers:*/
+	*pminvx=minvx;
+}
+/*}}}*/
+/*FUNCTION Tria::MinVy{{{*/
+void  Tria::MinVy(IssmDouble* pminvy, bool process_units){
+
+	/*Get minimum:*/
+	IssmDouble minvy=this->inputs->Min(VyEnum);
+
+	/*process units if requested: */
+	if(process_units) minvy=UnitConversion(minvy,IuToExtEnum,VyEnum);
+
+	/*Assign output pointers:*/
+	*pminvy=minvy;
+}
+/*}}}*/
+/*FUNCTION Tria::MinVz{{{*/
+void  Tria::MinVz(IssmDouble* pminvz, bool process_units){
+
+	/*Get minimum:*/
+	IssmDouble minvz=this->inputs->Min(VzEnum);
+
+	/*process units if requested: */
+	if(process_units) minvz=UnitConversion(minvz,IuToExtEnum,VzEnum);
+
+	/*Assign output pointers:*/
+	*pminvz=minvz;
+}
+/*}}}*/
+/*FUNCTION Tria::ElementResponse{{{*/
+void Tria::ElementResponse(IssmDouble* presponse,int response_enum,bool process_units){
+
+	switch(response_enum){
+		case MaterialsRheologyBbarEnum:
+			*presponse=this->matice->GetBbar();
+			break;
+		case VelEnum:
+
+			/*Get input:*/
+			IssmDouble vel;
+			Input* vel_input;
+
+			vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+			vel_input->GetInputAverage(&vel);
+
+			/*process units if requested: */
+			if(process_units) vel=UnitConversion(vel,IuToExtEnum,VelEnum);
+
+			/*Assign output pointers:*/
+			*presponse=vel;
+		default:  
+			_error2_("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], nodes, 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
+	
+	/*Process units: */
+	Total_Smb=UnitConversion(Total_Smb,IuToExtEnum,TotalSmbEnum);																// smb on element in GigaTon yr-1
+	
+	/*Return: */
+	return Total_Smb;
+}
+/*}}}*/
+#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){
+
+	/*Constants*/
+	const int  numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries*/
+	int        i,j,ig;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     viscosity,newviscosity,oldviscosity;
+	IssmDouble     viscosity_overshoot,thickness,Jdet;
+	IssmDouble     epsilon[3],oldepsilon[3];    /* epsilon=[exx,eyy,exy];    */
+	IssmDouble     B[3][numdof];
+	IssmDouble     Bprime[3][numdof];
+	IssmDouble     D[3][3]   = {0.0};
+	IssmDouble     D_scalar;
+	GaussTria *gauss = NULL;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, 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: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		GetBMacAyeal(&B[0][0], &xyz_list[0][0], gauss);
+		GetBprimeMacAyeal(&Bprime[0][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);
+		matice->GetViscosity2d(&viscosity, &epsilon[0]);
+		matice->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][i]=D_scalar;
+
+		TripleMultiply(&B[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixDiagnosticMacAyealFriction {{{*/
+ElementMatrix* Tria::CreateKMatrixDiagnosticMacAyealFriction(void){
+
+	/*Constants*/
+	const int  numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries*/
+	int        i,j,ig;
+	int        analysis_type;
+	IssmDouble     MAXSLOPE  = .06; // 6 %
+	IssmDouble     MOUNTAINKEXPONENT = 10;
+	IssmDouble     slope_magnitude,alpha2;
+	IssmDouble     Jdet;
+	IssmDouble     L[2][numdof];
+	IssmDouble     DL[2][2]  = {{ 0,0 },{0,0}};
+	IssmDouble     DL_scalar;
+	IssmDouble     slope[2]  = {0.0,0.0};
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	Friction  *friction = NULL;
+	GaussTria *gauss    = NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	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);
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*build friction object, used later on: */
+	friction=new Friction("2d",inputs,matpar,analysis_type);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		// If we have a slope > 6% for this element,  it means  we are on a mountain. In this particular case, 
+		//velocity should be = 0. To achieve this result, we set alpha2_list to a very high value: */
+		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
+		slope_magnitude=sqrt(pow(slope[0],2)+pow(slope[1],2));
+		if(slope_magnitude>MAXSLOPE) alpha2=pow((IssmDouble)10,MOUNTAINKEXPONENT);
+		else friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum);
+
+		GetL(&L[0][0], &xyz_list[0][0], gauss,NDOF2);
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		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 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(){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int            i,j,ig;
+	IssmDouble         driving_stress_baseline,thickness;
+	IssmDouble         Jdet;
+	IssmDouble         xyz_list[NUMVERTICES][3];
+	IssmDouble         slope[2];
+	IssmDouble         basis[3];
+	IssmDouble         pe_g_gaussian[numdof];
+	GaussTria*     gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, 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: */
+	gauss=new GaussTria(2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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 pe_g_gaussian vector: */
+		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 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=matice->GetN();
+	B=matice->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){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	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     phi[NUMVERTICES];
+	IssmDouble     dphi[2][NUMVERTICES];
+	GaussTria *gauss=NULL;
+
+	/*Initialize Jacobian with regular MacAyeal (first part of the Gateau derivative)*/
+	ElementMatrix* Ke=CreateKMatrixDiagnosticMacAyeal();
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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);
+		matice->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;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::GetSolutionFromInputsDiagnosticHoriz{{{*/
+void  Tria::GetSolutionFromInputsDiagnosticHoriz(Vector* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	IssmDouble       vx,vy;
+	IssmDouble       values[numdof];
+	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::GetSolutionFromInputsDiagnosticHutter{{{*/
+void  Tria::GetSolutionFromInputsDiagnosticHutter(Vector* 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){
+	
+	const int numdof=NDOF2*NUMVERTICES;
+
+	int       i;
+	int*      doflist=NULL;
+	IssmDouble    rho_ice,g;
+	IssmDouble    values[numdof];
+	IssmDouble    vx[NUMVERTICES];
+	IssmDouble    vy[NUMVERTICES];
+	IssmDouble    vz[NUMVERTICES];
+	IssmDouble    vel[NUMVERTICES];
+	IssmDouble    pressure[NUMVERTICES];
+	IssmDouble    thickness[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]];
+
+	/*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])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error2_("NaN found in solution vector");
+	}
+
+	/*Get Vz and compute vel*/
+	GetInputListOnVertices(&vz[0],VzEnum,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 2D, 
+	 *so the pressure is just the pressure at the bedrock: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	GetInputListOnVertices(&thickness[0],ThicknessEnum);
+	for(i=0;i<NUMVERTICES;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 TriaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new TriaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new TriaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new TriaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionDiagnosticHutter {{{*/
+void  Tria::InputUpdateFromSolutionDiagnosticHutter(IssmDouble* solution){
+	
+	const int numdof=NDOF2*NUMVERTICES;
+	
+	int       i;
+	int*      doflist=NULL;
+	IssmDouble    rho_ice,g;
+	IssmDouble    values[numdof];
+	IssmDouble    vx[NUMVERTICES];
+	IssmDouble    vy[NUMVERTICES];
+	IssmDouble    vz[NUMVERTICES];
+	IssmDouble    vel[NUMVERTICES];
+	IssmDouble    pressure[NUMVERTICES];
+	IssmDouble    thickness[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++){
+		vx[i]=values[i*NDOF2+0];
+		vy[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error2_("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 2D, 
+	 *so the pressure is just the pressure at the bedrock: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	GetInputListOnVertices(&thickness[0],ThicknessEnum);
+	for(i=0;i<NUMVERTICES;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 TriaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new TriaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new TriaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new TriaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_CONTROL_
+/*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){
+			input=(Input*)matice->inputs->GetInput(control_type[i]); _assert_(input);
+		}
+		else{
+			input=(Input*)this->inputs->GetInput(control_type[i]);   _assert_(input);
+		}
+
+		if (input->ObjectEnum()!=ControlInputEnum){
+			_error2_("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* gradient,int enum_type,int control_index){
+
+	int doflist1[NUMVERTICES];
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->inputs->GetInput(enum_type);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error2_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&doflist1[0],control_index);
+	((ControlInput*)input)->GetGradient(gradient,&doflist1[0]);
+
+}/*}}}*/
+/*FUNCTION Tria::ControlInputScaleGradient{{{*/
+void Tria::ControlInputScaleGradient(int enum_type,IssmDouble scale){
+
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->inputs->GetInput(enum_type);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error2_("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    doflist1[NUMVERTICES];
+	IssmDouble grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->inputs->GetInput(enum_type);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error2_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error2_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&doflist1[0],control_index);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[doflist1[i]];
+	grad_input=new TriaP1Input(GradientEnum,grad_list);
+
+	((ControlInput*)input)->SetGradient(grad_input);
+
+}/*}}}*/
+/*FUNCTION Tria::Gradj {{{*/
+void  Tria::Gradj(Vector* 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 BalancethicknessThickeningRateEnum:
+			GradjDhDtBalancedthickness(gradient,control_index);
+			break;
+		case VxEnum:
+			GradjVxBalancedthickness(gradient,control_index);
+			break;
+		case VyEnum:
+			GradjVyBalancedthickness(gradient,control_index);
+			break;
+		default:
+			_error2_("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 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:
+			_error2_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+	}
+
+	xDelete<int>(responses);
+}
+/*}}}*/
+/*FUNCTION Tria::GradjBGradient{{{*/
+void  Tria::GradjBGradient(Vector* gradient,int weight_index,int control_index){
+
+	int        i,ig;
+	int        doflist1[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], nodes, NUMVERTICES);
+	GradientIndexing(&doflist1[0],control_index);
+	Input* rheologyb_input=matice->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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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,doflist1,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjBMacAyeal{{{*/
+void  Tria::GradjBMacAyeal(Vector* gradient,int control_index){
+
+	/*Intermediaries*/
+	int        i,ig;
+	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], nodes, 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=matice->inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(4);
+	for (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);
+		matice->GetViscosityComplement(&viscosity_complement,&epsilon[0]);
+
+		GetJacobianDeterminant2d(&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* gradient,int control_index){
+
+	int        i,ig;
+	int        analysis_type;
+	int        doflist1[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], nodes, NUMVERTICES);
+	GradientIndexing(&doflist1[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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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,doflist1,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjDragGradient{{{*/
+void  Tria::GradjDragGradient(Vector* gradient, int weight_index,int control_index){
+
+	int        i,ig;
+	int        doflist1[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], nodes, NUMVERTICES);
+	GradientIndexing(&doflist1[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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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,doflist1,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjDhDtBalancedthickness{{{*/
+void  Tria::GradjDhDtBalancedthickness(Vector* gradient,int control_index){
+
+	/*Intermediaries*/
+	int    doflist1[NUMVERTICES];
+	IssmDouble lambda[NUMVERTICES];
+	IssmDouble gradient_g[NUMVERTICES];
+
+	/*Compute Gradient*/
+	GradientIndexing(&doflist1[0],control_index);
+	GetInputListOnVertices(&lambda[0],AdjointEnum);
+	for(int i=0;i<NUMVERTICES;i++) gradient_g[i]=-lambda[i];
+
+	gradient->SetValues(NUMVERTICES,doflist1,gradient_g,INS_VAL);
+}
+/*}}}*/
+/*FUNCTION Tria::GradjVxBalancedthickness{{{*/
+void  Tria::GradjVxBalancedthickness(Vector* gradient,int control_index){
+
+	/*Intermediaries*/
+	int        i,ig;
+	int        doflist1[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], nodes, NUMVERTICES);
+	GradientIndexing(&doflist1[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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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,doflist1,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjVyBalancedthickness{{{*/
+void  Tria::GradjVyBalancedthickness(Vector* gradient,int control_index){
+
+	/*Intermediaries*/
+	int        i,ig;
+	int        doflist1[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], nodes, NUMVERTICES);
+	GradientIndexing(&doflist1[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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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,doflist1,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*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->nodes[i]->GetVertexDof() + control_index;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::RheologyBbarAbsGradient{{{*/
+IssmDouble Tria::RheologyBbarAbsGradient(bool process_units,int weight_index){
+
+	/* Intermediaries */
+	int        ig;
+	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], nodes, NUMVERTICES);
+	Input* weights_input  =inputs->GetInput(InversionCostFunctionsCoefficientsEnum);              _assert_(weights_input);
+	Input* rheologyb_input=matice->inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&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(bool process_units,int weight_index){
+
+	const int    numdof=2*NUMVERTICES;
+
+	int        i,ig;
+	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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&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*pow( pow(vx-vxobs,2.) + pow(vy-vyobs,2.) ,0.5);
+
+		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceAverageVelMisfitEnum);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean-up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceLogVelMisfit {{{*/
+IssmDouble Tria::SurfaceLogVelMisfit(bool process_units,int weight_index){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int        i,ig;
+	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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&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:
+		 *                 [        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.);
+
+		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceLogVelMisfitEnum);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean-up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceLogVxVyMisfit {{{*/
+IssmDouble Tria::SurfaceLogVxVyMisfit(bool process_units,int weight_index){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int        i,ig;
+	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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&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.) );
+
+		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceLogVxVyMisfitEnum);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean-up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceAbsVelMisfit {{{*/
+IssmDouble Tria::SurfaceAbsVelMisfit(bool process_units,int weight_index){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int        i,ig;
+	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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&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.) );
+
+		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceAverageVelMisfitEnum);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceRelVelMisfit {{{*/
+IssmDouble Tria::SurfaceRelVelMisfit(bool process_units,int weight_index){
+	const int  numdof=2*NUMVERTICES;
+
+	int        i,ig;
+	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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&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.));
+		if(process_units)UnitConversion(misfit,IuToExtEnum,SurfaceRelVelMisfitEnum);
+
+		/*Add to cost function*/
+		Jelem+=misfit*weight*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::ThicknessAbsGradient{{{*/
+IssmDouble Tria::ThicknessAbsGradient(bool process_units,int weight_index){
+
+	/* Intermediaries */
+	int        ig;
+	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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&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*(pow(dp[0],2.)+pow(dp[1],2.))*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::ThicknessAbsMisfit {{{*/
+IssmDouble Tria::ThicknessAbsMisfit(bool process_units,int weight_index){
+
+	/*Intermediaries*/
+	int        i,ig;
+	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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&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*pow(thickness-thicknessobs,2.0)*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,ig,resp;
+	IssmDouble      Jdet;
+	IssmDouble      thickness,thicknessobs,weight;
+	int        *responses = NULL;
+	int         num_responses;
+	IssmDouble      xyz_list[NUMVERTICES][3];
+	IssmDouble      basis[3];
+	IssmDouble      dbasis[NDOF2][NUMVERTICES];
+	IssmDouble      dH[2];
+	GaussTria*  gauss=NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, 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);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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;
+			default:
+				_error2_("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,ig;
+	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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&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 = - pow(meanvel,2.) * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+						duy = - pow(meanvel,2.) * 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 RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				default:
+					_error2_("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,ig;
+	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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&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 = - pow(meanvel,2.) * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+						duy = - pow(meanvel,2.) * 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 RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				default:
+					_error2_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(responses);
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::DragCoefficientAbsGradient{{{*/
+IssmDouble Tria::DragCoefficientAbsGradient(bool process_units,int weight_index){
+
+	/* Intermediaries */
+	int        ig;
+	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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant2d(&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*(pow(dp[0],2.)+pow(dp[1],2.))*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:
+			_error2_("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,ig;
+	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     phi[NUMVERTICES];
+	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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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);
+		matice->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])) _error2_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambday[i])) _error2_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new TriaP1Input(AdjointxEnum,lambdax));
+	this->inputs->AddInput(new TriaP1Input(AdjointyEnum,lambday));
+
+	/*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])) _error2_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new TriaP1Input(AdjointEnum,lambda));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::GetVectorFromControlInputs{{{*/
+void  Tria::GetVectorFromControlInputs(Vector* vector,int control_enum,int control_index,const char* data){
+
+	int doflist1[NUMVERTICES];
+	Input *input=NULL;
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&doflist1[0],control_index);
+
+	/*Get input (either in element or material)*/
+	if(control_enum==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->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){
+		_error2_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->GetVectorFromInputs(vector,&doflist1[0],data);
+}
+/*}}}*/
+/*FUNCTION Tria::SetControlInputsFromVector{{{*/
+void  Tria::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){
+
+	IssmDouble  values[NUMVERTICES];
+	int     doflist1[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(&doflist1[0],control_index);
+
+	/*Get values on vertices*/
+	for (int i=0;i<NUMVERTICES;i++){
+		values[i]=vector[doflist1[i]];
+	}
+	new_input = new TriaP1Input(control_enum,values);
+
+	if(control_enum==MaterialsRheologyBbarEnum){
+		input=(Input*)matice->inputs->GetInput(control_enum); _assert_(input);
+	}
+	else{
+		input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	}
+
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error2_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->SetInput(new_input);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_HYDROLOGY_
+/*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*pow(CR,2)*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]= - pow(w,2)/(12 * mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
+	//	vy[iv]= - pow(w,2)/(12 * mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
+	
+		vx[iv]= - pow(w,2)/(VelocityFactor* mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
+		vy[iv]= - pow(w,2)/(VelocityFactor* mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
+	}
+
+	/*clean-up*/
+	delete gauss;
+
+	/*Add to inputs*/
+	this->inputs->AddInput(new TriaP1Input(HydrologyWaterVxEnum,vx));
+	this->inputs->AddInput(new TriaP1Input(HydrologyWaterVyEnum,vy));
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixHydrology{{{*/
+ElementMatrix* Tria::CreateKMatrixHydrology(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	IssmDouble     diffusivity;
+	int        i,j,ig;
+	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     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};
+	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], nodes, NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&diffusivity,HydrologyStabilizationEnum);
+	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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		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( &L[0],1,numdof,1,
+					&DL_scalar,1,1,0,
+					&L[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(pow(vx,2.)+pow(vy,2.));
+		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::CreatePVectorHydrology {{{*/
+ElementVector* Tria::CreatePVectorHydrology(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,ig;
+	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], nodes, 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(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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(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::GetSolutionFromInputsHydrology{{{*/
+void  Tria::GetSolutionFromInputsHydrology(Vector* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int i;
+	int*         doflist=NULL;
+	IssmDouble       watercolumn;
+	IssmDouble       values[numdof];
+	GaussTria*   gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Get inputs*/
+	Input* watercolumn_input=inputs->GetInput(WatercolumnEnum); _assert_(watercolumn_input);
+
+	/*Ok, we have watercolumn values, fill in watercolumn array: */
+	/*P1 element only for now*/
+	gauss=new GaussTria();
+	for(i=0;i<NUMVERTICES;i++){
+
+		gauss->GaussVertex(i);
+
+		/*Recover watercolumn*/
+		watercolumn_input->GetInputValue(&watercolumn,gauss);
+		values[i]=watercolumn;
+	}
+
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionHydrology{{{*/
+void  Tria::InputUpdateFromSolutionHydrology(IssmDouble* solution){
+
+	/*Intermediaries*/
+	const int numdof = NDOF1*NUMVERTICES;
+
+	int       i;
+	int*      doflist=NULL;
+	IssmDouble    values[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]];
+		if(xIsNan<IssmDouble>(values[i])) _error2_("NaN found in solution vector");
+		if (values[i]<pow((IssmDouble)10,(IssmDouble)-10))values[i]=pow((IssmDouble)10,(IssmDouble)-10); //correcting the water column to positive values
+ 
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new TriaP1Input(WatercolumnEnum,values));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+#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 TriaP1Input*/
+			IssmDouble values[3];
+
+			/*Get values on the 3 vertices*/
+			for (i=0;i<3;i++){
+				values[i]=vector[this->nodes[i]->GetSidList()]; //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 TriaP1Input(ThicknessEnum,thickness));
+					this->inputs->AddInput(new TriaP1Input(BedEnum,bed));
+					this->inputs->AddInput(new TriaP1Input(SurfaceEnum,surface));
+
+					break;
+				default:
+					this->inputs->AddInput(new TriaP1Input(name,values));
+			}
+			break;
+
+		default:
+			_error2_("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){
+	_error2_("not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVectorDakota(bool* vector, int name, int type);{{{*/
+void  Tria::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+	_error2_("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->nodes[i]->GetSidList();
+					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 TriaP1Input(name,values),time);
+				transientinput->Configure(parameters);
+			}
+			this->inputs->AddInput(transientinput);
+			break;
+
+		default:
+			_error2_("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:
+			_error2_("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,ig,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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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(pow(vx,2.)+pow(vy,2.));
+			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,ig,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], nodes, 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 (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant2d(&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:
+			_error2_("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,ig;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     dhdt_g,basal_melting_g,surface_mass_balance_g,Jdettria;
+	IssmDouble     L[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], nodes, 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(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);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(surface_mass_balance_g-basal_melting_g-dhdt_g)*L[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,ig;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     basal_melting_g,surface_mass_balance_g,dhdt_g,Jdettria;
+	IssmDouble     L[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], nodes, 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(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);
+
+		GetJacobianDeterminant2d(&Jdettria, &xyz_list[0][0],gauss);
+		GetL(&L[0], &xyz_list[0][0], gauss,NDOF1);
+
+		for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(surface_mass_balance_g-basal_melting_g-dhdt_g)*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Tria.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Tria.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/Tria.h	(revision 12878)
@@ -0,0 +1,239 @@
+/*! \file Tria.h 
+ *  \brief: header file for tria object
+ */
+
+#ifndef _TRIA_H_
+#define _TRIA_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Element.h"
+#include "./TriaHook.h"
+#include "./TriaRef.h"
+class Parameters;
+class Inputs;
+class IoModel;
+class Node;
+class Matice;
+class Matpar;
+class ElementMatrix;
+class ElementVector;
+
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+/*}}}*/
+
+class Tria: public Element,public TriaHook,public TriaRef{
+
+	public:
+
+		int  id;
+		int  sid;
+
+		Node   **nodes;    // 3 nodes
+		Matice  *matice;   // 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   MyRank();
+		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   AverageOntoPartition(Vector* partition_contributions,Vector* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
+		void   ComputeBasalStress(Vector* sigma_b);
+		void   ComputeStrainRate(Vector* eps);
+		void   ComputeStressTensor();
+		void   Configure(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters);
+		void   SetCurrentConfiguration(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters);
+		void   CreateKMatrix(Matrix* Kff, Matrix* Kfs,Vector* df);
+		void   CreatePVector(Vector* pf);
+		void   CreateJacobianMatrix(Matrix* Jff);
+		void   Delta18oParameterization(void);
+		int    GetNodeIndex(Node* node);
+		int    Sid();
+		bool   IsOnBed();
+		bool   IsFloating(); 
+		bool   IsNodeOnShelf(); 
+		bool   IsNodeOnShelfFromFlags(IssmDouble* flags);
+		bool   IsOnWater(); 
+		void   GetSolutionFromInputs(Vector* solution);
+		void   GetVectorFromInputs(Vector* vector, int name_enum);
+		void   GetVectorFromResults(Vector* vector,int offset,int enum_in,int interp);
+		void   InputArtificialNoise(int enum_type,IssmDouble min, IssmDouble max);
+		bool   InputConvergence(IssmDouble* eps, int* enums,int num_enums,int* criterionenums,IssmDouble* criterionvalues,int num_criterionenums);
+		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){_error2_("not implemented yet");};
+		void   MigrateGroundingLine(IssmDouble* oldfloating,IssmDouble* sheet_ungrounding);
+		int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum,bool process_units);
+		void   PotentialSheetUngrounding(Vector* potential_sheet_ungrounding);
+		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   ProcessResultsUnits(void);
+		void   ResetCoordinateSystem(void){_error2_("not implemented yet");};
+		void	 SmbGradients();
+		IssmDouble SurfaceArea(void);
+		void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type);
+		int    UpdatePotentialSheetUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf);
+		IssmDouble TimeAdapt();
+		int*   GetHorizontalNeighboorSids(void);
+		void   SmearFunction(Vector* smearedvector,IssmDouble (*WeightFunction)(IssmDouble distance,IssmDouble radius),IssmDouble radius);
+
+		#ifdef _HAVE_RESPONSES_
+		IssmDouble IceVolume(void);
+		IssmDouble TotalSmb(void);
+		void   MinVel(IssmDouble* pminvel, bool process_units);
+		void   MinVx(IssmDouble* pminvx, bool process_units);
+		void   MinVy(IssmDouble* pminvy, bool process_units);
+		void   MinVz(IssmDouble* pminvz, bool process_units);
+		IssmDouble MassFlux(IssmDouble* segment,bool process_units);
+		void   MaxAbsVx(IssmDouble* pmaxabsvx, bool process_units);
+		void   MaxAbsVy(IssmDouble* pmaxabsvy, bool process_units);
+		void   MaxAbsVz(IssmDouble* pmaxabsvz, bool process_units);
+		void   ElementResponse(IssmDouble* presponse,int response_enum,bool process_units);
+		void   MaxVel(IssmDouble* pmaxvel, bool process_units);
+		void   MaxVx(IssmDouble* pmaxvx, bool process_units);
+		void   MaxVy(IssmDouble* pmaxvy, bool process_units);
+		void   MaxVz(IssmDouble* pmaxvz, bool process_units);
+		#endif
+
+
+		#ifdef _HAVE_CONTROL_
+		IssmDouble DragCoefficientAbsGradient(bool process_units,int weight_index);
+		void   GradientIndexing(int* indexing,int control_index);
+		void   Gradj(Vector* gradient,int control_type,int control_index);
+		void   GradjBGradient(Vector* gradient,int weight_index,int control_index);
+		void   GradjBMacAyeal(Vector* gradient,int control_index);
+		void   GradjDragMacAyeal(Vector* gradient,int control_index);
+		void   GradjDragStokes(Vector* gradient,int control_index);
+		void   GradjDragGradient(Vector* gradient,int weight_index,int control_index);
+		void   GradjDhDtBalancedthickness(Vector* gradient,int control_index);
+		void   GradjVxBalancedthickness(Vector* gradient,int control_index);
+		void   GradjVyBalancedthickness(Vector* gradient,int control_index);
+		void   GetVectorFromControlInputs(Vector* gradient,int control_enum,int control_index,const char* data);
+		void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
+		void   ControlInputGetGradient(Vector* 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(bool process_units,int weight_index);
+		IssmDouble ThicknessAbsMisfit(     bool process_units,int weight_index);
+		IssmDouble SurfaceAbsVelMisfit(    bool process_units,int weight_index);
+		IssmDouble ThicknessAbsGradient(bool process_units,int weight_index);
+		IssmDouble SurfaceRelVelMisfit(    bool process_units,int weight_index);
+		IssmDouble SurfaceLogVelMisfit(    bool process_units,int weight_index);
+		IssmDouble SurfaceLogVxVyMisfit(   bool process_units,int weight_index);
+		IssmDouble SurfaceAverageVelMisfit(bool process_units,int weight_index);
+		void   InputControlUpdate(IssmDouble scalar,bool save_parameter);
+		#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* CreateKMatrixSlope(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	         GetDofList1(int* doflist);
+		void           GetSidList(int* sidlist);
+		void           GetConnectivityList(int* connectivity);
+		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           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]);
+		
+		#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* solution);
+		void	  GetSolutionFromInputsDiagnosticHutter(Vector* 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* CreateKMatrixHydrology(void);
+		ElementVector* CreatePVectorHydrology(void);
+		void      CreateHydrologyWaterVelocityInput(void);
+		void	  GetSolutionFromInputsHydrology(Vector* solution);
+		void	  InputUpdateFromSolutionHydrology(IssmDouble* solution);
+		#endif
+		#ifdef _HAVE_BALANCED_
+		#endif
+
+		/*}}}*/
+
+};
+#endif  /* _TRIA_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaHook.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaHook.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaHook.cpp	(revision 12878)
@@ -0,0 +1,72 @@
+/*!\file TriaHook.c
+ * \brief: implementation of the TriaHook 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 "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*Object constructors and destructor*/
+/*FUNCTION TriaHook::TriaHook(){{{*/
+TriaHook::TriaHook(){
+	numanalyses=UNDEF;
+	this->hnodes=NULL;
+	this->hmatice=NULL;
+	this->hmatpar=NULL;
+}
+/*}}}*/
+/*FUNCTION TriaHook::~TriaHook(){{{*/
+TriaHook::~TriaHook(){
+	int i;
+
+	for(i=0;i<this->numanalyses;i++){
+		if (this->hnodes[i]) delete this->hnodes[i];
+	}
+	delete [] this->hnodes;
+	delete hmatice;
+	delete hmatpar;
+
+}
+/*}}}*/
+/*FUNCTION TriaHook::TriaHook(int in_numanalyses,int matice_id, int matpar_id){{{*/
+TriaHook::TriaHook(int in_numanalyses,int matice_id, IoModel* iomodel){
+
+	/*intermediary: */
+	int matpar_id;
+
+	/*retrieve parameters: */
+	iomodel->Constant(&matpar_id,MeshNumberofelementsEnum); matpar_id++;
+	
+	this->numanalyses=in_numanalyses;
+	this->hnodes= new Hook*[in_numanalyses];
+	this->hmatice=new Hook(&matice_id,1);
+	this->hmatpar=new Hook(&matpar_id,1);
+
+	//Initialize hnodes as NULL
+	for(int i=0;i<this->numanalyses;i++){
+		this->hnodes[i]=NULL;
+	}
+
+}
+/*}}}*/
+
+/*FUNCTION TriaHook::SetHookNodes{{{*/
+void TriaHook::SetHookNodes(int* node_ids,int analysis_counter){
+
+	/*initialize hook*/
+	this->hnodes[analysis_counter]=new Hook(node_ids,3);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaHook.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaHook.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaHook.h	(revision 12878)
@@ -0,0 +1,31 @@
+/*!\file: TriaHook.h
+ * \brief prototypes for TriaHook.h
+ */ 
+
+#ifndef _TRIAHOOK_H_
+#define  _TRIAHOOK_H_
+
+class Hook;
+class IoModel;
+
+class TriaHook{
+
+	public: 
+		int    numanalyses; //number of analysis types
+		Hook** hnodes; // 3 nodes for each analysis type
+		Hook*  hmatice; // 1 ice material
+		Hook*  hmatpar; // 1 material parameter
+
+
+		/*FUNCTION constructors, destructors {{{*/
+		TriaHook();
+		TriaHook(int in_numanalyses,int matice_id, IoModel* iomodel);
+		~TriaHook();
+		void SetHookNodes(int* node_ids,int analysis_counter);
+		/*}}}*/
+
+};
+
+
+#endif //ifndef _TRIAHOOK_H_
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaRef.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaRef.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaRef.cpp	(revision 12878)
@@ -0,0 +1,503 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*Element macros*/
+#define NUMNODES 3
+
+/*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::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=[ 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: 3x(NDOF2*NUMNODES)
+	 */
+
+	int i;
+	IssmDouble dbasis[NDOF2][NUMNODES];
+
+	/*Get dh1dh2dh3 in actual coordinate system: */
+	GetNodalFunctionsDerivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build B: */
+	for (i=0;i<NUMNODES;i++){
+		*(B+NDOF2*NUMNODES*0+NDOF2*i)=dbasis[0][i]; //B[0][NDOF2*i]=dbasis[0][i];
+		*(B+NDOF2*NUMNODES*0+NDOF2*i+1)=0;
+		*(B+NDOF2*NUMNODES*1+NDOF2*i)=0;
+		*(B+NDOF2*NUMNODES*1+NDOF2*i+1)=dbasis[1][i];
+		*(B+NDOF2*NUMNODES*2+NDOF2*i)=(float).5*dbasis[1][i]; 
+		*(B+NDOF2*NUMNODES*2+NDOF2*i+1)=(float).5*dbasis[0][i]; 
+	}
+}
+/*}}}*/
+/*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=[   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: 3x(NDOF2*NUMNODES)
+	 */
+
+	/*Same thing in the actual coordinate system: */
+	IssmDouble dbasis[NDOF2][NUMNODES];
+
+	/*Get dh1dh2dh3 in actual coordinates system : */
+	GetNodalFunctionsDerivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build B': */
+	for (int i=0;i<NUMNODES;i++){
+		*(B+NDOF2*NUMNODES*0+NDOF2*i)=dbasis[0][i]; 
+		*(B+NDOF2*NUMNODES*0+NDOF2*i+1)=0; 
+		*(B+NDOF2*NUMNODES*1+NDOF2*i)=0; 
+		*(B+NDOF2*NUMNODES*1+NDOF2*i+1)=dbasis[1][i]; 
+		*(B+NDOF2*NUMNODES*2+NDOF2*i)=0.5*dbasis[1][i]; 
+		*(B+NDOF2*NUMNODES*2+NDOF2*i+1)=0.5*dbasis[0][i]; 
+	}
+}
+/*}}}*/
+/*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
+	 */
+
+	IssmDouble l1l3[NUMNODES];
+
+	GetNodalFunctions(&l1l3[0],gauss);
+
+	B[0] = +l1l3[index1];
+	B[1] = +l1l3[index2];
+	B[2] = -l1l3[index1];
+	B[3] = -l1l3[index2];
+}
+/*}}}*/
+/*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
+	 */
+
+	IssmDouble l1l3[NUMNODES];
+
+	GetNodalFunctions(&l1l3[0],gauss);
+
+	Bprime[0] = l1l3[index1];
+	Bprime[1] = l1l3[index2];
+	Bprime[2] = l1l3[index1];
+	Bprime[3] = l1l3[index2];
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBPrognostic{{{*/
+void TriaRef::GetBPrognostic(IssmDouble* B_prog, 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=[ h ]
+	 *          [ h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*NUMNODES)
+	 */
+
+	IssmDouble basis[NUMNODES];
+
+	/*Get dh1dh2dh3 in actual coordinate system: */
+	GetNodalFunctions(&basis[0],gauss);
+
+	/*Build B_prog: */
+	for (int i=0;i<NUMNODES;i++){
+		*(B_prog+NDOF1*NUMNODES*0+NDOF1*i)=basis[i];
+		*(B_prog+NDOF1*NUMNODES*1+NDOF1*i)=basis[i];
+	}
+}
+/*}}}*/
+/*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*dh/dx    dh/dy ]
+	 *                [   dh/dx  2*dh/dy ]
+	 *                [   dh/dy    dh/dx ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*NUMNODES)
+	 */
+
+	/*Same thing in the actual coordinate system: */
+	IssmDouble dbasis[NDOF2][NUMNODES];
+
+	/*Get dh1dh2dh3 in actual coordinates system : */
+	GetNodalFunctionsDerivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build B': */
+	for (int i=0;i<NUMNODES;i++){
+		*(Bprime+NDOF2*NUMNODES*0+NDOF2*i)=2*dbasis[0][i]; 
+		*(Bprime+NDOF2*NUMNODES*0+NDOF2*i+1)=dbasis[1][i]; 
+		*(Bprime+NDOF2*NUMNODES*1+NDOF2*i)=dbasis[0][i]; 
+		*(Bprime+NDOF2*NUMNODES*1+NDOF2*i+1)=2*dbasis[1][i]; 
+		*(Bprime+NDOF2*NUMNODES*2+NDOF2*i)=dbasis[1][i]; 
+		*(Bprime+NDOF2*NUMNODES*2+NDOF2*i+1)=dbasis[0][i]; 
+	}
+}
+/*}}}*/
+/*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=[  dh/dx    0   ]
+	 *               [    0    dh/dy ]
+	 *               [  dh/dy  dh/dx ]
+	 *               [  dh/dx  dh/dy ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume Bprime has been allocated already, of size: 3x(NDOF2*NUMNODES)
+	 */
+
+	/*Same thing in the actual coordinate system: */
+	IssmDouble dbasis[NDOF2][NUMNODES];
+
+	/*Get dh1dh2dh3 in actual coordinates system : */
+	GetNodalFunctionsDerivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build Bprime: */
+	for (int i=0;i<NUMNODES;i++){
+		*(Bprime+NDOF2*NUMNODES*0+NDOF2*i)=dbasis[0][i]; 
+		*(Bprime+NDOF2*NUMNODES*0+NDOF2*i+1)=0; 
+		*(Bprime+NDOF2*NUMNODES*1+NDOF2*i)=0; 
+		*(Bprime+NDOF2*NUMNODES*1+NDOF2*i+1)=dbasis[1][i]; 
+		*(Bprime+NDOF2*NUMNODES*2+NDOF2*i)=dbasis[1][i]; 
+		*(Bprime+NDOF2*NUMNODES*2+NDOF2*i+1)=dbasis[0][i]; 
+		*(Bprime+NDOF2*NUMNODES*3+NDOF2*i)=dbasis[0][i]; 
+		*(Bprime+NDOF2*NUMNODES*3+NDOF2*i+1)=dbasis[1][i]; 
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetBprimePrognostic{{{*/
+void TriaRef::GetBprimePrognostic(IssmDouble* Bprime_prog, 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=[ dh/dx ]
+	 *                [ dh/dy ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*NUMNODES)
+	 */
+
+	/*Same thing in the actual coordinate system: */
+	IssmDouble dbasis[NDOF2][NUMNODES];
+
+	/*Get dh1dh2dh3 in actual coordinates system : */
+	GetNodalFunctionsDerivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build B': */
+	for (int i=0;i<NUMNODES;i++){
+		*(Bprime_prog+NDOF1*NUMNODES*0+NDOF1*i)=dbasis[0][i]; 
+		*(Bprime_prog+NDOF1*NUMNODES*1+NDOF1*i)=dbasis[1][i]; 
+	}
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetL{{{*/
+void TriaRef::GetL(IssmDouble* L, IssmDouble* xyz_list,GaussTria* gauss,int numdof){
+	/*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: 
+	 *       numdof=1: 
+	 *                 Li=h;
+	 *       numdof=2:
+	 *                 Li=[ h   0 ]
+	 *                    [ 0   h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume L has been allocated already, of size: NUMNODES (numdof=1), or numdofx(numdof*NUMNODES) (numdof=2)
+	 */
+
+	int i;
+	IssmDouble basis[3];
+
+	/*Get basis in actual coordinate system: */
+	GetNodalFunctions(basis,gauss);
+
+	/*Build L: */
+	if(numdof==1){
+		for (i=0;i<NUMNODES;i++){
+			L[i]=basis[i]; 
+		}
+	}
+	else{
+		for (i=0;i<NUMNODES;i++){
+			*(L+numdof*NUMNODES*0+numdof*i)=basis[i]; //L[0][NDOF2*i]=dbasis[0][i];
+			*(L+numdof*NUMNODES*0+numdof*i+1)=0;
+			*(L+numdof*NUMNODES*1+numdof*i)=0;
+			*(L+numdof*NUMNODES*1+numdof*i+1)=basis[i];
+		}
+	}
+}
+/*}}}*/
+/*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,y1,x2,y2,x3,y3;
+
+	x1=*(xyz_list+NUMNODES*0+0);
+	y1=*(xyz_list+NUMNODES*0+1);
+	x2=*(xyz_list+NUMNODES*1+0);
+	y2=*(xyz_list+NUMNODES*1+1);
+	x3=*(xyz_list+NUMNODES*2+0);
+	y3=*(xyz_list+NUMNODES*2+1);
+
+
+	*(J+NDOF2*0+0)=0.5*(x2-x1);
+	*(J+NDOF2*1+0)=SQRT3/6.0*(2*x3-x1-x2);
+	*(J+NDOF2*0+1)=0.5*(y2-y1);
+	*(J+NDOF2*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,y1,x2,y2;
+
+	x1=*(xyz_list+3*0+0);
+	y1=*(xyz_list+3*0+1);
+	x2=*(xyz_list+3*1+0);
+	y2=*(xyz_list+3*1+1);
+
+	*Jdet=1.0/2.0*sqrt(pow(x2-x1,2.) + pow(y2-y1,2.));
+	if(*Jdet<0) _error2_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetJacobianDeterminant2d{{{*/
+void TriaRef::GetJacobianDeterminant2d(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) _error2_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetJacobianDeterminant3d {{{*/
+void TriaRef::GetJacobianDeterminant3d(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 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=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) _error2_("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.*/
+
+	basis[0]=gauss->coord1;
+	basis[1]=gauss->coord2;
+	basis[2]=gauss->coord3;
+
+}
+/*}}}*/
+/*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.*/
+
+	IssmDouble BasisFunctions[3];
+
+	GetNodalFunctions(&BasisFunctions[0],gauss);
+
+	_assert_(index1>=0 && index1<3);
+	_assert_(index2>=0 && index2<3);
+	basis[0]=BasisFunctions[index1];
+	basis[1]=BasisFunctions[index2];
+}
+/*}}}*/
+/*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): */
+	int       i;
+	IssmDouble    dbasis_ref[NDOF2][NUMNODES];
+	IssmDouble    Jinv[NDOF2][NDOF2];
+
+	/*Get derivative values with respect to parametric coordinate system: */
+	GetNodalFunctionsDerivativesReference(&dbasis_ref[0][0], gauss); 
+
+	/*Get Jacobian invert: */
+	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
+
+	/*Build dbasis: 
+	 *
+	 * [dhi/dx]= Jinv*[dhi/dr]
+	 * [dhi/dy]       [dhi/ds]
+	 */
+	for (i=0;i<NUMNODES;i++){
+		dbasis[NUMNODES*0+i]=Jinv[0][0]*dbasis_ref[0][i]+Jinv[0][1]*dbasis_ref[1][i];
+		dbasis[NUMNODES*1+i]=Jinv[1][0]*dbasis_ref[0][i]+Jinv[1][1]*dbasis_ref[1][i];
+	}
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctionsDerivativesReference{{{*/
+void TriaRef::GetNodalFunctionsDerivativesReference(IssmDouble* dl1dl3,GaussTria* gauss){
+	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
+	 * natural coordinate system) at the gaussian point. */
+
+	/*First nodal function: */
+	*(dl1dl3+NUMNODES*0+0)=-0.5; 
+	*(dl1dl3+NUMNODES*1+0)=-1.0/(2.0*SQRT3);
+
+	/*Second nodal function: */
+	*(dl1dl3+NUMNODES*0+1)=0.5;
+	*(dl1dl3+NUMNODES*1+1)=-1.0/(2.0*SQRT3);
+
+	/*Third nodal function: */
+	*(dl1dl3+NUMNODES*0+2)=0;
+	*(dl1dl3+NUMNODES*1+2)=1.0/SQRT3;
+
+}
+/*}}}*/
+/*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 of size 2x1 already allocated.
+	 */
+
+	/*Nodal Derivatives*/
+	IssmDouble dbasis[2][3]; //nodal derivative functions in actual coordinate system.
+
+	/*Get dh1dh2dh3 in actual coordinate system: */
+	GetNodalFunctionsDerivatives(&dbasis[0][0],xyz_list, gauss);
+
+	/*Assign values*/
+	*(p+0)=plist[0]*dbasis[0][0]+plist[1]*dbasis[0][1]+plist[2]*dbasis[0][2];
+	*(p+1)=plist[0]*dbasis[1][0]+plist[1]*dbasis[1][1]+plist[2]*dbasis[1][2];
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetInputValue{{{*/
+void TriaRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussTria* gauss){
+
+	/*From node values of parameter p (plist[0],plist[1],plist[2]), return parameter value at gaussian 
+	 * point specifie by gauss: */
+
+	/*nodal functions annd output: */
+	IssmDouble basis[3];
+
+	/*Get nodal functions*/
+	GetNodalFunctions(basis, gauss);
+
+	/*Get parameter*/
+	*p=basis[0]*plist[0]+basis[1]*plist[1]+basis[2]*plist[2];
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaRef.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaRef.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Elements/TriaRef.h	(revision 12878)
@@ -0,0 +1,49 @@
+/*!\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_prog, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetBPrognostic(IssmDouble* B_prog, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetL(IssmDouble* L, IssmDouble* xyz_list,GaussTria* gauss,int numdof);
+		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussTria* gauss);
+		void GetSegmentJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,GaussTria* gauss);
+		void GetJacobianDeterminant2d(IssmDouble* Jdet, IssmDouble* xyz_list,GaussTria* gauss);
+		void GetJacobianDeterminant3d(IssmDouble* Jdet, IssmDouble* xyz_list,GaussTria* gauss);
+		void GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,GaussTria* gauss);
+		void GetNodalFunctions(IssmDouble* l1l2l3,GaussTria* gauss);
+		void GetSegmentNodalFunctions(IssmDouble* l1l2l3,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* l1l2l3,IssmDouble* xyz_list, GaussTria* gauss);
+		void GetNodalFunctionsDerivativesReference(IssmDouble* dl1dl3,GaussTria* gauss);
+		void GetInputValue(IssmDouble* pp, IssmDouble* plist, GaussTria* gauss);
+		void GetInputDerivativeValue(IssmDouble* pp, IssmDouble* plist,IssmDouble* xyz_list, GaussTria* gauss);
+
+};
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/BoolExternalResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/BoolExternalResult.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/BoolExternalResult.cpp	(revision 12878)
@@ -0,0 +1,132 @@
+/*!\file BoolExternalResult.c
+ * \brief: implementation of the BoolExternalResult object
+ */
+
+/*header files: */
+/*{{{*/
+#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 "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*BoolExternalResult constructors and destructor*/
+/*FUNCTION BoolExternalResult::BoolExternalResult(){{{*/
+BoolExternalResult::BoolExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::BoolExternalResult(int enum_type,bool value){{{*/
+BoolExternalResult::BoolExternalResult(int in_id, int in_enum_type,bool 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;
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::~BoolExternalResult(){{{*/
+BoolExternalResult::~BoolExternalResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION BoolExternalResult::Echo {{{*/
+void BoolExternalResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::DeepEcho{{{*/
+void BoolExternalResult::DeepEcho(void){
+
+	_printLine_("BoolExternalResult:");
+	_printLine_("   id: " << this->id);
+	_printLine_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " <<(this->value?"true":"false"));
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::Id{{{*/
+int    BoolExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION BoolExternalResult::MyRank{{{*/
+int    BoolExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::ObjectEnum{{{*/
+int BoolExternalResult::ObjectEnum(void){
+
+	return BoolExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::copy{{{*/
+Object* BoolExternalResult::copy() {
+	
+	return new BoolExternalResult(this->id,this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*BoolExternalResult management: */
+/*FUNCTION BoolExternalResult::WriteData{{{*/
+void   BoolExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	int     size;
+	IssmPDouble  passiveDouble;
+	extern  int my_rank;
+	char*   name = NULL;
+
+	/*return if now on cpu 0: */
+	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, type is 1, size is 1: */
+	type=1;
+	size=1;
+	fwrite(&type,sizeof(int),1,fid);
+	fwrite(&size,sizeof(int),1,fid);
+        /*Now write bool, after casting it: */
+        passiveDouble=reCast<IssmPDouble>(this->value);
+        fwrite(&passiveDouble,size*sizeof(IssmPDouble),1,fid);
+
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::GetResultName{{{*/
+void BoolExternalResult::GetResultName(char** pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION BoolExternalResult::GetStep{{{*/
+int BoolExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/BoolExternalResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/BoolExternalResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/BoolExternalResult.h	(revision 12878)
@@ -0,0 +1,54 @@
+/*! \file BoolExternalResult.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _BOOLEXTERNALRESULT_H_
+#define _BOOLEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ExternalResult.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+class BoolExternalResult: public ExternalResult{
+
+	public:
+		int    id;
+		int    enum_type;
+		bool   value;
+		int    step;
+		IssmDouble time;
+
+		/*BoolExternalResult constructors, destructors: {{{*/
+		BoolExternalResult();
+		BoolExternalResult(int id, int enum_type,bool value,int step,IssmDouble time);
+		~BoolExternalResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult management: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleExternalResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleExternalResult.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleExternalResult.cpp	(revision 12878)
@@ -0,0 +1,131 @@
+/*!\file DoubleExternalResult.c
+ * \brief: implementation of the DoubleExternalResult object
+ */
+
+/*header files: */
+/*{{{*/
+#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 "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*DoubleExternalResult constructors and destructor*/
+/*FUNCTION DoubleExternalResult::DoubleExternalResult(){{{*/
+DoubleExternalResult::DoubleExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::DoubleExternalResult(int enum_type,IssmDouble value){{{*/
+DoubleExternalResult::DoubleExternalResult(int in_id, int in_enum_type,IssmDouble 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;
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::~DoubleExternalResult(){{{*/
+DoubleExternalResult::~DoubleExternalResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleExternalResult::Echo {{{*/
+void DoubleExternalResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::DeepEcho{{{*/
+void DoubleExternalResult::DeepEcho(void){
+
+	_printLine_("DoubleExternalResult:");
+	_printLine_("   id: " << this->id);
+	_printLine_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " << this->value);
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::Id{{{*/
+int    DoubleExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleExternalResult::MyRank{{{*/
+int    DoubleExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::ObjectEnum{{{*/
+int DoubleExternalResult::ObjectEnum(void){
+
+	return DoubleExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::copy{{{*/
+Object* DoubleExternalResult::copy() {
+	
+	return new DoubleExternalResult(this->id,this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*DoubleExternalResult management: */
+/*FUNCTION DoubleExternalResult::WriteData{{{*/
+void   DoubleExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	int     size;
+	char   *name    = NULL;
+	extern  int my_rank;
+	IssmPDouble passiveDouble;
+
+	/*return if now on cpu 0: */
+	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, type is 1, size is 1: */
+	type=1;
+	size=1;
+	fwrite(&type,sizeof(int),1,fid);
+	fwrite(&size,sizeof(int),1,fid);
+        passiveDouble=reCast<IssmPDouble>(this->value);
+	fwrite(&passiveDouble,size*sizeof(IssmPDouble),1,fid);
+
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::GetResultName{{{*/
+void DoubleExternalResult::GetResultName(char** pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleExternalResult::GetStep{{{*/
+int DoubleExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleExternalResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleExternalResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleExternalResult.h	(revision 12878)
@@ -0,0 +1,56 @@
+/*! \file DoubleExternalResult.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _DOUBLEEXTERNALRESULT_H_
+#define _DOUBLEEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+
+#include "./ExternalResult.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+class DoubleExternalResult: public ExternalResult{
+
+	public:
+		int    id;
+		int    enum_type;
+		IssmDouble value;
+		int    step;
+		IssmDouble time;
+
+
+		/*DoubleExternalResult constructors, destructors: {{{*/
+		DoubleExternalResult();
+		DoubleExternalResult(int id,int enum_type,IssmDouble value,int step,IssmDouble time);
+		~DoubleExternalResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult management: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _DOUBLEEXTERNALRESULT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleMatExternalResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleMatExternalResult.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleMatExternalResult.cpp	(revision 12878)
@@ -0,0 +1,166 @@
+/*!\file DoubleMatExternalResult.c
+ * \brief: implementation of the DoubleMatExternalResult object
+ */
+
+/*header files: */
+/*{{{*/
+#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 "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*DoubleMatExternalResult constructors and destructor*/
+/*FUNCTION DoubleMatExternalResult::DoubleMatExternalResult(){{{*/
+DoubleMatExternalResult::DoubleMatExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::DoubleMatExternalResult(int in_id, int enum_type,IssmDoubleMat values,int M,int N,int in_step,IssmDouble in_time){{{*/
+DoubleMatExternalResult::DoubleMatExternalResult(int in_id, int in_enum_type,IssmDouble* 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;
+
+	/*Copy result in values*/
+	if(M*N){
+		values=xNew<IssmDouble>(M*N);
+		xMemCpy<IssmDouble>(values,in_values,M*N);
+	}
+	else values=NULL;
+
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::~DoubleMatExternalResult(){{{*/
+DoubleMatExternalResult::~DoubleMatExternalResult(){
+
+	xDelete<IssmDouble>(this->values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleMatExternalResult::Echo {{{*/
+void DoubleMatExternalResult::Echo(void){
+
+	_printLine_("DoubleMatExternalResult:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+	_printLine_("   matrix size: " << this->M << "-" << this->N);
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::DeepEcho{{{*/
+void DoubleMatExternalResult::DeepEcho(void){
+
+	int i,j;
+	
+	_printLine_("DoubleMatExternalResult:");
+	_printLine_("   id: " << this->id);
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+	_printLine_("   matrix size: " << this->M << "-" << this->N);
+	for (i=0;i<this->M;i++){  
+		_printString_("   [ ");
+		for (j=0;j<this->N;j++){
+			_printString_( " " << setw(11) << setprecision (5) << this->values[i*this->N+j]);
+		}  
+		_printLine_(" ]");
+	}  
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::Id{{{*/
+int    DoubleMatExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::MyRank{{{*/
+int    DoubleMatExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::ObjectEnum{{{*/
+int DoubleMatExternalResult::ObjectEnum(void){
+
+	return DoubleMatExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::copy{{{*/
+Object* DoubleMatExternalResult::copy() {
+	
+	return new DoubleMatExternalResult(this->id,this->enum_type,this->values,this->M,this->N,this->step,this->time);
+
+}
+/*}}}*/
+
+/*DoubleMatExternalResult management: */
+/*FUNCTION DoubleMatExternalResult::WriteData{{{*/
+void   DoubleMatExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	int     rows,cols;
+	char   *name    = NULL;
+	extern  int my_rank;
+	IssmPDouble *passiveDouble_p=NULL;
+	IssmPDouble passiveDouble;
+
+	if(io_gather){
+		/*we are gathering the data on cpu 0, don't write on other cpus: */
+		if(my_rank) return;
+	}
+
+	passiveDouble_p=xNew<IssmPDouble>(M*N);
+
+	/*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);
+	for (int i=0; i<N*M; ++i) passiveDouble_p[i]=reCast<IssmPDouble>(values[i]);
+	fwrite(passiveDouble_p,cols*rows*sizeof(IssmPDouble),1,fid);
+	xDelete(passiveDouble_p);
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::GetResultName{{{*/
+void DoubleMatExternalResult::GetResultName(char** pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleMatExternalResult::GetStep{{{*/
+int DoubleMatExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleMatExternalResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleMatExternalResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleMatExternalResult.h	(revision 12878)
@@ -0,0 +1,56 @@
+/*! \file DoubleMatExternalResult.h 
+ */
+
+
+#ifndef _DOUBLEMATEXTERNALRESULT_H_
+#define _DOUBLEMATEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ExternalResult.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+class DoubleMatExternalResult: public ExternalResult{
+
+	private: 
+		int id;
+		int enum_type;
+		IssmDouble* values;
+		int M;
+		int N;
+		int step;
+		IssmDouble time;
+
+	public:
+		/*DoubleMatExternalResult constructors, destructors: {{{*/
+		DoubleMatExternalResult();
+		DoubleMatExternalResult(int id,int enum_type,IssmDouble* values,int M,int N,int step, IssmDouble time);
+		~DoubleMatExternalResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult managemnet: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _DOUBLEMATEXTERNALRESULT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleVecExternalResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleVecExternalResult.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleVecExternalResult.cpp	(revision 12878)
@@ -0,0 +1,152 @@
+/*!\file DoubleVecExternalResult.c
+ * \brief: implementation of the DoubleVecExternalResult object
+ */
+
+/*header files: */
+/*{{{*/
+#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 "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*DoubleVecExternalResult constructors and destructor*/
+/*FUNCTION DoubleVecExternalResult::DoubleVecExternalResult(){{{*/
+DoubleVecExternalResult::DoubleVecExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::DoubleVecExternalResult(int enum_type,IssmDoubleVec values,int M,int in_step,IssmDouble in_time){{{*/
+DoubleVecExternalResult::DoubleVecExternalResult(int in_id, int in_enum_type,IssmDouble* in_values, int in_M,int in_step,IssmDouble in_time){
+
+	id=in_id;
+	enum_type=in_enum_type;
+	M=in_M;
+
+	if(M){
+		values=xNew<IssmDouble>(M);
+		xMemCpy<IssmDouble>(values,in_values,M);
+	}
+	else values=NULL;
+
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::~DoubleVecExternalResult(){{{*/
+DoubleVecExternalResult::~DoubleVecExternalResult(){
+	xDelete<IssmDouble>(values);
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DoubleVecExternalResult::Echo {{{*/
+void DoubleVecExternalResult::Echo(void){
+
+	_printLine_("DoubleVecExternalResult:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   vector size: " << this->M);
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::DeepEcho{{{*/
+void DoubleVecExternalResult::DeepEcho(void){
+
+	int i;
+	
+	_printLine_("DoubleVecExternalResult:");
+	_printLine_("   id: " << this->id);
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   vector size: " << this->M);
+	for(i=0;i<this->M;i++){
+		_printLine_(i << " " << this->values[i]);
+	}
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::Id{{{*/
+int    DoubleVecExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::MyRank{{{*/
+int    DoubleVecExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::ObjectEnum{{{*/
+int DoubleVecExternalResult::ObjectEnum(void){
+
+	return DoubleVecExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::copy{{{*/
+Object* DoubleVecExternalResult::copy() {
+	
+	return new DoubleVecExternalResult(this->id,this->enum_type,this->values,this->M,this->step,this->time);
+
+}
+/*}}}*/
+
+/*DoubleVecExternalResult management: */
+/*FUNCTION DoubleVecExternalResult::WriteData{{{*/
+void   DoubleVecExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	int     size;
+	char   *name    = NULL;
+	extern  int my_rank;
+	IssmPDouble *passiveDouble_p=NULL;
+	IssmPDouble passiveDouble;
+
+	/*return if now on cpu 0: */
+	if(my_rank)return;
+
+	passiveDouble_p=xNew<IssmPDouble>(M);
+	/*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, type is 1, size is 1: */
+	type=1;
+	size=this->M;
+	fwrite(&type,sizeof(int),1,fid);
+	fwrite(&size,sizeof(int),1,fid);
+        for (int i=0; i<M; ++i) passiveDouble_p[i]=reCast<IssmPDouble>(values[i]);
+	fwrite(passiveDouble_p,size*sizeof(IssmPDouble),1,fid);
+        xDelete(passiveDouble_p);
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::GetResultName{{{*/
+void DoubleVecExternalResult::GetResultName(char** pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleVecExternalResult::GetStep{{{*/
+int DoubleVecExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleVecExternalResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleVecExternalResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/DoubleVecExternalResult.h	(revision 12878)
@@ -0,0 +1,55 @@
+/*! \file DoubleVecExternalResult.h 
+ */
+
+
+#ifndef _DOUBLEVECEXTERNALRESULT_H_
+#define _DOUBLEVECEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ExternalResult.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+class DoubleVecExternalResult: public ExternalResult{
+
+	private: 
+		int id;
+		int enum_type;
+		IssmDouble* values;
+		int M;
+		int step;
+		IssmDouble time;
+
+	public:
+		/*DoubleVecExternalResult constructors, destructors: {{{*/
+		DoubleVecExternalResult();
+		DoubleVecExternalResult(int id,int enum_type,IssmDouble* values,int M,int step, IssmDouble time);
+		~DoubleVecExternalResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult management: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _DOUBLEVECEXTERNALRESULT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/ExternalResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/ExternalResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/ExternalResult.h	(revision 12878)
@@ -0,0 +1,34 @@
+/*!\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 "../Object.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/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/IntExternalResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/IntExternalResult.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/IntExternalResult.cpp	(revision 12878)
@@ -0,0 +1,132 @@
+/*!\file IntExternalResult.c
+ * \brief: implementation of the IntExternalResult object
+ */
+
+/*header files: */
+/*{{{*/
+#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 "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*IntExternalResult constructors and destructor*/
+/*FUNCTION IntExternalResult::IntExternalResult(){{{*/
+IntExternalResult::IntExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::IntExternalResult(int in_id, int in_enum_type,int in_value,int in_step, IssmDouble in_time){{{*/
+IntExternalResult::IntExternalResult(int in_id, int in_enum_type,int 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;
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::~IntExternalResult(){{{*/
+IntExternalResult::~IntExternalResult(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION IntExternalResult::Echo {{{*/
+void IntExternalResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::DeepEcho{{{*/
+void IntExternalResult::DeepEcho(void){
+
+	_printLine_("IntExternalResult:");
+	_printLine_("   id: " << this->id);
+	_printLine_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " << this->value);
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::Id{{{*/
+int    IntExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntExternalResult::MyRank{{{*/
+int    IntExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::ObjectEnum{{{*/
+int IntExternalResult::ObjectEnum(void){
+
+	return IntExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::copy{{{*/
+Object* IntExternalResult::copy() {
+	
+	return new IntExternalResult(this->id,this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*IntExternalResult management: */
+/*FUNCTION IntExternalResult::WriteData{{{*/
+void   IntExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	int     size;
+	char   *name    = NULL;
+	IssmPDouble  passiveDouble;
+	extern  int my_rank;
+
+	/*return if now on cpu 0: */
+	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 IssmPDouble, 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);
+
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::GetResultName{{{*/
+void IntExternalResult::GetResultName(char** pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION IntExternalResult::GetStep{{{*/
+int IntExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/IntExternalResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/IntExternalResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/IntExternalResult.h	(revision 12878)
@@ -0,0 +1,54 @@
+/*! \file IntExternalResult.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _INTEXTERNALRESULT_H_
+#define _INTEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ExternalResult.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+/*}}}*/
+
+class IntExternalResult: public ExternalResult{
+
+	public:
+		int    id;
+		int    enum_type;
+		int    value;
+		int    step;
+		IssmDouble time;
+
+
+		/*IntExternalResult constructors, destructors: {{{*/
+		IntExternalResult();
+		IntExternalResult(int id,int enum_type,int value,int step,IssmDouble time);
+		~IntExternalResult();
+
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult managemnet: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _INTEXTERNALRESULT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/PetscVecExternalResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/PetscVecExternalResult.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/PetscVecExternalResult.cpp	(revision 12878)
@@ -0,0 +1,149 @@
+/*!\file PetscVecExternalResult.c
+ * \brief: implementation of the PetscVecExternalResult object
+ */
+
+/*header files: */
+/*{{{*/
+#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 "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*PetscVecExternalResult constructors and destructor*/
+/*FUNCTION PetscVecExternalResult::PetscVecExternalResult(){{{*/
+PetscVecExternalResult::PetscVecExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::PetscVecExternalResult(int enum_type,IssmPetscVec value){{{*/
+PetscVecExternalResult::PetscVecExternalResult(int in_id, int in_enum_type,Vector* in_value,int in_step, IssmDouble in_time){
+
+	id=in_id;
+	enum_type=in_enum_type;
+
+	value=NULL;
+
+	if(in_value){
+		value=in_value->Duplicate();
+		in_value->Copy(value);
+	}
+	else value=NULL;
+
+	step=in_step;
+	time=in_time;
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::~PetscVecExternalResult(){{{*/
+PetscVecExternalResult::~PetscVecExternalResult(){
+	VecFree(&value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION PetscVecExternalResult::Echo {{{*/
+void PetscVecExternalResult::Echo(void){
+
+	_printLine_("PetscVecExternalResult:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::DeepEcho{{{*/
+void PetscVecExternalResult::DeepEcho(void){
+
+	int i;
+	_printLine_("PetscVecExternalResult:");
+	_printLine_("   id: " << this->id);
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+	VecView(value,PETSC_VIEWER_STDOUT_WORLD);
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::Id{{{*/
+int    PetscVecExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::MyRank{{{*/
+int    PetscVecExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::ObjectEnum{{{*/
+int PetscVecExternalResult::ObjectEnum(void){
+
+	return PetscVecExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::copy{{{*/
+Object* PetscVecExternalResult::copy() {
+	
+	return new PetscVecExternalResult(this->id,this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*PetscVecExternalResult management: */
+/*FUNCTION PetscVecExternalResult::WriteData{{{*/
+void   PetscVecExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	int     size;
+	char   *name      = NULL;
+	IssmPDouble *serialvec = NULL;
+	extern int my_rank;
+	IssmPDouble passiveDouble;
+
+	/*serialize: */
+	VecGetSize(this->value,&size);
+	VecToMPISerial(&serialvec,this->value);
+
+	/*now, exit if we are not on cpu 0: */
+	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, type is 1, size is 1: */
+	type=1;
+	
+	fwrite(&type,sizeof(int),1,fid);
+	fwrite(&size,sizeof(int),1,fid);
+	fwrite(serialvec,size*sizeof(IssmPDouble),1,fid);
+
+	/*Free ressources:*/
+	xDelete<IssmPDouble>(serialvec);
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::GetResultName{{{*/
+void PetscVecExternalResult::GetResultName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION PetscVecExternalResult::GetStep{{{*/
+int PetscVecExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/PetscVecExternalResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/PetscVecExternalResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/PetscVecExternalResult.h	(revision 12878)
@@ -0,0 +1,55 @@
+/*! \file PetscVecExternalResult.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _PETSCVECEXTERNALRESULT_H_
+#define _PETSCVECEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ExternalResult.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+class PetscVecExternalResult: public ExternalResult{
+
+	private: 
+		int id;
+		int enum_type;
+		Vector* value;
+		int step;
+		IssmDouble time;
+
+	public:
+		/*PetscVecExternalResult constructors, destructors: {{{*/
+		PetscVecExternalResult();
+		PetscVecExternalResult(int id,int enum_type,Vector* value, int step, IssmDouble time);
+		~PetscVecExternalResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult management: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _PETSCVECEXTERNALRESULT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/StringExternalResult.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/StringExternalResult.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/StringExternalResult.cpp	(revision 12878)
@@ -0,0 +1,132 @@
+/*!\file StringExternalResult.c
+ * \brief: implementation of the StringExternalResult object
+ */
+
+/*header files: */
+/*{{{*/
+#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 "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*StringExternalResult constructors and destructor*/
+/*FUNCTION StringExternalResult::StringExternalResult(){{{*/
+StringExternalResult::StringExternalResult(){
+	return;
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::StringExternalResult(int enum_type,IssmString value){{{*/
+StringExternalResult::StringExternalResult(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;
+	
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::~StringExternalResult(){{{*/
+StringExternalResult::~StringExternalResult(){
+	xDelete<char>(value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION StringExternalResult::Echo {{{*/
+void StringExternalResult::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::DeepEcho{{{*/
+void StringExternalResult::DeepEcho(void){
+
+	_printLine_("StringExternalResult:");
+	_printLine_("   id: " << this->id);
+	_printLine_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " << this->value);
+	_printLine_("   step: " << this->step);
+	_printLine_("   time: " << this->time);
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::Id{{{*/
+int    StringExternalResult::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION StringExternalResult::MyRank{{{*/
+int    StringExternalResult::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::ObjectEnum{{{*/
+int StringExternalResult::ObjectEnum(void){
+
+	return StringExternalResultEnum;
+
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::copy{{{*/
+Object* StringExternalResult::copy() {
+	
+	return new StringExternalResult(this->id,this->enum_type,this->value,this->step,this->time);
+
+}
+/*}}}*/
+
+/*StringExternalResult management: */
+/*FUNCTION StringExternalResult::WriteData{{{*/
+void   StringExternalResult::WriteData(FILE* fid,bool io_gather){
+
+	int     length;
+	int     type;
+	char   *name      = NULL;
+	extern  int my_rank;
+        IssmPDouble passiveDouble;
+
+	/*return if now on cpu 0: */
+	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 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);
+
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::GetResultName{{{*/
+void StringExternalResult::GetResultName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION StringExternalResult::GetStep{{{*/
+int StringExternalResult::GetStep(void){
+
+	return this->step;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/StringExternalResult.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/StringExternalResult.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/ExternalResults/StringExternalResult.h	(revision 12878)
@@ -0,0 +1,55 @@
+/*! \file StringExternalResult.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _STRINGEXTERNALRESULT_H_
+#define _STRINGEXTERNALRESULT_H_
+
+/*Headers:*/
+/*{{{*/
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ExternalResult.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+class StringExternalResult: public ExternalResult{
+
+	private: 
+		int    id;
+		int    enum_type;
+		char*  value;
+		int    step;
+		IssmDouble time;
+
+	public:
+		/*StringExternalResult constructors, destructors: {{{*/
+		StringExternalResult();
+		StringExternalResult(int id,int enum_type,char* value,int step, IssmDouble time);
+		~StringExternalResult();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ExternalResult management: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  WriteData(FILE* fid,bool io_gather);
+		void  GetResultName(char**);
+		int   GetStep(void);
+		/*}}}*/
+};
+#endif  /* _STRINGEXTERNALRESULT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/BoolInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/BoolInput.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/BoolInput.cpp	(revision 12878)
@@ -0,0 +1,193 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+
+/*BoolInput constructors and destructor*/
+/*FUNCTION BoolInput::BoolInput(){{{*/
+BoolInput::BoolInput(){
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolInput::BoolInput(IssmDouble* values){{{*/
+BoolInput::BoolInput(int in_enum_type,IssmBool 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){
+
+	_printLine_("BoolInput:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " <<(value?"true":"false"));
+}
+/*}}}*/
+/*FUNCTION BoolInput::Id{{{*/
+int    BoolInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION BoolInput::MyRank{{{*/
+int    BoolInput::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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){_error2_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue){{{*/
+void BoolInput::GetInputValue(IssmDouble* pvalue){_error2_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void BoolInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error2_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
+void BoolInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error2_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error2_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::ChangeEnum{{{*/
+void BoolInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION BoolInput::SquareMin{{{*/
+void BoolInput::SquareMin(IssmDouble* psquaremin, bool process_units,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:
+			_error2_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::Extrude{{{*/
+void BoolInput::Extrude(void){
+
+	/*do nothing*/
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolInput::GetVectorFromInputs{{{*/
+void BoolInput::GetVectorFromInputs(Vector* vector,int* doflist){
+
+	_error2_("not supporte yet!");
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::GetValuesPtr{{{*/
+void BoolInput::GetValuesPtr(IssmDouble** pvalues,int* pnum_values){
+
+	_error2_("not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::Configure{{{*/
+void BoolInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/BoolInput.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/BoolInput.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/BoolInput.h	(revision 12878)
@@ -0,0 +1,85 @@
+/*! \file BoolInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _BOOLINPUT_H_
+#define _BOOLINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../../../include/include.h"
+class GaussTria;
+/*}}}*/
+
+class BoolInput: public Input{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int    enum_type;
+		IssmBool value;
+
+		/*BoolInput constructors, destructors: {{{*/
+		BoolInput();
+		BoolInput(int enum_type,IssmBool value);
+		~BoolInput();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*BoolInput management: {{{*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error2_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error2_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error2_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		void Configure(Parameters* parameters);
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error2_("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){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("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){_error2_("not implemented yet");};
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum){_error2_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error2_("InfinityNorm not implemented for booleans");};
+		IssmDouble Max(void){_error2_("Max not implemented for booleans");};
+		IssmDouble MaxAbs(void){_error2_("Max not implemented for booleans");};
+		IssmDouble Min(void){_error2_("Min not implemented for booleans");};
+		IssmDouble MinAbs(void){_error2_("Min not implemented for booleans");};
+		void Scale(IssmDouble scale_factor);
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error2_("Constrain not implemented for booleans");};
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input){_error2_("not supported yet");};
+		void GetVectorFromInputs(Vector* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _BOOLINPUT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/ControlInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/ControlInput.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/ControlInput.cpp	(revision 12878)
@@ -0,0 +1,282 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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 TriaP1InputEnum:
+			values     =new TriaP1Input(enum_type,pvalues);
+			savedvalues=new TriaP1Input(enum_type,pvalues);
+			minvalues  =new TriaP1Input(enum_type,pmin);
+			maxvalues  =new TriaP1Input(enum_type,pmax);
+			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:
+			_error2_("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){
+
+	_printLine_("ControlInput:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("---values: ");     if (values)      values->Echo();
+	_printLine_("---savedvalues: ");if (savedvalues) savedvalues->Echo();
+	_printLine_("---minvalues: ");  if (minvalues)   minvalues->Echo();
+	_printLine_("---maxvalues: ");  if (maxvalues)   maxvalues->Echo();
+	_printLine_("---gradient: ");   if (gradient)    gradient->Echo();
+}
+/*}}}*/
+/*FUNCTION ControlInput::Id{{{*/
+int    ControlInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION ControlInput::MyRank{{{*/
+int    ControlInput::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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=(Input*)this->values->copy();
+	if(savedvalues) output->savedvalues=(Input*)this->savedvalues->copy();
+	if(minvalues)   output->minvalues=(Input*)this->minvalues->copy();
+	if(maxvalues)   output->maxvalues=(Input*)this->maxvalues->copy();
+	if(gradient)    output->gradient=(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* gradient_vec,int* doflist){
+	if(gradient) gradient->GetVectorFromInputs(gradient_vec,doflist);
+}/*}}}*/
+/*FUNCTION ControlInput::ScaleGradient{{{*/
+void ControlInput::ScaleGradient(IssmDouble scaling_factor){
+	if(!gradient) _error2_("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:
+			_error2_("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* vector,int* doflist){{{*/
+void ControlInput::GetVectorFromInputs(Vector* vector,int* doflist){
+	values->GetVectorFromInputs(vector,doflist);
+}/*}}}*/
+/*FUNCTION ControlInput::GetVectorFromInputs(Vector* vector,int* doflist,const char* data){{{*/
+void ControlInput::GetVectorFromInputs(Vector* 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{
+		 _error2_("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) _error2_("Values of " << EnumToStringx(this->enum_type) << " not found");
+
+	if(savedvalues) delete this->savedvalues;
+	this->savedvalues=(Input*)this->values->copy();
+}/*}}}*/
+/*FUNCTION ControlInput::UpdateValue{{{*/
+void ControlInput::UpdateValue(IssmDouble scalar){
+	if(!gradient)    _error2_("Gradient of " << EnumToStringx(this->enum_type) << " not found");
+	if(!savedvalues) _error2_("Values of " << EnumToStringx(this->enum_type) << " not found");
+
+	if(values) delete this->values;
+	this->values=(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/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/ControlInput.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/ControlInput.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/ControlInput.h	(revision 12878)
@@ -0,0 +1,98 @@
+/*! \file ControlInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _CONTROLINPUT_H_
+#define _CONTROLINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../../../include/include.h"
+class GaussTria;
+/*}}}*/
+
+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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*ControlInput management: {{{*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error2_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error2_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error2_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error2_("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){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("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 GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void ChangeEnum(int newenumtype){_error2_("not implemented yet");};
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters){_error2_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error2_("not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error2_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar){_error2_("not implemented yet");};
+		void Constrain(void);
+		void Constrain(IssmDouble min,IssmDouble max);
+		IssmDouble InfinityNorm(void){_error2_("not implemented yet");};
+		IssmDouble Max(void){_error2_("not implemented yet");};
+		IssmDouble MaxAbs(void){_error2_("not implemented yet");};
+		IssmDouble Min(void){_error2_("not implemented yet");};
+		IssmDouble MinAbs(void){_error2_("not implemented yet");};
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vector* vector,int* doflist,const char* data);
+		void GetVectorFromInputs(Vector* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values){_error2_("not implemented yet");};
+		ElementResult* SpawnGradient(int step, IssmDouble time);
+		void GetGradient(Vector* 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/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DatasetInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DatasetInput.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DatasetInput.cpp	(revision 12878)
@@ -0,0 +1,122 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("DatasetInput:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("---inputs: "); inputs->Echo();
+}
+/*}}}*/
+/*FUNCTION DatasetInput::Id{{{*/
+int    DatasetInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DatasetInput::MyRank{{{*/
+int    DatasetInput::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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=(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) _error2_("index requested (" << index << ") exceeds dataset size (" << inputs->Size() << ")");
+	Input* input=(Input*)this->inputs->GetObjectByOffset(index);
+	
+	input->GetInputValue(pvalue,gauss);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DatasetInput.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DatasetInput.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DatasetInput.h	(revision 12878)
@@ -0,0 +1,92 @@
+/*! \file DatasetInput.h 
+ *  \brief: header file for datasetinput object
+ */
+
+
+#ifndef _DATASETINPUT_H_
+#define _DATASETINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../../../include/include.h"
+class GaussTria;
+/*}}}*/
+
+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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*DatasetInput management: {{{*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error2_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error2_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error2_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time){_error2_("not implemented yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error2_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue){_error2_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue){_error2_("not implemented yet");};
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void ChangeEnum(int newenumtype){_error2_("not implemented yet");};
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters){_error2_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error2_("not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error2_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar){_error2_("not implemented yet");};
+		void Constrain(void){_error2_("not implemented yet");};
+		void Constrain(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error2_("not implemented yet");};
+		IssmDouble Max(void){_error2_("not implemented yet");};
+		IssmDouble MaxAbs(void){_error2_("not implemented yet");};
+		IssmDouble Min(void){_error2_("not implemented yet");};
+		IssmDouble MinAbs(void){_error2_("not implemented yet");};
+		void Extrude(void){_error2_("not implemented yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error2_("not implemented yet");};
+		void GetVectorFromInputs(Vector* vector,int* doflist){_error2_("not implemented yet");};
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values){_error2_("not implemented yet");};
+		ElementResult* SpawnGradient(int step, IssmDouble time){_error2_("not implemented yet");};
+		void GetGradient(Vector* gradient_vec,int* doflist){_error2_("not implemented yet");};
+		void ScaleGradient(IssmDouble scale){_error2_("not implemented yet");};
+		void SetGradient(Input* gradient_in){_error2_("not implemented yet");};
+		void UpdateValue(IssmDouble scalar){_error2_("not implemented yet");};
+		void SaveValue(void){_error2_("not implemented yet");};
+		/*}}}*/
+
+};
+#endif  /* _DATASETINPUT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DoubleInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DoubleInput.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DoubleInput.cpp	(revision 12878)
@@ -0,0 +1,359 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("DoubleInput:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " << this->value);
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Id{{{*/
+int    DoubleInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleInput::MyRank{{{*/
+int    DoubleInput::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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){
+	_error2_("Double input of enum " << EnumToStringx(enum_type) << " cannot return a boolean");
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(int* pvalue){{{*/
+void DoubleInput::GetInputValue(int* pvalue){
+	_error2_("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){_error2_("not supported yet!");}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error2_("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, bool process_units,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:
+			_error2_("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* vector,int* doflist){
+
+	_error2_("not supporte yet!");
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetValuesPtr{{{*/
+void DoubleInput::GetValuesPtr(IssmDouble** pvalues,int* pnum_values){
+
+	_error2_("not supported 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) _error2_("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:
+			_error2_("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/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DoubleInput.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DoubleInput.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/DoubleInput.h	(revision 12878)
@@ -0,0 +1,84 @@
+/*! \file DoubleInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _DOUBLEINPUT_H_
+#define _DOUBLEINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../../../include/include.h"
+class GaussTria;
+/*}}}*/
+
+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   MyRank();
+		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){_error2_("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){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("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 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, bool process_units,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum);
+		void Scale(IssmDouble scale_factor);
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
+		IssmDouble InfinityNorm(void){_error2_("not implemented yet");};
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void){_error2_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vector* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _DOUBLEINPUT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/Input.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/Input.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/Input.h	(revision 12878)
@@ -0,0 +1,69 @@
+/*!\file:  Input.h
+ * \brief abstract class for Input object
+ */ 
+
+
+#ifndef _INPUT_H_
+#define _INPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../Object.h"
+class Node;
+class ElementResult;
+class GaussTria;
+class Parameters;
+/*}}}*/
+
+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 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, bool process_units,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* vector,int* doflist)=0;
+		virtual void   GetValuesPtr(IssmDouble** pvalues,int* pnum_values)=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/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/IntInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/IntInput.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/IntInput.cpp	(revision 12878)
@@ -0,0 +1,199 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("IntInput:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " << (int)this->value);
+}
+/*}}}*/
+/*FUNCTION IntInput::Id{{{*/
+int    IntInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntInput::MyRank{{{*/
+int    IntInput::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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){
+	
+	_error2_("not supported yet!");
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION IntInput::GetInputValue(bool* pvalue) {{{*/
+void IntInput::GetInputValue(bool* pvalue){_error2_("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){
+	_error2_("IntInput cannot return a IssmDouble in parallel");
+}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void IntInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error2_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
+void IntInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error2_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error2_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::ChangeEnum{{{*/
+void IntInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION IntInput::SquareMin{{{*/
+void IntInput::SquareMin(IssmDouble* psquaremin, bool process_units,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:
+			_error2_("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* vector,int* doflist){
+
+	_error2_("not supporte yet!");
+
+}
+/*}}}*/
+/*FUNCTION IntInput::GetValuesPtr{{{*/
+void IntInput::GetValuesPtr(IssmDouble** pvalues,int* pnum_values){
+
+	_error2_("not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION IntInput::Configure{{{*/
+void IntInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/IntInput.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/IntInput.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/IntInput.h	(revision 12878)
@@ -0,0 +1,85 @@
+/*! \file IntInput.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+
+#ifndef _INTINPUT_H_
+#define _INTINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../../../include/include.h"
+class GaussTria;
+/*}}}*/
+
+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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*IntInput management: {{{*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error2_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error2_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error2_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error2_("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){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("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){_error2_("not implemented yet");};
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum){_error2_("not implemented yet");};
+		void Scale(IssmDouble scale_factor);
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
+		IssmDouble InfinityNorm(void){_error2_("InfinityNorm not implemented for integers");};
+		IssmDouble Max(void){_error2_("Max not implemented for integers");};
+		IssmDouble MaxAbs(void){_error2_("Max not implemented for integers");};
+		IssmDouble Min(void){_error2_("Min not implemented for integers");};
+		IssmDouble MinAbs(void){_error2_("Min not implemented for integers");};
+		void Extrude(void){_error2_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error2_("not supported yet");};
+		void GetVectorFromInputs(Vector* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _INTINPUT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/PentaP1Input.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/PentaP1Input.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/PentaP1Input.cpp	(revision 12878)
@@ -0,0 +1,629 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("PentaP1Input:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   values: [" << this->values[0] << " " << this->values[1] << " " << this->values[2] << " " << this->values[3] << " " << this->values[4] << " " << this->values[5] << "]");
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::Id{{{*/
+int    PentaP1Input::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION PentaP1Input::MyRank{{{*/
+int    PentaP1Input::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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*/
+	TriaP1Input* 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 TriaP1Input(this->enum_type,&newvalues[0]);
+
+	/*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, bool process_units,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];
+
+	/*Process units if requested: */
+	if(process_units)UnitConversion(&valuescopy[0],numnodes,IuToExtEnum,enum_type);
+
+	/*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) _error2_("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:
+			_error2_("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){
+
+	/*Intermediaries*/
+	int i;
+	const int  numnodes = 6;
+	int        num_thickness_values;
+	IssmDouble    *thickness_values = NULL;
+
+	/*Check that input provided is a thickness*/
+	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error2_("Input provided is not a Thickness (enum_type is " << EnumToStringx(thickness_input->InstanceEnum()) << ")");
+
+	/*Get Thickness value pointer*/
+	thickness_input->GetValuesPtr(&thickness_values,&num_thickness_values);
+
+	/*vertically integrate depending on type:*/
+	switch(thickness_input->ObjectEnum()){
+
+		case PentaP1InputEnum:
+			for(i=0;i<3;i++){
+				this->values[i]=0.5*(this->values[i]+this->values[i+3]) * thickness_values[i];
+				this->values[i+3]=this->values[i];
+			}
+			return;
+
+		default:
+			_error2_("not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::PointwiseDivide{{{*/
+Input* PentaP1Input::PointwiseDivide(Input* inputB){
+
+	/*Ouput*/
+	PentaP1Input* outinput=NULL;
+
+	/*Intermediaries*/
+	int               i;
+	PentaP1Input *xinputB     = NULL;
+	int               B_numvalues;
+	const int         numnodes    = 6;
+	IssmDouble            AdotBvalues[numnodes];
+
+	/*Check that inputB is of the same type*/
+	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error2_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(PentaP1Input*)inputB;
+
+	/*Create point wise sum*/
+	for(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;
+	int               B_numvalues;
+	const int         numnodes    = 6;
+	IssmDouble            minvalues[numnodes];
+
+	/*Check that inputB is of the same type*/
+	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error2_("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;
+	int               B_numvalues;
+	const int         numnodes    = 6;
+	IssmDouble            maxvalues[numnodes];
+
+	/*Check that inputB is of the same type*/
+	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error2_("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* vector,int* doflist){
+
+	const int numvertices=6;
+	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
+
+} /*}}}*/
+/*FUNCTION PentaP1Input::GetValuesPtr{{{*/
+void PentaP1Input::GetValuesPtr(IssmDouble** pvalues,int* pnum_values){
+
+	*pvalues=this->values;
+	*pnum_values=6;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::Configure{{{*/
+void PentaP1Input::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/PentaP1Input.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/PentaP1Input.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/PentaP1Input.h	(revision 12878)
@@ -0,0 +1,86 @@
+/*! \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 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   MyRank();
+		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){_error2_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue){_error2_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error2_("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, bool process_units,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum);
+		void Scale(IssmDouble scale_factor);
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("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* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _PENTAP1INPUT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TransientInput.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TransientInput.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TransientInput.cpp	(revision 12878)
@@ -0,0 +1,486 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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<IssmDouble>(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;
+
+	_printLine_("TransientInput:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   numtimesteps: " << this->numtimesteps);
+	_printLine_("---inputs: "); 
+	for(i=0;i<this->numtimesteps;i++){
+		_printLine_("   time: " << this->timesteps[i] << "  ");
+		((Input*)this->inputs->GetObjectByOffset(i))->Echo();
+	}
+}
+/*}}}*/
+/*FUNCTION TransientInput::Id{{{*/
+int    TransientInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION TransientInput::MyRank{{{*/
+int    TransientInput::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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);
+   memcpy(output->timesteps,this->timesteps,this->numtimesteps*sizeof(IssmDouble));
+	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);
+	memcpy(outinput->timesteps,this->timesteps,this->numtimesteps*sizeof(IssmDouble));
+	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;
+
+}
+/*}}}*/
+
+/*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]) _assert_("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);
+		memcpy(old_timesteps,this->timesteps,this->numtimesteps*sizeof(IssmDouble));
+		xDelete<IssmDouble>(this->timesteps); 
+	}
+
+	this->numtimesteps=this->numtimesteps+1;
+	this->timesteps=xNew<IssmDouble>(this->numtimesteps);
+
+	if (this->numtimesteps > 1){
+		memcpy(this->timesteps,old_timesteps,(this->numtimesteps-1)*sizeof(IssmDouble));
+		xDelete<IssmDouble>(old_timesteps);
+	}
+
+	/*go ahead and plug: */
+	this->timesteps[this->numtimesteps-1]=time;
+	inputs->AddObject(input);
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::SquareMin{{{*/
+void TransientInput::SquareMin(IssmDouble* psquaremin, bool process_units,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,process_units,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* 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){
+
+	int     i,j;
+	IssmDouble  deltat;
+	IssmDouble  alpha1,alpha2;
+	bool    found=false;
+	Input*  input=NULL;
+	Input*  input1=NULL;
+	Input*  input2=NULL;
+
+	/*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(intime<this->timesteps[0]){
+		/*get values for the first time: */
+		input=(Input*)((Input*)this->inputs->GetObjectByOffset(0))->copy();
+		found=true;
+	}
+	else if(intime>this->timesteps[this->numtimesteps-1]){
+		/*get values for the last time: */
+		input=(Input*)((Input*)this->inputs->GetObjectByOffset(numtimesteps-1))->copy();
+		found=true;
+	}
+	else{
+		/*Find which interval we fall within: */
+		for(i=0;i<this->numtimesteps;i++){
+			if(intime==this->timesteps[i]){
+				/*We are right on one step time: */
+				input=(Input*)((Input*)this->inputs->GetObjectByOffset(i))->copy();
+				found=true;
+				break; //we are done with the time interpolation.
+			}
+			else{
+				if(this->timesteps[i]<intime && intime<this->timesteps[i+1]){
+					/*ok, we have the interval ]i:i+1[. Interpolate linearly for now: */
+					deltat=this->timesteps[i+1]-this->timesteps[i];
+					alpha2=(intime-this->timesteps[i])/deltat;
+					alpha1=(1.0-alpha2);
+
+					input1=(Input*)this->inputs->GetObjectByOffset(i); 
+					input2=(Input*)this->inputs->GetObjectByOffset(i+1);
+
+					input=(Input*)input1->copy();
+					input->Scale(alpha1);
+					input->AXPY(input2,alpha2);
+
+					found=true;
+					break;
+				}
+				else continue; //keep looking on the next interval
+			}
+		}
+	}
+	if(!found)_error2_("did not find time interval on which to interpolate forcing values!");
+
+	/*Assign output pointer*/
+	return input;
+}
+/*}}}*/
+/*FUNCTION TransientInput::Configure{{{*/
+void TransientInput::Configure(Parameters* parameters){
+	this->parameters=parameters;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TransientInput.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TransientInput.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TransientInput.h	(revision 12878)
@@ -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 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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*TransientInput management: {{{*/
+		int    InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* forcingB){_error2_("not implemented yet");};
+		Input* PointwiseMin(Input* forcingB){_error2_("not implemented yet");};
+		Input* PointwiseMax(Input* forcingB){_error2_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue){_error2_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue){_error2_("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){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum){_error2_("not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error2_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error2_("not implemented yet");};
+		void AXPY(Input* xforcing,IssmDouble scalar){_error2_("not implemented yet");};
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error2_("not implemented yet");};
+		IssmDouble InfinityNorm(void);
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void){_error2_("not supported yet");}
+		void VerticallyIntegrate(Input* thickness_forcing){_error2_("not supported yet");};
+		void GetVectorFromInputs(Vector* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values){_error2_("not supported yet");};
+      void GetTimeValues(IssmDouble* values,IssmDouble time){_error2_("not implemented yet");};
+		Input* GetTimeInput(IssmDouble time);
+		/*}}}*/
+
+};
+#endif  /* _TRANSIENTINPUT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TriaP1Input.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TriaP1Input.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TriaP1Input.cpp	(revision 12878)
@@ -0,0 +1,422 @@
+/*!\file TriaP1Input.c
+ * \brief: implementation of the TriaP1Input object
+ */
+
+#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 "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+
+/*TriaP1Input constructors and destructor*/
+/*FUNCTION TriaP1Input::TriaP1Input(){{{*/
+TriaP1Input::TriaP1Input(){
+	return;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::TriaP1Input(int in_enum_type,IssmDouble* values){{{*/
+TriaP1Input::TriaP1Input(int in_enum_type,IssmDouble* in_values)
+	:TriaRef(1)
+{
+
+	/*Set TriaRef*/
+	this->SetElementType(P1Enum,0);
+	this->element_type=P1Enum;
+
+	/*Set Enum*/
+	enum_type=in_enum_type;
+
+	/*Set values*/
+	values[0]=in_values[0];
+	values[1]=in_values[1];
+	values[2]=in_values[2];
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::~TriaP1Input(){{{*/
+TriaP1Input::~TriaP1Input(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION TriaP1Input::Echo {{{*/
+void TriaP1Input::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::DeepEcho{{{*/
+void TriaP1Input::DeepEcho(void){
+
+	_printLine_("TriaP1Input:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   values: [" << this->values[0] << " " << this->values[1] << " " << this->values[2] << "]");
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Id{{{*/
+int    TriaP1Input::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION TriaP1Input::MyRank{{{*/
+int    TriaP1Input::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::ObjectEnum{{{*/
+int TriaP1Input::ObjectEnum(void){
+
+	return TriaP1InputEnum;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::copy{{{*/
+Object* TriaP1Input::copy() {
+	
+	return new TriaP1Input(this->enum_type,this->values);
+
+}
+/*}}}*/
+	
+/*TriaP1Input management*/
+/*FUNCTION TriaP1Input::InstanceEnum{{{*/
+int TriaP1Input::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::SpawnTriaInput{{{*/
+Input* TriaP1Input::SpawnTriaInput(int* indices){
+
+	/*output*/
+	TriaP1Input* outinput=NULL;
+
+	/*Create new Tria input (copy of current input)*/
+	outinput=new TriaP1Input(this->enum_type,&this->values[0]);
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::SpawnResult{{{*/
+ElementResult* TriaP1Input::SpawnResult(int step, IssmDouble time){
+
+	return new TriaP1ElementResult(this->enum_type,this->values,step,time);
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION TriaP1Input::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void TriaP1Input::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){
+
+	/*Call TriaRef function*/
+	TriaRef::GetInputValue(pvalue,&values[0],gauss);
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void TriaP1Input::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussTria* gauss){
+
+	/*Call TriaRef function*/
+	TriaRef::GetInputDerivativeValue(p,&values[0],xyz_list,gauss);
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::GetVxStrainRate2d{{{*/
+void TriaP1Input::GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){
+
+	/*Intermediary*/
+	int       i;
+	const int numnodes=3;
+	IssmDouble B[3][NDOF2*numnodes];
+	IssmDouble velocity[3][NDOF2];
+
+	/*Get B matrix: */
+	GetBMacAyeal(&B[0][0], xyz_list, gauss);
+
+	/*Here, we are computing the strain rate of (vx,0)*/
+	for(i=0;i<3;i++){
+		velocity[i][0]=this->values[i];
+		velocity[i][1]=0.0;
+	}
+	/*Get epsilon(vx) = B*velocity*/
+	MatrixMultiply( &B[0][0],3,NDOF2*numnodes,0,
+				&velocity[0][0],NDOF2*numnodes,1,0,
+				epsilonvx,0);
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::GetVyStrainRate2d{{{*/
+void TriaP1Input::GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){
+
+	/*Intermediary*/
+	int       i;
+	const int numnodes=3;
+	IssmDouble B[3][NDOF2*numnodes];
+	IssmDouble velocity[3][NDOF2];
+
+	/*Get B matrix: */
+	GetBMacAyeal(&B[0][0], xyz_list, gauss);
+
+	/*Here, we are computing the strain rate of (0,vy)*/
+	for(i=0;i<3;i++){
+		velocity[i][0]=0.0;
+		velocity[i][1]=this->values[i];
+	}
+	/*Get epsilon(vy) = B*velocity*/
+	MatrixMultiply( &B[0][0],3,NDOF2*numnodes,0,
+				&velocity[0][0],NDOF2*numnodes,1,0,
+				epsilonvy,0);
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::ChangeEnum{{{*/
+void TriaP1Input::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::GetInputAverage{{{*/
+void TriaP1Input::GetInputAverage(IssmDouble* pvalue){
+	*pvalue=1./3.*(values[0]+values[1]+values[2]);
+}
+/*}}}*/
+
+/*Intermediary*/
+/*FUNCTION TriaP1Input::SquareMin{{{*/
+void TriaP1Input::SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters){
+
+	int i;
+	const int numnodes=3;
+	IssmDouble valuescopy[numnodes];
+	IssmDouble squaremin;
+
+	/*First,  copy values, to process units if requested: */
+	for(i=0;i<numnodes;i++)valuescopy[i]=this->values[i];
+
+	/*Process units if requested: */
+	if(process_units)UnitConversion(&valuescopy[0],numnodes,IuToExtEnum,enum_type);
+
+	/*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 TriaP1Input::ContrainMin{{{*/
+void TriaP1Input::ConstrainMin(IssmDouble minimum){
+	
+	int i;
+	const int numnodes=3;
+
+	for(i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::InfinityNorm{{{*/
+IssmDouble TriaP1Input::InfinityNorm(void){
+
+	/*Output*/
+	IssmDouble norm=0;
+	const int numnodes=3;
+
+	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
+	return norm;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Max{{{*/
+IssmDouble TriaP1Input::Max(void){
+
+	const int numnodes=3;
+	IssmDouble    max=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]>max) max=values[i];
+	}
+	return max;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::MaxAbs{{{*/
+IssmDouble TriaP1Input::MaxAbs(void){
+
+	const int numnodes=3;
+	IssmDouble    max=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])>max) max=fabs(values[i]);
+	}
+	return max;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Min{{{*/
+IssmDouble TriaP1Input::Min(void){
+
+	const int numnodes=3;
+	IssmDouble    min=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]<min) min=values[i];
+	}
+	return min;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::MinAbs{{{*/
+IssmDouble TriaP1Input::MinAbs(void){
+
+	const int numnodes=3;
+	IssmDouble    min=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])<min) min=fabs(values[i]);
+	}
+	return min;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Scale{{{*/
+void TriaP1Input::Scale(IssmDouble scale_factor){
+	
+	int i;
+	const int numnodes=3;
+
+	for(i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::ArtificialNoise{{{*/
+void TriaP1Input::ArtificialNoise(IssmDouble min,IssmDouble max){
+
+	int i;
+	const int numnodes=3;
+	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 TriaP1Input::AXPY{{{*/
+void TriaP1Input::AXPY(Input* xinput,IssmDouble scalar){
+
+	int i;
+	const int numnodes=3;
+	TriaP1Input*  xtriavertexinput=NULL;
+
+	/*xinput is of the same type, so cast it: */
+	xtriavertexinput=(TriaP1Input*)xinput;
+
+	/*Carry out the AXPY operation depending on type:*/
+	switch(xinput->ObjectEnum()){
+
+		case TriaP1InputEnum :
+			for(i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*xtriavertexinput->values[i];
+			return;
+
+		default :
+			_error2_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Constrain{{{*/
+void TriaP1Input::Constrain(IssmDouble cm_min, IssmDouble cm_max){
+
+	int i;
+	const int numnodes=3;
+		
+	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 TriaP1Input::GetVectorFromInputs{{{*/
+void TriaP1Input::GetVectorFromInputs(Vector* vector,int* doflist){
+
+	const int numvertices=3;
+	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
+
+} /*}}}*/
+/*FUNCTION TriaP1Input::GetValuesPtr{{{*/
+void TriaP1Input::GetValuesPtr(IssmDouble** pvalues,int* pnum_values){
+
+	*pvalues=this->values;
+	if(pnum_values)*pnum_values=3;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::PointwiseMin{{{*/
+Input* TriaP1Input::PointwiseMin(Input* inputB){
+
+	/*Ouput*/
+	TriaP1Input* outinput=NULL;
+
+	/*Intermediaries*/
+	int               i;
+	TriaP1Input *xinputB     = NULL;
+	int               B_numvalues;
+	const int         numnodes    = 3;
+	IssmDouble            minvalues[numnodes];
+
+	/*Check that inputB is of the same type*/
+	if (inputB->ObjectEnum()!=TriaP1InputEnum) _error2_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(TriaP1Input*)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 Tria vertex input (copy of current input)*/
+	outinput=new TriaP1Input(this->enum_type,&minvalues[0]);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::PointwiseMax{{{*/
+Input* TriaP1Input::PointwiseMax(Input* inputB){
+
+	/*Ouput*/
+	TriaP1Input* outinput=NULL;
+
+	/*Intermediaries*/
+	int               i;
+	TriaP1Input *xinputB     = NULL;
+	int               B_numvalues;
+	const int         numnodes    = 3;
+	IssmDouble            maxvalues[numnodes];
+
+	/*Check that inputB is of the same type*/
+	if (inputB->ObjectEnum()!=TriaP1InputEnum) _error2_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(TriaP1Input*)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 Tria vertex input (copy of current input)*/
+	outinput=new TriaP1Input(this->enum_type,&maxvalues[0]);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TriaP1Input::Configure{{{*/
+void TriaP1Input::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TriaP1Input.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TriaP1Input.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Inputs/TriaP1Input.h	(revision 12878)
@@ -0,0 +1,86 @@
+/*! \file TriaP1Input.h 
+ *  \brief: header file for TriaP1Input object
+ */
+
+
+#ifndef _TRIAP1INPUT_H_
+#define _TRIAP1INPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../Elements/TriaRef.h"
+class GaussTria;
+/*}}}*/
+
+class TriaP1Input: public Input,public TriaRef{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int    enum_type;
+		IssmDouble values[3];
+
+		/*TriaP1Input constructors, destructors: {{{*/
+		TriaP1Input();
+		TriaP1Input(int enum_type,IssmDouble* values);
+		~TriaP1Input();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*TriaP1Input management: {{{*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int* indices);
+		Input* PointwiseDivide(Input* inputB){_error2_("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){_error2_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue){_error2_("not implemented yet");}
+		void GetInputValue(int* pvalue){_error2_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue){_error2_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error2_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int index){_error2_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue);
+		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){_error2_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error2_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+
+		void SquareMin(IssmDouble* psquaremin, bool process_units,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){_error2_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error2_("not supported yet");};
+		void GetVectorFromInputs(Vector* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _TRIAP1INPUT_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KMLFileReadUtils.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KMLFileReadUtils.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KMLFileReadUtils.cpp	(revision 12878)
@@ -0,0 +1,700 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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;
+
+	buffer=(char *) xmalloc(buflen*sizeof(char));
+	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)++;
+						*ppcom=(char **) xrealloc(*ppcom,*pncom*sizeof(char*));
+						(*ppcom)[*pncom-1]=bufferc;
+					}
+					else
+						xfree((void**)&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)++;
+						*ppcom=(char **) xrealloc(*ppcom,*pncom*sizeof(char*));
+						(*ppcom)[*pncom-1]=bufferc;
+					}
+					else
+						xfree((void**)&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)
+//		_pprintLine_("tag buffer (length=" << ibuf << "):");
+//	else if (ifield)
+//		_pprintLine_("field buffer (length=" << ibuf << "):");
+//	_pprintLine_(buffer);
+
+	if (!ibuf)
+		xfree((void**)&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=(char *) xmalloc(buflen*sizeof(char));
+	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);
+				xfree((void**)&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;
+		}
+
+//	_pprintLine_("comment buffer (length=" << ibuf << "):");
+//	_pprintLine_(buffer);
+
+	if (!ibuf)
+		xfree((void**)&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*   buffer=NULL;
+
+/*  check buffer length and realloc if necessary  */
+
+	if (*pibuf+2 > *pbuflen) {
+		*pbuflen+=bufblk;
+		*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))
+		_error2_("KMLFileTagName -- Missing tag delimiters in " << ktag << ".\n");
+
+/*  strtok modifies ktag, so work on copy  */
+
+	ktagi=(char *) xmalloc((strlen(ktag)+1)*sizeof(char));
+	memcpy(ktagi,ktag,(strlen(ktag)+1)*sizeof(char));
+
+/*  skip opening delimeter and find subsequent blank or closing delimiter  */
+
+	ktokn=strtok(ktagi,"< >");
+//	_pprintLine_("KMLFileTagName -- initial token=\"" << ktokn << "\".");
+
+	if (!pname) {
+		if (maxlen)
+			pname=(char *) xmalloc((maxlen       +1)*sizeof(char));
+		else
+			pname=(char *) xmalloc((strlen(ktokn)+1)*sizeof(char));
+	}
+
+	if (maxlen && (maxlen < strlen(ktokn))) {
+		_pprintLine_("KMLFileTagName -- string field too short for " << ktag << ".");
+		_pprintLine_("KMLFileTagName -- \"" << ktokn << "\" truncated to " << maxlen << " characters.");
+		strncpy(pname,ktokn,maxlen);
+	}
+	else
+		memcpy(pname,ktokn,(strlen(ktokn)+1)*sizeof(char));
+
+	xfree((void**)&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=(char *) xmalloc((strlen(ktag)+1)*sizeof(char));
+	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," ");
+//	_pprintLine_("KMLFileTagAttrib -- initial token=\"" << ktokn << "\".");
+
+	/*  return next non " =?/>" and move past subsequent " =?/>"  */
+	while (ktokn=strtok(NULL," =?/>")) {
+
+		/*  return next non quote and move past subsequent quote  */
+		ktokv=strtok(NULL,quote);
+//		_pprintLine_("KMLFileTagAttrib -- attribute " << ktokn << "=\"" << ktokv << "\".");
+
+/*  add the attribute to the dataset  */
+
+		if (kobj)
+			kobj->AddAttrib(ktokn,ktokv);
+	}
+
+	xfree((void**)&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;
+//	_pprintLine_("KMLFileTagAttrib -- isolo=" << isolo << ".");
+
+	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] == '<'))
+		_error2_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");
+
+	sscanf(kstr,"%d",pival);
+	xfree((void**)&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)))
+		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xfree((void**)&kstr);
+
+//	_pprintLine_("KMLFileTokenParse -- " << ktag << "=" << *pival << ".");
+
+	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] == '<'))
+	  {_error2_("KMLFileTokenParse -- Missing bool field for " << ktag << ".\n");}
+
+	sscanf(kstr,"%d",&ival);
+	*pbval=(bool)ival;
+	xfree((void**)&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)))
+		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xfree((void**)&kstr);
+
+//	_pprintLine_("KMLFileTokenParse -- " << ktag << "=" << (*pbval ? "true" : "false") << ".");
+
+	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] == '<'))
+		_error2_("KMLFileTokenParse -- Missing string field for " << ktag << ".\n");
+
+	if (!pstr) {
+		if (maxlen)
+			pstr=(char *) xmalloc((maxlen      +1)*sizeof(char));
+		else
+			pstr=(char *) xmalloc((strlen(kstr)+1)*sizeof(char));
+	}
+
+	if (maxlen && (maxlen < strlen(kstr))) {
+		_pprintLine_("KMLFileTokenParse -- string field too short for " << ktag << ".");
+		_pprintLine_("KMLFileTokenParse -- \"" << kstr << "\" truncated to " << maxlen << " characters.");
+		strncpy(pstr,kstr,maxlen);
+	}
+	else
+		memcpy(pstr,kstr,(strlen(kstr)+1)*sizeof(char));
+
+	xfree((void**)&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)))
+		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xfree((void**)&kstr);
+
+//	_pprintLine_("KMLFileTokenParse -- " << ktag << "=\"" << pstr << "\".");
+
+	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] == '<'))
+	  {_error2_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");}
+
+	sscanf(kstr,"%g",pfval);
+	xfree((void**)&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)))
+		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xfree((void**)&kstr);
+
+//	_pprintLine_("KMLFileTokenParse -- " << ktag << "=" << *pfval << ".");
+
+	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] == '<'))
+		_error2_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");
+
+	sscanf(kstr,"%lg",pdval);
+	xfree((void**)&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)))
+		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xfree((void**)&kstr);
+
+//	_pprintLine_("KMLFileTokenParse -- " << ktag << "=" << *pdval << ".");
+
+	return(0);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenParse {{{*/
+int KMLFileTokenParse(double **pdval,int* m,int maxlen,
+					  char* ktag,
+					  FILE* fid){
+
+	int     i=-1,j;
+	char*   kstr;
+	char*   ktok;
+	char    delim[]={' ',',','\f','\n','\r','\t','\v','\0'};
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error2_("KMLFileTokenParse -- Missing double [m] field for " << ktag << ".\n");
+
+	if (!*pdval)
+		if (maxlen)
+			*pdval=(double *) xmalloc(maxlen              *sizeof(double));
+		else
+			*pdval=(double *) xmalloc(((strlen(kstr)+1)/2)*sizeof(double));
+
+/*  loop through string to get all values  */
+
+	ktok=strtok(kstr,delim);
+	while (ktok) {
+		i++;
+		if (maxlen && (maxlen < i+1))
+			_error2_("KMLFileTokenParse -- Double [m] field too short for " << ktag << ".\n");
+		sscanf(ktok,"%lg",&((*pdval)[i]));
+		ktok=strtok(NULL,delim);
+	}
+	xfree((void**)&kstr);
+
+	if (!maxlen)
+		*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)))
+		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xfree((void**)&kstr);
+
+//	_pprintLine_("KMLFileTokenParse -- " << ktag << "=...");
+//	for (j=0; j<=i; j++)
+//		_pprintLine_("   [" << j << "]: " << (*pdval)[j] << "g");
+
+	return(0);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenParse {{{*/
+int KMLFileTokenParse(double (**pdval3)[3],int* m,int maxlen,
+					  char* ktag,
+					  FILE* fid){
+
+	int     i=0,j=-1;
+	char*   kstr;
+	char*   ktok;
+	char    delim[]={' ',',','\f','\n','\r','\t','\v','\0'};
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error2_("KMLFileTokenParse -- Missing double [m x 3] field for " << ktag << ".\n");
+
+	if (!*pdval3)
+		if (maxlen)
+			*pdval3=(double (*)[3]) xmalloc((maxlen*3)          *sizeof(double));
+		else
+			*pdval3=(double (*)[3]) xmalloc(((strlen(kstr)+1)/2)*sizeof(double));
+
+/*  loop through string to get all values  */
+
+	ktok=strtok(kstr,delim);
+	while (ktok) {
+		j++;
+		if (j == 3) {
+			i++;
+			j=0;
+			if (maxlen && (maxlen < i+1))
+				_error2_("KMLFileTokenParse -- Double [m x 3] field too short for " << ktag << ".\n");
+		}
+		sscanf(ktok,"%lg",&((*pdval3)[i][j]));
+		ktok=strtok(NULL,delim);
+	}
+	xfree((void**)&kstr);
+
+	if (!maxlen)
+		*pdval3=(double (*)[3]) xrealloc(*pdval3,((i+1)*3)*sizeof(double));
+
+	if (m)
+		*m=i+1;
+
+	if (j != 2)
+		_pprintLine_("KMLFileTokenParse -- Double [m x 3] field for " << ktag << " does not have multiple of 3 values.");
+
+/*  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)))
+		  {_error2_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xfree((void**)&kstr);
+
+//	_pprintLine_("KMLFileTokenParse -- " << ktag << "=...");
+//	for (j=0; j<=i; j++)
+//		_pprintLine_("   [" << j << "][0-2]: " << (*pdval3)[j][0] << "g," << (*pdval3)[j][1] << "g," << (*pdval3)[j][2] << "g");
+
+	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  */
+
+	_pprintLine_("KMLFileTagSkip -- input tag " << ktag << ".");
+
+/*  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)))) {
+			_pprintLine_("KMLFileTagSkip -- closing tag " << kstr << ".");
+			xfree((void**)&kstr);
+			return(0);
+		}
+
+/*  if next token is an opening tag, call recursively  */
+
+		else if ((kstr[0] == '<') &&
+				 (kstr[1] != '/')) {
+			_pprintLine_("KMLFileTagSkip -- opening tag " << kstr << ".");
+			KMLFileTagSkip(kstr,
+						   fid);
+		}
+
+/*  if next token is a closing tag, error out  */
+
+		else if ((kstr[0] == '<') &&
+				 (kstr[1] == '/')) {
+			_error2_("KMLFileTagSkip -- Unexpected closing tag " << kstr << ".\n");
+		}
+
+		xfree((void**)&kstr);
+	}
+
+	_error2_("KMLFileTokenParse -- Corresponding closing tag for " << ktag << " not found.\n");
+
+	return(0);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KMLFileReadUtils.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KMLFileReadUtils.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KMLFileReadUtils.h	(revision 12878)
@@ -0,0 +1,57 @@
+/*!\file:  KMLFileReadUtils.h
+ * \brief: header file for kml file reading utilities.
+ */ 
+
+#ifndef _KMLFILEREADUTILS_H
+#define _KMLFILEREADUTILS_H
+
+/*Headers:{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+
+#include "../Object.h"
+/*}}}*/
+
+/* 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 (**pdval3)[3],int* m,int maxlen,
+					  char* ktag,
+					  FILE* fid);
+int KMLFileTagSkip(char* ktag,
+				   FILE* fid);
+
+#endif  /* _KMLFILEREADUTILS_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Attribute.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Attribute.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Attribute.cpp	(revision 12878)
@@ -0,0 +1,133 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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      ) xfree((void**)&name);
+	if (value     ) xfree((void**)&value);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Attribute::Echo {{{*/
+void  KML_Attribute::Echo(){
+
+	int   i;
+	bool  flag=true;
+
+	if(flag) _pprintString_("    ");
+	for (i=0;i<10-strlen(name);i++)
+		if(flag) _pprintString_(" ");
+	if(flag) _pprintLine_(name << ": \"" << value << "\"");
+
+	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) _pprintString_(indent << "    ");
+	for (i=0;i<10-strlen(name);i++)
+		if(flag) _pprintString_(" ");
+	if(flag) _pprintLine_(name << ": \"" << value << "\"");
+
+	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 =(char *) xmalloc((strlen(namei )+1)*sizeof(char));
+	memcpy(name,namei,(strlen(namei)+1)*sizeof(char));
+
+	value=(char *) xmalloc((strlen(valuei)+1)*sizeof(char));
+	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=(char *) xmalloc((strlen(deflt)+1)*sizeof(char));
+		memcpy(*pvalueo,deflt,(strlen(deflt)+1)*sizeof(char));
+	}
+	else {
+		*pvalueo=(char *) xmalloc((strlen(value)+1)*sizeof(char));
+		memcpy(*pvalueo,value,(strlen(value)+1)*sizeof(char));
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Attribute.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Attribute.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Attribute.h	(revision 12878)
@@ -0,0 +1,50 @@
+/*! \file KML_Attribute.h 
+ *  \brief: header file for kml_attribute object
+ */
+
+#ifndef _KML_ATTRIBUTE_H_
+#define _KML_ATTRIBUTE_H_
+
+/*Headers:{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+
+#include "../Object.h"
+class DataSet;
+/*}}}*/
+
+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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_ColorStyle.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_ColorStyle.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_ColorStyle.cpp	(revision 12878)
@@ -0,0 +1,109 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("         color: " << color);
+	if(flag) _pprintLine_("     colormode: " << colormode);
+
+	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) _pprintLine_(indent << "         color: " << color);
+	if(flag) _pprintLine_(indent << "     colormode: " << colormode);
+}
+/*}}}*/
+/*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))
+	  {_error2_("KML_ColorStyle::Read -- Unexpected closing tag " << kstr);}
+	else if (strncmp(kstr,"<",1))
+	  {_error2_("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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_ColorStyle.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_ColorStyle.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_ColorStyle.h	(revision 12878)
@@ -0,0 +1,48 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_COLORSTYLE_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Comment.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Comment.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Comment.cpp	(revision 12878)
@@ -0,0 +1,118 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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     ) xfree((void**)&value);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Comment::Echo {{{*/
+void  KML_Comment::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _pprintString_("    ");
+	if(flag) _pprintLine_(value);
+
+	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) _pprintString_(indent << "    ");
+	if(flag) _pprintLine_(value);
+
+	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=(char *) xmalloc((strlen(valuei)+1)*sizeof(char));
+	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=(char *) xmalloc((strlen(value)+1)*sizeof(char));
+	memcpy(*pvalueo,value,(strlen(value)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Comment.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Comment.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Comment.h	(revision 12878)
@@ -0,0 +1,50 @@
+/*! \file KML_Comment.h 
+ *  \brief: header file for kml_comment object
+ */
+
+#ifndef _KML_COMMENT_H_
+#define _KML_COMMENT_H_
+
+/*Headers:{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+
+#include "../Object.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Container.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Container.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Container.cpp	(revision 12878)
@@ -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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("       feature: (size=" << feature->Size() << ")");
+
+	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) _pprintLine_(indent << "       feature: -------- begin [" << i << "] --------");
+			((KML_Feature *)feature->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _pprintLine_(indent << "       feature: --------  end  [" << i << "] --------");
+		}
+	else
+		if(flag) _pprintLine_(indent << "       feature: [empty]");
+
+	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)) {
+		xfree((void**)&kstr);
+		return;
+	}
+	else if (!strncmp(kstr,"</",2))
+	  {_error2_("KML_Container::Read -- Unexpected closing tag " << kstr );}
+	else if (strncmp(kstr,"<",1))
+	  {_error2_("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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Container.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Container.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Container.h	(revision 12878)
@@ -0,0 +1,46 @@
+/*! \file KML_Container.h 
+ *  \brief: header file for kml_container abstract object
+ */
+
+#ifndef _KML_CONTAINER_H_
+#define _KML_CONTAINER_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_CONTAINER_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Document.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Document.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Document.cpp	(revision 12878)
@@ -0,0 +1,127 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("KML_Document:");
+	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) _pprintLine_(indent << "KML_Document:");
+	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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_Document::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("KML_Document::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Container::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Document.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Document.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Document.h	(revision 12878)
@@ -0,0 +1,43 @@
+/*! \file KML_Document.h 
+ *  \brief: header file for kml_document object
+ */
+
+#ifndef _KML_DOCUMENT_H_
+#define _KML_DOCUMENT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_DOCUMENT_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Feature.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Feature.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Feature.cpp	(revision 12878)
@@ -0,0 +1,179 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("          name: \"" << name << "\"");
+	if(flag) _pprintLine_("    visibility: " << (visibility ? "true" : "false"));
+	if(flag) _pprintLine_("          open: " << (open ? "true" : "false"));
+	if(flag) _pprintLine_("       snippet: \"" << snippet << "\"");
+	if(flag) _pprintLine_("      descript: \"" << descript << "\"");
+	if(flag) _pprintLine_("      styleurl: \"" << styleurl << "\"");
+	if(flag) _pprintLine_("         style: (size=" << style->Size() << ")");
+
+	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) _pprintLine_(indent << "          name: \"" << name << "\"");
+	if(flag) _pprintLine_(indent << "    visibility: " << (visibility ? "true" : "false"));
+	if(flag) _pprintLine_(indent << "          open: " << (open ? "true" : "false"));
+	if(flag) _pprintLine_(indent << "       snippet: \"" << snippet << "\"");
+	if(flag) _pprintLine_(indent << "      descript: \"" << descript << "\"");
+	if(flag) _pprintLine_(indent << "      styleurl: \"" << styleurl << "\"");
+
+/*  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) _pprintLine_(indent << "         style: -------- begin [" << i << "] --------");
+			((KML_Style *)style->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _pprintLine_(indent << "         style: --------  end  [" << i << "] --------");
+		}
+	else
+		if(flag) _pprintLine_(indent << "         style: [empty]");
+
+	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))
+	  {_error2_("KML_Feature::Read -- Unexpected closing tag " << kstr);}
+	else if (strncmp(kstr,"<",1))
+	  {_error2_("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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Feature.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Feature.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Feature.h	(revision 12878)
@@ -0,0 +1,57 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FEATURE_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_File.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_File.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_File.cpp	(revision 12878)
@@ -0,0 +1,140 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("KML_File:");
+	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) _pprintLine_(indent << "KML_File:");
+	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;
+	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,"</kml", 5)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_File::Read -- Unexpected closing tag " << kstri << ".");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("KML_File::Read -- Unexpected field \"" << kstri << "\"");}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_File.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_File.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_File.h	(revision 12878)
@@ -0,0 +1,44 @@
+/*! \file KML_File.h 
+ *  \brief: header file for kml_file object
+ */
+
+#ifndef _KML_FILE_H_
+#define _KML_FILE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FILE_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Folder.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Folder.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Folder.cpp	(revision 12878)
@@ -0,0 +1,126 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("KML_Folder:");
+	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) _pprintLine_(indent << "KML_Folder:");
+	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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_Folder::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("KML_Folder::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Container::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Folder.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Folder.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Folder.h	(revision 12878)
@@ -0,0 +1,43 @@
+/*! \file KML_Folder.h 
+ *  \brief: header file for kml_folder object
+ */
+
+#ifndef _KML_FOLDER_H_
+#define _KML_FOLDER_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FOLDER_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Geometry.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Geometry.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Geometry.cpp	(revision 12878)
@@ -0,0 +1,90 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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))
+	  {_error2_("KML_Geometry::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error2_("KML_Geometry::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Geometry.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Geometry.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Geometry.h	(revision 12878)
@@ -0,0 +1,42 @@
+/*! \file KML_Geometry.h 
+ *  \brief: header file for kml_geometry abstract object
+ */
+
+#ifndef _KML_GEOMETRY_H_
+#define _KML_GEOMETRY_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_GEOMETRY_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_GroundOverlay.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_GroundOverlay.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_GroundOverlay.cpp	(revision 12878)
@@ -0,0 +1,164 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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(){
+
+	_printLine_("KML_GroundOverlay:");
+	KML_Overlay::Echo();
+
+	_printLine_("         altitude: " << altitude);
+	_printLine_("          altmode: " << altmode);
+	_printLine_("            llbox: " << llbox);
+}
+/*}}}*/
+/*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];
+
+	_printLine_(indent << "KML_GroundOverlay:");
+	KML_Overlay::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	_printLine_(indent<<"      altitude: " << altitude);
+	_printLine_(indent<<"       altmode: " << altmode);
+	if (llbox)
+	 llbox->DeepEcho(indent2);
+	else
+	 _printLine_(indent<<"         llbox: " << llbox);
+}
+/*}}}*/
+/*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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_GroundOverlay::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("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);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_GroundOverlay.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_GroundOverlay.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_GroundOverlay.h	(revision 12878)
@@ -0,0 +1,49 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_GROUNDOVERLAY_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Icon.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Icon.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Icon.cpp	(revision 12878)
@@ -0,0 +1,182 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("KML_Icon:");
+	KML_Object::Echo();
+
+	if(flag) _pprintLine_("          href: \"" << href << "\"");
+	if(flag) _pprintLine_("       refmode: \"" << refmode << "\"");
+	if(flag) _pprintLine_("        refint: " << refint);
+	if(flag) _pprintLine_("      vrefmode: \"" << vrefmode << "\"");
+	if(flag) _pprintLine_("      vreftime: " << vreftime);
+	if(flag) _pprintLine_("      vboundsc: " << vboundsc);
+	if(flag) _pprintLine_("       vformat: \"" << vformat << "\"");
+	if(flag) _pprintLine_("        hquery: \"" << hquery << "\"");
+
+	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) _pprintLine_(indent << "KML_Icon:");
+	KML_Object::DeepEcho(indent);
+
+	if(flag) _pprintLine_(indent << "          href: \"" << href << "\"");
+	if(flag) _pprintLine_(indent << "       refmode: \"" << refmode << "\"");
+	if(flag) _pprintLine_(indent << "        refint: " << refint);
+	if(flag) _pprintLine_(indent << "      vrefmode: \"" << vrefmode << "\"");
+	if(flag) _pprintLine_(indent << "      vreftime: " << vreftime);
+	if(flag) _pprintLine_(indent << "      vboundsc: " << vboundsc);
+	if(flag) _pprintLine_(indent << "       vformat: \"" << vformat << "\"");
+	if(flag) _pprintLine_(indent << "        hquery: \"" << hquery << "\"");
+
+	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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_Icon::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("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);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Icon.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Icon.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Icon.h	(revision 12878)
@@ -0,0 +1,57 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_ICON_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LatLonBox.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LatLonBox.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LatLonBox.cpp	(revision 12878)
@@ -0,0 +1,162 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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(){
+
+
+	_printLine_("KML_LatLonBox:");
+	KML_Object::Echo();
+
+	_printLine_("         north: " << north);
+	_printLine_("         south: " << south);
+	_printLine_("          east: " << east);
+	_printLine_("          west: " << west);
+	_printLine_("      rotation: " << rotation);
+}
+/*}}}*/
+/*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){
+
+	_printLine_(indent << "KML_LatLonBox:");
+	KML_Object::DeepEcho(indent);
+
+	_printLine_("         north: " << north);
+	_printLine_("         south: " << south);
+	_printLine_("          east: " << east);
+	_printLine_("          west: " << west);
+	_printLine_("      rotation: " << rotation);
+}
+/*}}}*/
+/*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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_LatLonBox::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("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);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LatLonBox.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LatLonBox.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LatLonBox.h	(revision 12878)
@@ -0,0 +1,48 @@
+/*! \file KML_LatLonBox.h 
+ *  \brief: header file for kml_latlonbox object
+ */
+
+#ifndef _KML_LATLONBOX_H_
+#define _KML_LATLONBOX_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LATLONBOX_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineString.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineString.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineString.cpp	(revision 12878)
@@ -0,0 +1,230 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+#include "../../../modules/Ll2xyx/Ll2xyx.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) _pprintLine_("KML_LineString:");
+	KML_Geometry::Echo();
+
+	if(flag) _pprintLine_("       extrude: " << (extrude ? "true" : "false"));
+	if(flag) _pprintLine_("    tessellate: " << (tessellate ? "true" : "false"));
+	if(flag) _pprintLine_("       altmode: \"" << altmode << "\"");
+	if(flag) _pprintLine_("        coords: (ncoord=" << ncoord << ")");
+
+	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) _pprintLine_(indent << "KML_LineString:");
+	KML_Geometry::DeepEcho(indent);
+
+	if(flag) _pprintLine_(indent << "       extrude: " << (extrude ? "true" : "false"));
+	if(flag) _pprintLine_(indent << "    tessellate: " << (tessellate ? "true" : "false"));
+	if(flag) _pprintLine_(indent << "       altmode: \"" << altmode << "\"");
+	if(flag) _pprintLine_(indent << "        coords: (ncoord=" << ncoord << ")");
+	for (i=0; i<ncoord; i++)
+		if(flag) _pprintLine_(indent << "                (" << coords[3*i+0] << "," << coords[3*i+1] << "," << coords[3*i+2] << ")");
+
+	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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_LineString::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("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);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&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=(double *) xmalloc(ncoord*sizeof(double));
+	lon=(double *) xmalloc(ncoord*sizeof(double));
+	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  =(double *) xmalloc(ncoord*sizeof(double));
+	y  =(double *) xmalloc(ncoord*sizeof(double));
+	Ll2xyx(x,y,lat,lon,ncoord,sgn,cm,sp);
+
+/*  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");
+
+	xfree((void**)&y);
+	xfree((void**)&x);
+	xfree((void**)&lon);
+	xfree((void**)&lat);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineString.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineString.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineString.h	(revision 12878)
@@ -0,0 +1,51 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINESTRING_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineStyle.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineStyle.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineStyle.cpp	(revision 12878)
@@ -0,0 +1,138 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("KML_LineStyle:");
+	KML_ColorStyle::Echo();
+
+	if(flag) _pprintLine_("         width: " << width);
+
+	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){
+
+	int   i;
+	bool  flag=true;
+
+	if(flag) _pprintLine_(indent << "KML_LineStyle:");
+	KML_ColorStyle::DeepEcho(indent);
+
+	if(flag) _pprintLine_(indent << "         width: " << width);
+
+	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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_LineStyle::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("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);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineStyle.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineStyle.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LineStyle.h	(revision 12878)
@@ -0,0 +1,44 @@
+/*! \file KML_LineStyle.h 
+ *  \brief: header file for kml_linestyle object
+ */
+
+#ifndef _KML_LINESTYLE_H_
+#define _KML_LINESTYLE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINESTYLE_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LinearRing.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LinearRing.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LinearRing.cpp	(revision 12878)
@@ -0,0 +1,223 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+#include "../../../modules/Ll2xyx/Ll2xyx.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) _pprintLine_("KML_LinearRing:");
+	KML_Geometry::Echo();
+
+	if(flag) _pprintLine_("       extrude: " << (extrude ? "true" : "false"));
+	if(flag) _pprintLine_("    tessellate: " << (tessellate ? "true" : "false"));
+	if(flag) _pprintLine_("       altmode: \"" << altmode << "\"");
+	if(flag) _pprintLine_("        coords: (ncoord=" << ncoord << ")");
+
+	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) _pprintLine_(indent << "KML_LinearRing:");
+	KML_Geometry::DeepEcho(indent);
+
+	if(flag) _pprintLine_(indent << "       extrude: " << (extrude ? "true" : "false"));
+	if(flag) _pprintLine_(indent << "    tessellate: " << (tessellate ? "true" : "false"));
+	if(flag) _pprintLine_(indent << "       altmode: \"" << altmode << "\"");
+	if(flag) _pprintLine_(indent << "        coords: (ncoord=" << ncoord << ")");
+	for (i=0; i<ncoord; i++)
+		_printf_(flag,"%s                (%g,%g,%g)\n",indent,
+				coords[3*i+0],coords[3*i+1],coords[3*i+2]);
+
+	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))
+		  {_error2_("KML_LinearRing::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("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,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<double>(ncoord);
+	lon=xNew<double>(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<double>(ncoord);
+	y  =xNew<double>(ncoord);
+	Ll2xyx(x,y,lat,lon,ncoord,sgn,cm,sp);
+
+/*  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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LinearRing.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LinearRing.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_LinearRing.h	(revision 12878)
@@ -0,0 +1,51 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINEARRING_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_MultiGeometry.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_MultiGeometry.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_MultiGeometry.cpp	(revision 12878)
@@ -0,0 +1,203 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("KML_Multigeometry:");
+	KML_Geometry::Echo();
+
+	if(flag) _pprintLine_("      geometry: (size=" << geometry->Size() << ")");
+
+	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) _pprintLine_(indent << "KML_Multigeometry:");
+	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) _pprintLine_(indent << "      geometry: -------- begin [" << i << "] --------");
+			((KML_Geometry *)geometry->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _pprintLine_(indent << "      geometry: --------  end  [" << i << "] --------");
+		}
+	else
+		if(flag) _pprintLine_(indent << "      geometry: [empty]");
+
+	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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_MultiGeometry::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("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);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_MultiGeometry.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_MultiGeometry.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_MultiGeometry.h	(revision 12878)
@@ -0,0 +1,47 @@
+/*! \file KML_MultiGeometry.h 
+ *  \brief: header file for kml_multigeometry object
+ */
+
+#ifndef _KML_MULTIGEOMETRY_H_
+#define _KML_MULTIGEOMETRY_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_MULTIGEOMETRY_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Object.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Object.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Object.cpp	(revision 12878)
@@ -0,0 +1,387 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("        attrib: (size=" << attrib->Size() << ")");
+	if(flag) _pprintLine_("        commnt: (size=" << commnt->Size() << ")");
+	if(flag) _pprintLine_("        kmlobj: (size=" << kmlobj->Size() << ")");
+
+	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) _pprintLine_(indent << "        attrib: [empty]");
+
+/*  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) _pprintLine_(indent << "        commnt: [empty]");
+
+/*  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) _pprintLine_(indent << "        kmlobj: -------- begin [" << i << "] --------");
+			((KML_Unknown *)kmlobj->GetObjectByOffset(i))->DeepEcho(indent2);
+            if(flag) _pprintLine_(indent << "        kmlobj: --------  end  [" << i << "] --------");
+		}
+	else
+		if(flag) _pprintLine_(indent << "        kmlobj: [empty]");
+
+	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))
+	  {_error2_("KML_Object::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error2_("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)) {
+		_pprintLine_("KML_Object::Read -- Unrecognized opening tag " << kstr << ".");
+//		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=(char *) xmalloc((strlen(deflt)+1)*sizeof(char));
+		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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Object.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Object.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Object.h	(revision 12878)
@@ -0,0 +1,56 @@
+/*! \file KML_Object.h 
+ *  \brief: header file for kml_object abstract object
+ */
+
+#ifndef _KML_OBJECT_H_
+#define _KML_OBJECT_H_
+
+/*Headers:{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+
+#include "../Object.h"
+class DataSet;
+/*}}}*/
+
+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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Overlay.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Overlay.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Overlay.cpp	(revision 12878)
@@ -0,0 +1,135 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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();
+	_pprintLine_("         color: \"" << color << "\"");
+	_pprintLine_("       draword: " << draword);
+	_pprintLine_("          icon: " << icon);
+}
+/*}}}*/
+/*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,"  ");
+
+	_pprintLine_(indent << "         color: " << color);
+	_pprintLine_(indent << "       draword: " << draword);
+	if (icon)
+		icon->DeepEcho(indent2);
+	else
+		_pprintLine_(indent << "          icon: " << icon);
+}
+/*}}}*/
+/*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)) {
+		xfree((void**)&kstr);
+		return;
+	}
+	else if (!strncmp(kstr,"</",2))
+	  {_error2_("KML_Overlay::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error2_("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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Overlay.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Overlay.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Overlay.h	(revision 12878)
@@ -0,0 +1,49 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_OVERLAY_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Placemark.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Placemark.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Placemark.cpp	(revision 12878)
@@ -0,0 +1,210 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("KML_Placemark:");
+	KML_Feature::Echo();
+
+	if(flag) _pprintLine_("      geometry: (size=" << geometry->Size() << ")");
+
+	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) _pprintLine_(indent << "KML_Placemark:");
+	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) _pprintLine_(indent << "      geometry: -------- begin [" << i << "] --------");
+			((KML_Geometry *)geometry->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _pprintLine_(indent << "      geometry: --------  end  [" << i << "] --------");
+		}
+	else
+		if(flag) _pprintLine_(indent << "      geometry: [empty]");
+
+	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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_Placemark::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("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);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Placemark.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Placemark.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Placemark.h	(revision 12878)
@@ -0,0 +1,47 @@
+/*! \file KML_Placemark.h 
+ *  \brief: header file for kml_placemark object
+ */
+
+#ifndef _KML_PLACEMARK_H_
+#define _KML_PLACEMARK_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_PLACEMARK_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Point.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Point.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Point.cpp	(revision 12878)
@@ -0,0 +1,193 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+#include "../../../modules/Ll2xyx/Ll2xyx.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) _pprintLine_("KML_Point:");
+	KML_Geometry::Echo();
+
+	if(flag) _pprintLine_("       extrude: " << (extrude ? "true" : "false"));
+	if(flag) _pprintLine_("       altmode: \"" << altmode << "\"");
+	if(flag) _pprintLine_("        coords: (" << coords[0] << "," << coords[1] << "," << coords[2] << ")");
+
+	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) _pprintLine_(indent << "KML_Point:");
+	KML_Geometry::DeepEcho(indent);
+
+	if(flag) _pprintLine_(indent << "       extrude: " << (extrude ? "true" : "false"));
+	if(flag) _pprintLine_(indent << "       altmode: \"" << altmode << "\"");
+	if(flag) _pprintLine_(indent << "        coords: (" << coords[0] << "," << coords[1] << "," << coords[2] << ")");
+
+	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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_Point::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("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);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&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  */
+
+	Ll2xyx(&x,&y,&lat,&lon,1,sgn,cm,sp);
+
+/*  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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Point.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Point.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Point.h	(revision 12878)
@@ -0,0 +1,49 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POINT_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_PolyStyle.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_PolyStyle.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_PolyStyle.cpp	(revision 12878)
@@ -0,0 +1,146 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("KML_PolyStyle:");
+	KML_ColorStyle::Echo();
+
+	if(flag) _pprintLine_("          fill: " << fill);
+	if(flag) _pprintLine_("       outline: " << outline);
+
+	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){
+
+	int   i;
+	bool  flag=true;
+
+	if(flag) _pprintLine_(indent << "KML_PolyStyle:");
+	KML_ColorStyle::DeepEcho(indent);
+
+	if(flag) _pprintLine_(indent << "          fill: " << fill);
+	if(flag) _pprintLine_(indent << "       outline: " << outline);
+
+	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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_PolyStyle::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("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);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_PolyStyle.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_PolyStyle.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_PolyStyle.h	(revision 12878)
@@ -0,0 +1,45 @@
+/*! \file KML_PolyStyle.h 
+ *  \brief: header file for kml_polystyle object
+ */
+
+#ifndef _KML_POLYSTYLE_H_
+#define _KML_POLYSTYLE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POLYSTYLE_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Polygon.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Polygon.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Polygon.cpp	(revision 12878)
@@ -0,0 +1,298 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _pprintLine_("KML_Polygon:");
+	KML_Geometry::Echo();
+
+	if(flag) _pprintLine_("       extrude: " << (extrude ? "true" : "false"));
+	if(flag) _pprintLine_("    tessellate: " << (tessellate ? "true" : "false"));
+	if(flag) _pprintLine_("       altmode: \"" << altmode << "\"");
+	if(flag) _pprintLine_("         outer: (size=" << outer->Size() << ")");
+	if(flag) _pprintLine_("         inner: (size=" << inner->Size() << ")");
+
+	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) _pprintLine_(indent << "KML_Polygon:");
+	KML_Geometry::DeepEcho(indent);
+
+	if(flag) _pprintLine_(indent << "       extrude: " << (extrude ? "true" : "false"));
+	if(flag) _pprintLine_(indent << "    tessellate: " << (tessellate ? "true" : "false"));
+	if(flag) _pprintLine_(indent << "       altmode: \"" << altmode << "\"");
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+	if (outer->Size())
+		for (i=0; i<outer->Size(); i++) {
+			if(flag) _pprintLine_(indent << "         outer: -------- begin [" << i << "] --------");
+			((KML_LinearRing *)outer->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _pprintLine_(indent << "         outer: --------  end  [" << i << "] --------");
+		}
+	else
+		if(flag) _pprintLine_(indent << "         outer: [empty]");
+
+	if (inner->Size())
+		for (i=0; i<inner->Size(); i++) {
+			if(flag) _pprintLine_(indent << "         inner: -------- begin [" << i << "] --------");
+			((KML_LinearRing *)inner->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _pprintLine_(indent << "         inner: --------  end  [" << i << "] --------");
+		}
+	else
+		if(flag) _pprintLine_(indent << "         inner: [empty]");
+
+	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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_Polygon::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("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)) {
+					xfree((void**)&kstrj);
+					break;
+				}
+				else if (!strncmp(kstrj,"</",2))
+				  {_error2_("KML_Polygon::Read -- Unexpected closing tag " << kstrj << ".\n");}
+				else if (strncmp(kstrj,"<",1))
+				  {_error2_("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);
+
+				xfree((void**)&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)) {
+					xfree((void**)&kstrj);
+					break;
+				}
+				else if (!strncmp(kstrj,"</",2))
+				  {_error2_("KML_Polygon::Read -- Unexpected closing tag " << kstrj << ".\n");}
+				else if (strncmp(kstrj,"<",1))
+				  {_error2_("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);
+
+				xfree((void**)&kstrj);
+			}
+
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&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/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Polygon.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Polygon.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Polygon.h	(revision 12878)
@@ -0,0 +1,53 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POLYGON_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Style.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Style.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Style.cpp	(revision 12878)
@@ -0,0 +1,243 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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;
+		if (list      ) xfree((void**)&list);
+		list      =NULL;
+	}
+	if (balloon) {
+//		delete balloon;
+		if (balloon   ) xfree((void**)&balloon);
+		balloon   =NULL;
+	}
+	if (poly) {
+		delete poly;
+		poly      =NULL;
+	}
+	if (line) {
+		delete line;
+		line      =NULL;
+	}
+	if (label) {
+//		delete label;
+		if (label     ) xfree((void**)&label);
+		label     =NULL;
+	}
+	if (icon) {
+//		delete icon;
+		if (icon      ) xfree((void**)&icon);
+		icon      =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Style::Echo {{{*/
+void  KML_Style::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _pprintLine_("KML_Style:");
+	KML_StyleSelector::Echo();
+
+	if(flag) _pprintLine_("          icon: " << icon);
+	if(flag) _pprintLine_("         label: " << label);
+	if(flag) _pprintLine_("          line: " << line);
+	if(flag) _pprintLine_("          poly: " << poly);
+	if(flag) _pprintLine_("       balloon: " << balloon);
+	if(flag) _pprintLine_("          list: " << list);
+
+	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) _pprintLine_(indent << "KML_Style:");
+	KML_StyleSelector::DeepEcho(indent);
+
+	memcpy(indent2,indent,(strlen(indent)+1)*sizeof(char));
+	strcat(indent2,"  ");
+
+//	if (icon)
+//		icon->DeepEcho(indent2);
+//	else
+		if(flag) _pprintLine_(indent << "          icon: " << icon);
+//	if (label)
+//		label->DeepEcho(indent2);
+//	else
+		if(flag) _pprintLine_(indent << "         label: " << label);
+	if (line)
+		line->DeepEcho(indent2);
+	else
+		if(flag) _pprintLine_(indent << "          line: " << line);
+	if (poly)
+		poly->DeepEcho(indent2);
+	else
+		if(flag) _pprintLine_(indent << "          poly: " << poly);
+//	if (balloon)
+//		balloon->DeepEcho(indent2);
+//	else
+		if(flag) _pprintLine_(indent << "       balloon: " << balloon);
+//	if (list)
+//		list->DeepEcho(indent2);
+//	else
+		if(flag) _pprintLine_(indent << "          list: " << list);
+
+	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)) {
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_Style::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error2_("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);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Style.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Style.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Style.h	(revision 12878)
@@ -0,0 +1,51 @@
+/*! \file KML_Style.h 
+ *  \brief: header file for kml_style object
+ */
+
+#ifndef _KML_STYLE_H_
+#define _KML_STYLE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_STYLE_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_StyleSelector.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_StyleSelector.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_StyleSelector.cpp	(revision 12878)
@@ -0,0 +1,95 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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))
+	  {_error2_("KML_StyleSelector::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error2_("KML_StyleSelector::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_StyleSelector.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_StyleSelector.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_StyleSelector.h	(revision 12878)
@@ -0,0 +1,42 @@
+/*! \file KML_StyleSelector.h 
+ *  \brief: header file for kml_styleselector abstract object
+ */
+
+#ifndef _KML_STYLESELECTOR_H_
+#define _KML_STYLESELECTOR_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_STYLESELECTOR_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_SubStyle.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_SubStyle.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_SubStyle.cpp	(revision 12878)
@@ -0,0 +1,95 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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))
+	  {_error2_("KML_SubStyle::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error2_("KML_SubStyle::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_SubStyle.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_SubStyle.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_SubStyle.h	(revision 12878)
@@ -0,0 +1,42 @@
+/*! \file KML_SubStyle.h 
+ *  \brief: header file for kml_substyle abstract object
+ */
+
+#ifndef _KML_SUBSTYLE_H_
+#define _KML_SUBSTYLE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_SUBSTYLE_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Unknown.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Unknown.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Unknown.cpp	(revision 12878)
@@ -0,0 +1,189 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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      ) xfree((void**)&name);
+	if (value     ) xfree((void**)&value);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Unknown::Echo {{{*/
+void  KML_Unknown::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _pprintLine_("KML_Unknown " << name << ":");
+	KML_Object::Echo();
+
+	if (value     )
+		if(flag) _pprintLine_("         value: \"" << value << "\"");
+    else
+        if(flag) _pprintLine_("         value: [none]");
+
+	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) _pprintLine_(indent << "KML_Unknown " << name << ":");
+	KML_Object::DeepEcho(indent);
+
+	if (value     ) {
+		valuei=(char *) xmalloc((strlen(value)+1)*sizeof(char));
+		memcpy(valuei,value,(strlen(value)+1)*sizeof(char)); 
+        
+		vtoken=strtok(valuei,nl);
+		if(flag) _pprintString_(indent << "         value: \"" << vtoken);
+    
+		while (vtoken=strtok(NULL,nl))
+			if(flag) _pprintString_("\n" << indent << "                 " << vtoken);
+		if(flag) _pprintLine_("\"");
+
+		xfree((void**)&valuei);
+	}
+    else
+        if(flag) _pprintLine_(indent << "         value: [none]");
+
+	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=(char *) xmalloc((strlen(value)+1)*sizeof(char));
+		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);
+
+		xfree((void**)&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;
+	int          ncom=0;
+	char**       pcom=NULL;
+	char         nl[]={'\n','\0'};
+
+/*  get object name  */
+
+	name=KMLFileTagName(NULL,
+						kstr);
+//	_pprintLine_("KML_Unknown::Read -- opening name=" << name << ".");
+
+/*  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)) {
+//		_pprintLine_("KML_Unknown::Read -- kstri=" << kstri << ".");
+		if      (!strncmp(&kstri[0],"</", 2) &&
+				 !strncmp(&kstri[2],name,strlen(name))) {
+//			_pprintLine_("KML_Unknown::Read -- closing name=" << name << ".");
+			xfree((void**)&kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error2_("KML_Unknown::Read -- Unexpected closing tag " << kstri << ".\n");}
+
+		else if (strncmp(kstri,"<",1)) {
+			if (value) {
+				value=(char *) xrealloc(value,(strlen(value)+1+strlen(kstri)+1)*sizeof(char));
+				strcat(value,nl);
+				strcat(value,kstri);
+			}
+			else {
+				value=(char *) xmalloc((strlen(kstri)+1)*sizeof(char));
+				memcpy(value,kstri,(strlen(kstri)+1)*sizeof(char));
+			}
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xfree((void**)&kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xfree((void**)&(pcom[ncom-1]));
+	xfree((void**)&pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Unknown.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Unknown.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/KML/KML_Unknown.h	(revision 12878)
@@ -0,0 +1,45 @@
+/*! \file KML_Unknown.h 
+ *  \brief: header file for kml_unknown object
+ */
+
+#ifndef _KML_UNKNOWN_H_
+#define _KML_UNKNOWN_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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(){_error2_("Not implemented yet.");};
+		int   MyRank(){_error2_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   MarshallSize(){_error2_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error2_("Not implemented yet.");};
+		int   ObjectEnum(){_error2_("Not implemented yet.");};
+		Object* copy(){_error2_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_UNKNOWN_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Friction.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Friction.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Friction.cpp	(revision 12878)
@@ -0,0 +1,334 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../Container/Container.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.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){
+	_printLine_("Friction:");
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	_printLine_("   element_type: " << this->element_type);
+	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 _error2_("element_type "<< element_type << " not supported yet");
+
+	/*Checks that s-1>0 if v=0*/
+        if(vmag==0 && (s-1)<0) _error2_("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::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 _error2_("element_type "<< element_type << " not supported yet");
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error2_("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: */
+	int     i;
+	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 _error2_("element_type "<< element_type << " not supported yet");
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error2_("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: */
+	int     i;
+	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 _error2_("element_type "<< element_type << " not supported yet");
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error2_("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) _error2_("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) _error2_("input " << EnumToStringx(enum_type) << " not found");
+	input->GetInputValue(pvalue,gauss);
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Friction.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Friction.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Friction.h	(revision 12878)
@@ -0,0 +1,38 @@
+/*!\file Friction.h
+ * \brief: header file for friction object
+ */
+
+#ifndef _FRICTION_H_
+#define _FRICTION_H_
+
+/*Headers:*/
+/*{{{*/
+class Inputs;
+class Matpar;
+/*}}}*/
+
+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/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Icefront.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Icefront.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Icefront.cpp	(revision 12878)
@@ -0,0 +1,743 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.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->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 num_nodes; 
+	int dim;
+	int numberofelements;
+
+	/*icefront constructor data: */
+	int  icefront_eid;
+	int  icefront_mparid;
+	int  icefront_node_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));
+	}
+	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));
+	}
+	else _error2_("in_icefront_type " << EnumToStringx(in_icefront_type) << " not supported yet!");
+
+	if (in_icefront_type==PattynIceFrontEnum || in_icefront_type==StokesIceFrontEnum)
+	 num_nodes=4;
+	else 
+	 num_nodes=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,num_nodes);
+	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(TypeEnum,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->element= NULL;
+	this->matpar= NULL;
+}
+
+
+/*}}}*/
+/*FUNCTION Icefront::~Icefront() {{{*/
+Icefront::~Icefront(){
+	delete inputs;
+	this->parameters=NULL;
+	delete hnodes;
+	delete helement;
+	delete hmatpar;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Icefront::Echo {{{*/
+void Icefront::Echo(void){
+	_printLine_("Icefront:");
+	_printLine_("   id: " << id);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	hnodes->Echo();
+	helement->Echo();
+	hmatpar->Echo();
+	_printLine_("   parameters: " << parameters);
+	if(parameters)parameters->Echo();
+	_printLine_("   inputs: " << inputs);
+	if(inputs)inputs->Echo();
+}
+/*}}}*/
+/*FUNCTION Icefront::DeepEcho{{{*/
+void Icefront::DeepEcho(void){
+
+	_printLine_("Icefront:");
+	_printLine_("   id: " << id);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	hnodes->DeepEcho();
+	helement->DeepEcho();
+	hmatpar->DeepEcho();
+	_printLine_("   parameters: " << parameters);
+	if(parameters)parameters->DeepEcho();
+	_printLine_("   inputs: " << inputs);
+	if(inputs)inputs->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION Icefront::Id {{{*/
+int    Icefront::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Icefront::MyRank {{{*/
+int    Icefront::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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->helement=(Hook*)this->helement->copy();
+	icefront->hmatpar=(Hook*)this->hmatpar->copy();
+
+	/*corresponding fields*/
+	icefront->nodes  =(Node**)icefront->hnodes->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(nodesin);
+	helement->configure(elementsin);
+	hmatpar->configure(materialsin);
+
+	/*Initialize hooked fields*/
+	this->nodes  =(Node**)hnodes->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* Kff, Matrix* Kfs){
+
+	/*No stiffness loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Icefront::CreatePVector {{{*/
+void  Icefront::CreatePVector(Vector* 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:
+			_error2_("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* Jff){
+	this->CreateKMatrix(Jff,NULL);
+}
+/*}}}*/
+/*FUNCTION Icefront::PenaltyCreateKMatrix {{{*/
+void  Icefront::PenaltyCreateKMatrix(Matrix* Kff, Matrix* Kfs, IssmDouble kmax){
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Icefront::PenaltyCreatePVector{{{*/
+void  Icefront::PenaltyCreatePVector(Vector* pf,IssmDouble kmax){
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Icefront::PenaltyCreateJacobianMatrix{{{*/
+void  Icefront::PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax){
+	this->PenaltyCreateKMatrix(Jff,NULL,kmax);
+}
+/*}}}*/
+/*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,TypeEnum);
+
+	switch(type){
+		case MacAyeal2dIceFrontEnum:
+			return CreatePVectorDiagnosticMacAyeal2d();
+        #ifdef _HAVE_3D_
+		case MacAyeal3dIceFrontEnum:
+			return CreatePVectorDiagnosticMacAyeal3d();
+		case PattynIceFrontEnum:
+			return CreatePVectorDiagnosticPattyn();
+		case StokesIceFrontEnum:
+			return CreatePVectorDiagnosticStokes();
+	    #endif
+		default:
+			_error2_("Icefront type " << EnumToStringx(type) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Icefront::CreatePVectorDiagnosticMacAyeal2d{{{*/
+ElementVector* Icefront::CreatePVectorDiagnosticMacAyeal2d(void){
+
+	/*Constants*/
+	const int numnodes= NUMVERTICESSEG;
+	const int numdofs = numnodes *NDOF2;
+
+	/*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[numnodes][3];
+	IssmDouble     normal[2];
+	IssmDouble     L[2];
+	GaussTria *gauss;
+
+	Tria* tria=((Tria*)element);
+
+	/*Initialize Element vector and return if necessary*/
+	if(tria->IsOnWater()) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICESSEG,this->parameters,MacAyealApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],nodes,numnodes);
+	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:
+				_error2_("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(&L[0],gauss,index1,index2);
+
+		for (int i=0;i<numnodes;i++){
+			pe->values[2*i+0]+= pressure*Jdet*gauss->weight*normal[0]*L[i];
+			pe->values[2*i+1]+= pressure*Jdet*gauss->weight*normal[1]*L[i];
+		}
+	}
+
+	/*Transform load vector*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICESSEG,XYEnum);
+
+	/*Clean up and return*/
+	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;
+	bool      onbed;
+
+	/*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(TypeEnum,MacAyeal2dIceFrontEnum));
+	ElementVector* pe=icefront->CreatePVectorDiagnosticMacAyeal2d();
+
+	/*clean-up and return*/
+	delete tria->matice;
+	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], nodes, 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:
+				_error2_("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], nodes, 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:
+				_error2_("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 i,j;
+	int numberofdofs=0;
+	int count=0;
+	int type;
+	int numberofnodes=2;
+
+	/*output: */
+	int* doflist=NULL;
+
+	
+	/*recover type: */
+	inputs->GetInputValue(&type,TypeEnum);
+
+	/*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(i=0;i<numberofnodes;i++){
+		numberofdofs+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+	}
+
+	/*Allocate: */
+	doflist=xNew<int>(numberofdofs);
+
+	/*Populate: */
+	count=0;
+	for(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/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Icefront.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Icefront.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Icefront.h	(revision 12878)
@@ -0,0 +1,98 @@
+/*!\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 Icefront: public Load {
+
+	public:
+		int id;
+		int analysis_type;
+
+		/*hooks: */
+		Hook* hnodes;
+		Hook* helement;
+		Hook* hmatpar;
+
+		/*Corresponding fields*/
+		Matpar   *matpar;
+		Node    **nodes;
+		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   MyRank();
+		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){_error2_("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* Kff, Matrix* Kfs);
+		void  CreatePVector(Vector* pf);
+		void  CreateJacobianMatrix(Matrix* Jff);
+		void  PenaltyCreateKMatrix(Matrix* Kff, Matrix* kfs, IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector*  pf, IssmDouble kmax);
+		void  PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax);
+		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/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Load.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Load.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Load.h	(revision 12878)
@@ -0,0 +1,40 @@
+/*!\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 Object;
+class Matrix;
+class Vector;
+
+#include "../Object.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../Container/Container.h"
+/*}}}*/
+
+class Load: public Object,public Update{
+
+	public: 
+
+		virtual       ~Load(){};
+		
+		/*Virtual functions: {{{*/
+		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,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
+		virtual void  CreateKMatrix(Matrix* Kff, Matrix* Kfs)=0;
+		virtual void  CreatePVector(Vector* pf)=0;
+		virtual void  CreateJacobianMatrix(Matrix* Jff)=0;
+		virtual void  PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax)=0;
+		virtual void  PenaltyCreateKMatrix(Matrix* Kff, Matrix* Kfs, IssmDouble kmax)=0;
+		virtual void  PenaltyCreatePVector(Vector* pf, IssmDouble kmax)=0;
+		virtual bool  InAnalysis(int analysis_type)=0;
+		/*}}}*/
+};
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Numericalflux.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Numericalflux.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Numericalflux.cpp	(revision 12878)
@@ -0,0 +1,880 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../../classes.h"
+/*}}}*/	
+
+/*Load macros*/
+#define NUMVERTICES_INTERNAL 4
+#define NUMVERTICES_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->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_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]);
+
+	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->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(TypeEnum,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;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Numericalflux::Echo {{{*/
+void Numericalflux::Echo(void){
+	_printLine_("Numericalflux:");
+	_printLine_("   id: " << id);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	hnodes->Echo();
+	helement->Echo();
+	_printLine_("   parameters: " << parameters);
+	_printLine_("   inputs: " << inputs);
+}
+/*}}}*/
+/*FUNCTION Numericalflux::DeepEcho {{{*/
+void Numericalflux::DeepEcho(void){
+
+	_printLine_("Numericalflux:");
+	_printLine_("   id: " << id);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	hnodes->DeepEcho();
+	helement->DeepEcho();
+	_printLine_("   parameters");
+	if(parameters)
+	 parameters->DeepEcho();
+	else
+	 _printLine_("      NULL");
+	_printLine_("   inputs");
+	inputs->DeepEcho();
+	
+}		
+/*}}}*/
+/*FUNCTION Numericalflux::Id {{{*/
+int    Numericalflux::Id(void){
+	return id;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::MyRank {{{*/
+int    Numericalflux::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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->helement=(Hook*)this->helement->copy();
+
+	/*corresponding fields*/
+	numericalflux->nodes  =(Node**)numericalflux->hnodes->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(nodesin);
+	helement->configure(elementsin);
+
+	/*Initialize hooked fields*/
+	this->nodes  =(Node**)hnodes->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* Kff, Matrix* 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:
+			_error2_("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* 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:
+			_error2_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::PenaltyCreateKMatrix {{{*/
+void  Numericalflux::PenaltyCreateKMatrix(Matrix* Kff, Matrix* Kfs,IssmDouble kmax){
+
+	/*No stiffness loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::PenaltyCreatePVector{{{*/
+void  Numericalflux::PenaltyCreatePVector(Vector* 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;
+}
+/*}}}*/
+
+/*Numericalflux management*/
+/*FUNCTION Numericalflux::CreateKMatrixPrognostic{{{*/
+ElementMatrix* Numericalflux::CreateKMatrixPrognostic(void){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreateKMatrixPrognosticInternal();
+		case BoundaryEnum:
+			return CreateKMatrixPrognosticBoundary();
+		default:
+			_error2_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixPrognosticInternal {{{*/
+ElementMatrix* Numericalflux::CreateKMatrixPrognosticInternal(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMVERTICES_INTERNAL;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL1,DL2,Jdet,dt,vx,vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES_INTERNAL][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,NUMVERTICES_INTERNAL,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes,NUMVERTICES_INTERNAL);
+	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*NUMVERTICES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES_BOUNDARY][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],nodes,NUMVERTICES_BOUNDARY);
+	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,NUMVERTICES_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,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreateKMatrixBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreateKMatrixBalancethicknessBoundary();
+		default:
+			_error2_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixBalancethicknessInternal {{{*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessInternal(void){
+
+	/* constants*/
+	const int numdof=NDOF1*NUMVERTICES_INTERNAL;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL1,DL2,Jdet,vx,vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES_INTERNAL][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,NUMVERTICES_INTERNAL,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes,NUMVERTICES_INTERNAL);
+	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*NUMVERTICES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL,Jdet,vx,vy,mean_vx,mean_vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES_BOUNDARY][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],nodes,NUMVERTICES_BOUNDARY);
+	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,NUMVERTICES_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,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreateKMatrixAdjointBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreateKMatrixAdjointBalancethicknessBoundary();
+		default:
+			_error2_("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,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreatePVectorPrognosticInternal();
+		case BoundaryEnum:
+			return CreatePVectorPrognosticBoundary();
+		default:
+			_error2_("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*NUMVERTICES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN,thickness;
+	IssmDouble     xyz_list[NUMVERTICES_BOUNDARY][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],nodes,NUMVERTICES_BOUNDARY);
+	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,NUMVERTICES_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)) _error2_("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,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreatePVectorBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreatePVectorBalancethicknessBoundary();
+		default:
+			_error2_("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*NUMVERTICES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL,Jdet,vx,vy,mean_vx,mean_vy,UdotN,thickness;
+	IssmDouble     xyz_list[NUMVERTICES_BOUNDARY][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],nodes,NUMVERTICES_BOUNDARY);
+	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,NUMVERTICES_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/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Numericalflux.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Numericalflux.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Numericalflux.h	(revision 12878)
@@ -0,0 +1,97 @@
+/*!\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;
+
+		/*Corresponding fields*/
+		Element* element;
+		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   MyRank();
+		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){_error2_("Not implemented yet!");}
+		void    InputUpdateFromVector(bool* vector, int name, int type){_error2_("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){_error2_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(bool* vector, int name, int type){_error2_("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){_error2_("Not implemented yet!");}
+		void    InputUpdateFromSolution(IssmDouble* solution){_error2_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error2_("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* Kff, Matrix* Kfs);
+		void  CreatePVector(Vector* pf);
+		void  CreateJacobianMatrix(Matrix* Jff){_error2_("Not implemented yet");};
+		void  PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax){_error2_("Not implemented yet");};
+		void  PenaltyCreateKMatrix(Matrix* Kff, Matrix* kfs, IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector* pf, IssmDouble kmax);
+		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/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Pengrid.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Pengrid.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Pengrid.cpp	(revision 12878)
@@ -0,0 +1,620 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.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 i,j;
+	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){
+
+	_printLine_("Pengrid:");
+	_printLine_("   id: " << id);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	hnode->DeepEcho();
+	helement->DeepEcho();
+	hmatpar->DeepEcho();
+	_printLine_("   active " << this->active);
+	_printLine_("   zigzag_counter " << this->zigzag_counter);
+	_printLine_("   parameters");
+	parameters->DeepEcho();
+	_printLine_("   inputs");
+	inputs->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION Pengrid::Id {{{*/
+int    Pengrid::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Pengrid::MyRank {{{*/
+int    Pengrid::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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* Kff, Matrix* Kfs){
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Pengrid::CreatePVector {{{*/
+void  Pengrid::CreatePVector(Vector* pf){
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreateMatrix {{{*/
+void  Pengrid::PenaltyCreateKMatrix(Matrix* Kff, Matrix* 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
+		default:
+			_error2_("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* pf,IssmDouble kmax){
+
+	/*Retrieve parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case ThermalAnalysisEnum:
+			pe=PenaltyCreatePVectorThermal(kmax);
+			break;
+		#endif
+		#ifdef _HAVE_THERMAL_
+		case MeltingAnalysisEnum:
+			pe=PenaltyCreatePVectorMelting(kmax);
+			break;
+		case DiagnosticHorizAnalysisEnum: case AdjointHorizAnalysisEnum:
+			break;
+		#endif
+		default:
+			_error2_("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;
+}
+/*}}}*/
+
+/*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;
+	}
+	else if (analysis_type==ThermalAnalysisEnum){
+		ConstraintActivateThermal(punstable);
+	}
+	else if (analysis_type==MeltingAnalysisEnum){
+		/*No penalty to check*/
+		return;
+	}
+	else{
+		_error2_("analysis: " << EnumToStringx(analysis_type) << " not supported yet");
+	}
+
+}
+/*}}}*/
+/*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;
+}
+/*}}}*/
+#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::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 (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
+/*FUNCTION Pengrid::ResetConstraint {{{*/
+void  Pengrid::ResetConstraint(void){
+	active=0;
+	zigzag_counter=0;
+}
+/*}}}*/
+/*FUNCTION Pengrid::UpdateInputs {{{*/
+void  Pengrid::UpdateInputs(IssmDouble* solution){
+	_error2_("not supported yet!");
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Pengrid.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Pengrid.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Pengrid.h	(revision 12878)
@@ -0,0 +1,100 @@
+/*!\file Pengrid.h
+ * \brief: header file for pengrid object */
+
+#ifndef _PENGRID_H_
+#define _PENGRID_H_
+
+/*Headers:*/
+/*{{{*/
+#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   MyRank();
+		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){_error2_("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* Kff, Matrix* Kfs);
+		void  CreatePVector(Vector* pf);
+		void  CreateJacobianMatrix(Matrix* Jff){_error2_("Not implemented yet");};
+		void  PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax){_error2_("Not implemented yet");};
+		void  PenaltyCreateKMatrix(Matrix* Kff, Matrix* kfs, IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector* pf, IssmDouble kmax);
+		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);
+		#endif
+		void  ConstraintActivate(int* punstable);
+		void  ConstraintActivateThermal(int* punstable);
+		void  UpdateInputs(IssmDouble* solution);
+		void  ResetConstraint(void);
+		/*}}}*/
+
+};
+
+#endif  /* _PENGRID_H_ */
+
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Penpair.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Penpair.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Penpair.cpp	(revision 12878)
@@ -0,0 +1,355 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../include/include.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){
+
+	int i;
+
+	_printLine_("Penpair:");
+	_printLine_("   id: " << id);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	hnodes->Echo();
+	
+	return;
+}
+/*}}}*/
+/*FUNCTION Penpair::DeepEcho {{{*/
+void Penpair::DeepEcho(void){
+
+	_printLine_("Penpair:");
+	_printLine_("   id: " << id);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	hnodes->DeepEcho();
+
+	return;
+}		
+/*}}}*/
+/*FUNCTION Penpair::Id {{{*/
+int    Penpair::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Penpair::MyRank {{{*/
+int    Penpair::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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(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* Kff, Matrix* 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* pf){
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Penpair::CreateJacobianMatrix{{{*/
+void  Penpair::CreateJacobianMatrix(Matrix* Jff){
+	this->CreateKMatrix(Jff,NULL);
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreateKMatrix {{{*/
+void  Penpair::PenaltyCreateKMatrix(Matrix* Kff, Matrix* 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:
+			_error2_("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* pf,IssmDouble kmax){
+	/*No loads applied, do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreateJacobianMatrix{{{*/
+void  Penpair::PenaltyCreateJacobianMatrix(Matrix* 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;
+}
+/*}}}*/
+
+/*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: _error2_("not supported yet");
+			}
+		case PattynApproximationEnum:
+			switch(approximation1){
+				case MacAyealApproximationEnum: return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				case PattynApproximationEnum:   return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				default: _error2_("not supported yet");
+			}
+		case StokesApproximationEnum:
+			switch(approximation1){
+				case StokesApproximationEnum: return PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				case NoneApproximationEnum: return   PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				default: _error2_("not supported yet");
+			}
+		case NoneApproximationEnum:
+			switch(approximation1){
+				case StokesApproximationEnum: return PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				case NoneApproximationEnum: return   PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				default: _error2_("not supported yet");
+			}
+		default: _error2_("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/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Penpair.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Penpair.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Penpair.h	(revision 12878)
@@ -0,0 +1,77 @@
+/*!\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   MyRank();
+		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){_error2_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error2_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(int* vector, int name, int type){_error2_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(bool* vector, int name, int type){_error2_("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){_error2_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error2_("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* Kff, Matrix* Kfs);
+		void  CreatePVector(Vector* pf);
+		void  CreateJacobianMatrix(Matrix* Jff);
+		void  PenaltyCreateKMatrix(Matrix* Kff,Matrix* Kfs,IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector* pf, IssmDouble kmax);
+		void  PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax);
+		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/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Riftfront.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Riftfront.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Riftfront.cpp	(revision 12878)
@@ -0,0 +1,916 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.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=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+2);
+	el2=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+3); 
+
+	node1=(int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+0); 
+	node2=(int)*(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=(int)*(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 = (int)*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+7);
+	riftfront_friction=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+8);
+	riftfront_fractionincrement=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+10);
+	riftfront_shelf=(bool)iomodel->Data(MaskVertexonfloatingiceEnum)[node1-1];
+
+	this->inputs->AddInput(new IntInput(TypeEnum,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);
+
+	_printLine_("Riftfront:");
+	_printLine_("   id: " << id);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	_printLine_("   hnodes: " << hnodes);
+	_printLine_("   helements: " << helements);
+	_printLine_("   hmatpar: " << hmatpar);
+	_printLine_("   parameters: " << parameters);
+	_printLine_("   inputs: " << inputs);
+	_printLine_("   internal parameters: ");
+	_printLine_("   normal: " << normal[0] << "|" << normal[1]);
+	_printLine_("   length: " << length);
+	_printLine_("   penalty_lock: " << penalty_lock);
+	_printLine_("   active: " <<(active ? "true":"false"));
+	_printLine_("   counter: " << counter);
+	_printLine_("   prestable: " << (prestable ? "true":"false"));
+	_printLine_("   material_converged: " << (material_converged ? "true":"false"));
+	_printLine_("   fill: " << fill);
+	_printLine_("   friction: " << friction);
+	_printLine_("   fraction: " << fraction);
+	_printLine_("   fractionincrement: " << fractionincrement);
+	_printLine_("   state: " << state);
+	_printLine_("   frozen: " << (frozen ? "true":"false"));
+		
+}
+/*}}}*/
+/*FUNCTION Riftfront::DeepEcho{{{*/
+void Riftfront::DeepEcho(void){
+
+	_printLine_("Riftfront:");
+	_printLine_("   id: " << id);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	hnodes->DeepEcho();
+	helements->DeepEcho();
+	hmatpar->DeepEcho();
+	_printLine_("   parameters");
+	if(parameters)parameters->DeepEcho();
+	_printLine_("   inputs");
+	if(inputs)inputs->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION Riftfront::Id {{{*/
+int    Riftfront::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Riftfront::MyRank {{{*/
+int    Riftfront::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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*/
+	_error2_("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::SetCurrentConfiguration {{{*/
+void  Riftfront::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::PenaltyCreateKMatrix {{{*/
+void  Riftfront::PenaltyCreateKMatrix(Matrix* Kff, Matrix* 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:
+			_error2_("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* 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:
+			_error2_("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* Kff, Matrix* Kfs){
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Riftfront::CreatePVector {{{*/
+void  Riftfront::CreatePVector(Vector* pf){
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Riftfront::InAnalysis{{{*/
+bool Riftfront::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+
+/*Riftfront numerics*/
+/*FUNCTION Riftfront::PenaltyCreateKMatrixDiagnosticHoriz {{{*/
+ElementMatrix* Riftfront::PenaltyCreateKMatrixDiagnosticHoriz(IssmDouble kmax){
+
+	const int   numdof = NDOF2*NUMVERTICES;
+	int         i,j;
+	int         dofs[1]             = {0};
+	IssmDouble      Ke_gg[4][4];
+	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)_error2_("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])_error2_("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         i,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)_error2_("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])_error2_("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])_error2_("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) _error2_("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{
+		_error2_("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      max_penetration;
+	IssmDouble      penetration;
+	int         activate;
+	int         found;
+	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)_error2_("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;
+		//_printLine_("riftfront " << this->Id() << " fraction: " << this->fraction);
+	}
+
+	//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))_printLine_("Riftfront " << Id() << " wants to be released");
+
+	/*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){
+
+	int found=0;
+	IssmDouble converged=0;
+
+	this->inputs->GetInputValue(&converged,ConvergedEnum);
+
+	if(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        max_penetration;
+	IssmDouble        penetration=0;
+	int           found;
+	IssmDouble      vx1;
+	IssmDouble      vy1;
+	IssmDouble      vx2;
+	IssmDouble      vy2;
+
+	/*Objects: */
+	Tria       *tria1           = NULL;
+	Tria       *tria2           = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error2_("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;
+	int       found;
+
+	/*Objects: */
+	Tria     *tria1       = NULL;
+	Tria     *tria2       = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error2_("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      max_penetration;
+	IssmDouble      penetration;
+	int         activate;
+	int         unstable;
+	int         found;
+	IssmDouble      vx1;
+	IssmDouble      vy1;
+	IssmDouble      vx2;
+	IssmDouble      vy2;
+
+	/*Objects: */
+	Tria       *tria1           = NULL;
+	Tria       *tria2           = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error2_("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;
+	int         found;
+	IssmDouble      vx1;
+	IssmDouble      vy1;
+	IssmDouble      vx2;
+	IssmDouble      vy2;
+
+	/*Objects: */
+	Tria       *tria1       = NULL;
+	Tria       *tria2       = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error2_("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/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Riftfront.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Riftfront.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Loads/Riftfront.h	(revision 12878)
@@ -0,0 +1,104 @@
+/*!\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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Update virtual functions resolution: {{{*/
+		void    InputUpdateFromVector(IssmDouble* vector, int name, int type);
+		void    InputUpdateFromVector(int* vector, int name, int type){_error2_("Not implemented yet!");}
+		void    InputUpdateFromVector(bool* vector, int name, int type){_error2_("Not implemented yet!");}
+		void    InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows,int ncols, int name, int type){_error2_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error2_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(int* vector, int name, int type){_error2_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(bool* vector, int name, int type){_error2_("Not implemented yet!");}
+		void    InputUpdateFromConstant(IssmDouble constant, int name);
+		void    InputUpdateFromConstant(int constant, int name){_error2_("Not implemented yet!");}
+		void    InputUpdateFromConstant(bool constant, int name);
+		void    InputUpdateFromSolution(IssmDouble* solution){_error2_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error2_("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* Kff, Matrix* Kfs);
+		void  CreatePVector(Vector* pf);
+		void  CreateJacobianMatrix(Matrix* Jff){_error2_("Not implemented yet");};
+		void  PenaltyCreateJacobianMatrix(Matrix* Jff,IssmDouble kmax){_error2_("Not implemented yet");};
+		void  PenaltyCreateKMatrix(Matrix* Kff, Matrix* kfs, IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector* pf, IssmDouble kmax);
+		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/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Material.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Material.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Material.h	(revision 12878)
@@ -0,0 +1,27 @@
+/*!\file:  Material.h
+ * \brief abstract class for Material object
+ */ 
+
+
+#ifndef _MATERIAL_H_
+#define _MATERIAL_H_
+
+/*Headers:*/
+/*{{{*/
+class Object;
+#include "../Object.h"
+#include "../../../toolkits/toolkits.h"
+/*}}}*/
+
+class Material: public Object,public Update{
+
+	public: 
+		virtual       ~Material(){};
+
+		/*Numerics*/
+		virtual void   InputDuplicate(int original_enum,int new_enum)=0;
+		virtual void   Configure(Elements* elements)=0;
+		virtual void   GetVectorFromInputs(Vector* vector,int input_enum)=0;
+
+};
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matice.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matice.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matice.cpp	(revision 12878)
@@ -0,0 +1,769 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.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    i;
+	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){
+
+	_printLine_("Matice:");
+	_printLine_("   mid: " << mid);
+	_printLine_("   inputs:");
+	inputs->Echo();
+	_printLine_("   element:");
+	helement->Echo();
+}
+/*}}}*/
+/*FUNCTION Matice::DeepEcho {{{*/
+void Matice::DeepEcho(void){
+
+	_printLine_("Matice:");
+	_printLine_("   mid: " << mid);
+	_printLine_("   inputs:");
+	inputs->DeepEcho();
+	_printLine_("   element:");
+	helement->Echo();
+}		
+/*}}}*/
+/*FUNCTION Matice::Id {{{*/
+int    Matice::Id(void){ return mid; }
+/*}}}*/
+/*FUNCTION Matice::MyRank {{{*/
+int    Matice::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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(elementsin);
+}
+/*}}}*/
+/*FUNCTION Matice::SetCurrentConfiguration {{{*/
+void  Matice::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*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* 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 doflist1[3];
+			for(int i=0;i<3;i++) doflist1[i]=((Tria*)element)->nodes[i]->GetVertexDof();
+
+			/*Get input (either in element or material)*/
+			Input* input=inputs->GetInput(input_enum);
+			if(!input) _error2_("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,&doflist1[0]);}
+			break;
+
+		default: _error2_("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((IssmDouble)10,(IssmDouble)17);
+			}
+			else{
+				e=(n-1)/(2*n);
+				viscosity=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity<=0) _error2_("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) _error2_("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) _error2_("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,exz;
+
+	/*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)->nodes[i]->GetVertexDof()];
+					this->inputs->AddInput(new TriaP1Input(name,values));
+					return;
+				}
+				default: _error2_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+			}
+		default: _error2_("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)->nodes[i]->GetSidList()]; //use sid list, to index into serial oriented vector 
+					this->inputs->AddInput(new TriaP1Input(name,values));
+					/*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 TriaP1Input(MaterialsRheologyBbarEnum,values));
+						}
+					}
+					/*}}}*/
+					return;
+				}
+				default: _error2_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+			}
+		default: _error2_("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 TriaP1Input(MaterialsRheologyBbarEnum,nodeinputs));
+		}
+
+		/*Get n*/
+		if (iomodel->Data(MaterialsRheologyNEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
+			this->inputs->AddInput(new TriaP1Input(MaterialsRheologyNEnum,nodeinputs));
+		}
+
+		/*Control Inputs*/
+		#ifdef _HAVE_CONTROL_
+		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+			for(i=0;i<num_control_type;i++){
+				switch((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)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(MaterialsRheologyBbarEnum,TriaP1InputEnum,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)[int(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((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)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[int(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[int(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{
+		_error2_("Mesh type not supported yet!");
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Matice::IsInput{{{*/
+bool Matice::IsInput(int name){
+	if (
+				name==MaterialsRheologyBEnum ||
+				name==MaterialsRheologyBbarEnum ||
+				name==MaterialsRheologyNEnum
+		){
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matice.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matice.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matice.h	(revision 12878)
@@ -0,0 +1,74 @@
+/*!\file Matice.h
+ * \brief: header file for matice object
+ */
+
+#ifndef MATICE_H_
+#define MATICE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Material.h"
+class IoModel;
+/*}}}*/
+
+class Matice: public Material{
+
+	private: 
+		/*Id*/
+		int	   mid;
+
+		/*hooks: */
+		Hook* helement;
+
+	public:
+		/*WARNING: input should not be public but it is an easy way to update B from T (using UpdateFromSolution) from Pentas*/
+		Inputs*  inputs;
+
+		/*Matice constructors, destructors: {{{*/
+		Matice();
+		Matice(int mid,int i, IoModel* iomodel);
+		~Matice();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		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* vector,int input_enum);
+		/*}}}*/
+		/*Matice Numerics: {{{*/
+		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   GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		void   GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		IssmDouble GetB();
+		IssmDouble GetBbar();
+		IssmDouble GetN();
+		bool   IsInput(int name);
+		/*}}}*/
+};
+
+#endif  /* _MATICE_H_ */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matpar.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matpar.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matpar.cpp	(revision 12878)
@@ -0,0 +1,361 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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){
+
+	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);
+	
+	iomodel->Constant(&this->hydro_CR,HydrologyCREnum);
+	iomodel->Constant(&this->kn,HydrologyKnEnum);
+	iomodel->Constant(&this->hydro_n,HydrologyNEnum);
+	iomodel->Constant(&this->hydro_p,HydrologyPEnum);
+	iomodel->Constant(&this->hydro_q,HydrologyQEnum);
+}
+/*}}}*/
+/*FUNCTION Matpar::~Matpar() {{{*/
+Matpar::~Matpar(){
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Matpar::Echo {{{*/
+void Matpar::Echo(void){
+
+	_printLine_("Matpar:");
+	_printLine_("   mid: " << mid);
+	_printLine_("   rho_ice: " << rho_ice);
+	_printLine_("   rho_water: " << rho_water);
+	_printLine_("   rho_freshwater: " << rho_freshwater);
+	_printLine_("   mu_water: " << mu_water);
+	_printLine_("   heatcapacity: " << heatcapacity);
+	_printLine_("   thermalconductivity: " << thermalconductivity);
+	_printLine_("   latentheat: " << latentheat);
+	_printLine_("   beta: " << beta);
+	_printLine_("   meltingpoint: " << meltingpoint);
+	_printLine_("   referencetemperature: " << referencetemperature);
+	_printLine_("   mixed_layer_capacity: " << mixed_layer_capacity);
+	_printLine_("   thermal_exchange_velocity: " << thermal_exchange_velocity);
+	_printLine_("   g: " << g);
+	return;
+}
+/*}}}*/
+/*FUNCTION Matpar::DeepEcho {{{*/
+void Matpar::DeepEcho(void){
+
+	this->Echo();
+}		
+/*}}}*/
+/*FUNCTION Matpar::Id {{{*/
+int    Matpar::Id(void){ return mid; }
+/*}}}*/
+/*FUNCTION Matpar::MyRank {{{*/
+int    Matpar::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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;
+		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::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::GetThermalConductivity {{{*/
+IssmDouble Matpar::GetThermalConductivity(){
+	return thermalconductivity;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetThermalExchangeVelocity {{{*/
+IssmDouble Matpar::GetThermalExchangeVelocity(){
+	return thermal_exchange_velocity;
+}
+/*}}}*/
+/*FUNCTION Matpar::GetKn {{{*/		 
+IssmDouble Matpar::GetKn(){			 
+	return 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::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;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matpar.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matpar.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Materials/Matpar.h	(revision 12878)
@@ -0,0 +1,99 @@
+/*!\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;
+
+		/*hydrology: */		 
+		IssmDouble  kn;			 
+		IssmDouble  hydro_p;		 
+		IssmDouble  hydro_q;		 
+		IssmDouble  hydro_CR;			 
+		IssmDouble  hydro_n; 
+
+	public:
+		Matpar();
+		Matpar(int matpar_id, IoModel* iomodel);
+		~Matpar();
+
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		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){_error2_("not implemented yet");};
+		/*}}}*/
+		/*Material virtual functions resolution: {{{*/
+		void   InputDuplicate(int original_enum,int new_enum){_error2_("not implemented yet");};
+		void   Configure(Elements* elements);
+		void   GetVectorFromInputs(Vector* vector,int input_enum){return;}
+		/*}}}*/
+		/*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 GetKn();
+		IssmDouble GetHydrologyP();
+		IssmDouble GetHydrologyQ();
+		IssmDouble GetHydrologyCR();
+		IssmDouble GetHydrologyN();
+		IssmDouble TMeltingPoint(IssmDouble pressure);
+		IssmDouble PureIceEnthalpy(IssmDouble pressure);
+		IssmDouble GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure);
+		void   EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure);
+		void   ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure);
+		/*}}}*/
+
+};
+
+#endif  /* _MATPAR_H_ */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Node.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Node.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Node.cpp	(revision 12878)
@@ -0,0 +1,1012 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "./objects.h"
+#include "../../Container/Container.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../modules/modules.h"
+/*}}}*/
+
+/*Node constructors and destructors:*/
+/*FUNCTION Node::Node() default constructor {{{*/
+Node::Node(){
+		 this->inputs=NULL;
+		 this->hvertex=NULL;
+		 return;
+}
+/*}}}*/
+/*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!
+
+	//intialize inputs, and add as many inputs per element as requested: 
+	this->inputs=new Inputs();
+	if (iomodel->Data(MeshVertexonbedEnum))
+	 this->inputs->AddInput(new BoolInput(MeshVertexonbedEnum,reCast<IssmBool>(iomodel->Data(MeshVertexonbedEnum)[io_index])));
+	if (iomodel->Data(MeshVertexonsurfaceEnum))
+	 this->inputs->AddInput(new BoolInput(MeshVertexonsurfaceEnum,reCast<IssmBool>(iomodel->Data(MeshVertexonsurfaceEnum)[io_index])));
+	if (iomodel->Data(MaskVertexonfloatingiceEnum))
+	 this->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,reCast<IssmBool>(iomodel->Data(MaskVertexonfloatingiceEnum)[io_index])));
+	if (iomodel->Data(MaskVertexongroundediceEnum))
+	  this->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,reCast<IssmBool>(iomodel->Data(MaskVertexongroundediceEnum)[io_index])));
+	if (analysis_type==DiagnosticHorizAnalysisEnum)
+	 this->inputs->AddInput(new IntInput(ApproximationEnum,reCast<IssmInt>(iomodel->Data(FlowequationVertexEquationEnum)[io_index])));
+	/*set single point constraints: */
+
+	/*spc all nodes on water*/
+	if (!iomodel->Data(MaskVertexonwaterEnum)) _error2_("iomodel->nodeonwater is NULL");
+	if (reCast<IssmBool>(iomodel->Data(MaskVertexonwaterEnum)[io_index])){
+		for(k=1;k<=gsize;k++){
+			this->FreezeDof(k);
+		}
+	}
+
+	/*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 && !iomodel->Data(MeshVertexonbedEnum)[io_index]){
+				for(k=1;k<=gsize;k++) this->FreezeDof(k);
+			}
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealPattynApproximationEnum && iomodel->Data(FlowequationBordermacayealEnum)[io_index]){
+				if(!iomodel->Data(MeshVertexonbedEnum)[io_index]){
+					for(k=1;k<=gsize;k++) this->FreezeDof(k);
+				}
+			}
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealStokesApproximationEnum && iomodel->Data(FlowequationBordermacayealEnum)[io_index]){
+				if(!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){
+			for(k=1;k<=gsize;k++){
+				this->FreezeDof(k);
+			}
+		}
+	}
+	#endif
+
+	/*Diagnostic Hutter*/
+	if (analysis_type==DiagnosticHutterAnalysisEnum){
+		if (!iomodel->Data(FlowequationVertexEquationEnum)) _error2_("iomodel->vertices_type is NULL");
+		/*Constrain all nodes that are not Hutter*/
+		if (reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[io_index])!=HutterApproximationEnum){
+			for(k=1;k<=gsize;k++){
+				this->FreezeDof(k);
+			}
+		}
+	}
+
+	/*Prognostic/ Melting/ Slopecompute/ Balancethickness*/
+	if (
+				analysis_type==PrognosticAnalysisEnum || 
+				analysis_type==MeltingAnalysisEnum || 
+				analysis_type==BedSlopeAnalysisEnum || 
+				analysis_type==SurfaceSlopeAnalysisEnum || 
+				analysis_type==BalancethicknessAnalysisEnum
+				){
+		if (dim==3){
+			/*On a 3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
+			_assert_(iomodel->Data(MeshVertexonbedEnum));
+			if (!(reCast<IssmBool>(iomodel->Data(MeshVertexonbedEnum)[io_index]))){
+				for(k=1;k<=gsize;k++){
+					this->FreezeDof(k);
+				}
+			}
+		}
+	}
+
+}
+/*}}}*/
+/*FUNCTION Node::~Node(){{{*/
+Node::~Node(){
+	delete inputs;
+	delete hvertex;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Node::Echo{{{*/
+void Node::Echo(void){
+
+	_printLine_("Node:");
+	_printLine_("   id: " << id);
+	_printLine_("   sid: " << sid);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	indexing.Echo();
+	_printLine_("   hvertex:     not displayed");
+	_printLine_("   inputs:      " << inputs);
+
+
+}
+/*}}}*/
+/*FUNCTION Node::DeepEcho{{{*/
+void Node::DeepEcho(void){
+
+	_printLine_("Node:");
+	_printLine_("   id: " << id);
+	_printLine_("   sid: " << sid);
+	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
+	indexing.DeepEcho();
+	_printLine_("Vertex:");
+	hvertex->DeepEcho();
+	_printLine_("   inputs");
+
+
+}
+/*}}}*/
+/*FUNCTION Node::Id{{{*/
+int    Node::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Node::MyRank{{{*/
+int    Node::MyRank(void){ 
+	extern int my_rank;
+
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION Node::ObjectEnum{{{*/
+int Node::ObjectEnum(void){
+
+	return NodeEnum;
+
+}
+/*}}}*/
+
+/*Node management:*/
+/*FUNCTION Node::Configure {{{*/
+void  Node::Configure(DataSet* nodesin,Vertices* verticesin){
+
+	int i;
+
+	/*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 _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Node::GetDofList1{{{*/
+int  Node::GetDofList1(void){
+
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)this->hvertex->delivers();
+
+	return vertex->dof;
+}
+/*}}}*/
+/*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 _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+}
+/*}}}*/
+/*FUNCTION Node::GetSidList{{{*/
+int  Node::GetSidList(void){
+
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)this->hvertex->delivers();
+
+	return vertex->sid;
+}
+/*}}}*/
+/*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 _error2_("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 _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+}
+/*}}}*/
+/*FUNCTION Node::Sid{{{*/
+int    Node::Sid(void){ return sid; }
+/*}}}*/
+/*FUNCTION Node::GetVertexId {{{*/
+int   Node::GetVertexId(void){
+
+	Vertex*  vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->id;
+}
+/*}}}*/
+/*FUNCTION Node::GetVertexDof {{{*/
+int   Node::GetVertexDof(void){
+
+	Vertex*  vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->dof;
+}
+/*}}}*/
+#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::SetVertexDof {{{*/
+void   Node::SetVertexDof(int in_dof){
+
+	Vertex*  vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	vertex->dof=in_dof;
+
+}
+/*}}}*/
+/*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){
+
+	int index;
+
+	/*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* pv_g,Vector* pv_f,Vector* 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* 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::GetApproximation {{{*/
+int   Node::GetApproximation(){
+
+	int approximation;
+
+	/*recover parameters: */
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	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 _error2_("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 _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+	return numdofs;
+}
+/*}}}*/
+/*FUNCTION Node::GetSigma {{{*/
+IssmDouble Node::GetSigma(){
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->sigma;
+}
+/*}}}*/
+/*FUNCTION Node::GetX {{{*/
+IssmDouble Node::GetX(){
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->x;
+}
+/*}}}*/
+/*FUNCTION Node::GetY {{{*/
+IssmDouble Node::GetY(){
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->y;
+}
+/*}}}*/
+/*FUNCTION Node::GetZ {{{*/
+IssmDouble Node::GetZ(){
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)hvertex->delivers();
+	return vertex->z;
+}
+/*}}}*/
+/*FUNCTION Node::IsClone {{{*/
+int   Node::IsClone(){
+	
+	return indexing.clone;
+
+}
+/*}}}*/
+/*FUNCTION Node::IsOnBed {{{*/
+int   Node::IsOnBed(){
+
+	bool onbed;
+
+	/*recover parameters: */
+	inputs->GetInputValue(&onbed,MeshVertexonbedEnum);
+
+	return onbed;
+}
+/*}}}*/
+/*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::IsOnSurface {{{*/
+int   Node::IsOnSurface(){
+
+	bool onsurface;
+
+	/*recover parameters: */
+	inputs->GetInputValue(&onsurface,MeshVertexonsurfaceEnum);
+
+	return onsurface;
+}
+/*}}}*/
+/*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* 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 _error2_("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* 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 _error2_("VecReduce can only merge from the s or f-set onto the g-set!");
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+}
+/*}}}*/
+
+/* DofObject routines:*/
+/*FUNCTION Node::DistributeDofs{{{*/
+void  Node::DistributeDofs(int* pdofcount,int setenum){
+
+	int i;
+	extern int my_rank;
+	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 _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+
+
+	/*Assign output pointers: */
+	*pdofcount=dofcount;
+
+}
+/*}}}*/
+/*FUNCTION Node::Off_setDofs{{{*/
+void  Node::OffsetDofs(int dofcount,int setenum){
+	
+	int i;
+	extern int my_rank;
+	
+	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 _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Node::ShowTrueDofs{{{*/
+void  Node::ShowTrueDofs(int* truedofs, int ncols,int setenum){
+
+	int j;
+	extern int my_rank;
+	
+	/*Are we a clone? : */
+	if(indexing.clone)return;
+
+	/*Ok, we are not a clone, just plug our dofs into truedofs: */
+	if(setenum==GsetEnum)for(j=0;j<this->indexing.gsize;j++)  *(truedofs+ncols*sid+j)=indexing.gdoflist[j];
+	else if(setenum==FsetEnum)for(j=0;j<this->indexing.fsize;j++)  *(truedofs+ncols*sid+j)=indexing.fdoflist[j];
+	else if(setenum==SsetEnum)for(j=0;j<this->indexing.ssize;j++)  *(truedofs+ncols*sid+j)=indexing.sdoflist[j];
+	else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Node::UpdateCloneDofs{{{*/
+void  Node::UpdateCloneDofs(int* alltruedofs,int ncols,int setenum){
+
+	int j;
+	extern int my_rank;
+	
+	/*If we are not a clone, don't update, we already have dofs!: */
+	if(indexing.clone==0)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: */
+	if(setenum==GsetEnum)for(j=0;j<this->indexing.gsize;j++) indexing.gdoflist[j]=*(alltruedofs+ncols*sid+j);
+	else if(setenum==FsetEnum)for(j=0;j<this->indexing.fsize;j++) indexing.fdoflist[j]=*(alltruedofs+ncols*sid+j);
+	else if(setenum==SsetEnum)for(j=0;j<this->indexing.ssize;j++) indexing.sdoflist[j]=*(alltruedofs+ncols*sid+j);
+	else _error2_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION Node::SetClone {{{*/
+void  Node::SetClone(int* minranks){
+
+	extern int my_rank;
+
+	if (minranks[sid]==my_rank){
+		indexing.clone=0;
+	}
+	else{
+		/*!there is a cpu with lower rank that has the same node, 
+		therefore, I am a clone*/
+		indexing.clone=1; 	
+	}
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Node.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Node.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Node.h	(revision 12878)
@@ -0,0 +1,113 @@
+/*!\file Node.h
+ * \brief: header file for node object
+ */
+
+#ifndef _NODE_H_
+#define _NODE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Object.h"
+#include "../../shared/shared.h"
+#include "../DofIndexing.h"
+class  Inputs;
+class  Hook;
+class  IoModel;
+class  DataSet;
+class  Vertices;
+class  Vector;
+class  Matrix;
+#include "../Update.h"
+/*}}}*/
+
+class Node: public Object ,public Update{
+
+	public: 
+
+		int	    id;  //unique arbitrary id.
+		int     sid; //sid for "serial" id, ie the rank of this node in the nodes dataset, 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   MyRank();
+		int   ObjectEnum();
+		Object* copy(){_error2_("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){_error2_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error2_("Not implemented yet!");}
+		/*}}}*/
+		/*Node numerical routines {{{*/
+		void   Configure(DataSet* nodes,Vertices* vertices);
+		void   CreateNodalConstraints(Vector* ys);
+		void   SetCurrentConfiguration(DataSet* nodes,Vertices* vertices);
+		int    Sid(void); 
+		int    GetVertexDof(void);
+		int    GetVertexId(void);
+#ifdef _HAVE_DIAGNOSTIC_
+		void   GetCoordinateSystem(IssmDouble* coord_system_out);
+#endif
+		void   SetVertexDof(int in_dof);
+		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* pv_g,Vector* pv_f,Vector* pv_s);
+		int    GetConnectivity();
+		void   GetDofList(int* poutdoflist,int approximation_enum,int setenum);
+		void   GetLocalDofList(int* poutdoflist,int approximation_enum,int setenum);
+		int    GetDofList1(void);
+		int    GetSidList(void);
+		IssmDouble GetX();
+		IssmDouble GetY();
+		IssmDouble GetZ();
+		IssmDouble GetSigma();
+		int    IsOnBed();
+		int    IsOnSurface();
+		void   FreezeDof(int dof);
+		int    IsFloating();
+		int    IsGrounded();
+		void   UpdateSpcs(IssmDouble* ys);
+		void   VecMerge(Vector* ug, IssmDouble* vector_serial,int setenum);
+		void   VecReduce(Vector* vector, IssmDouble* ug_serial,int setnum);
+		
+		/*}}}*/
+		/*Dof Object routines {{{*/
+		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);
+		/*}}}*/
+};
+
+#endif  /* _NODE_H_ */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Object.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Object.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Object.h	(revision 12878)
@@ -0,0 +1,27 @@
+/*
+ * 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   MyRank()=0;
+		virtual int   ObjectEnum()=0;
+		virtual Object* copy()=0;
+
+};
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/Option.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/Option.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/Option.cpp	(revision 12878)
@@ -0,0 +1,116 @@
+/*!\file Option.cpp
+ * \brief: implementation of the optionsobject abstract 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 "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../io/io.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION Option::Option(){{{*/
+Option::Option(){
+
+	name  =NULL;
+	numel =0;
+	ndims =0;
+	size  =NULL;
+
+}
+/*}}}*/
+/*FUNCTION Option::~Option(){{{*/
+Option::~Option(){
+
+	if(size) xDelete<int>(size);
+	if(name) xDelete<char>(name);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION Option::Echo {{{*/
+void  Option::Echo(){
+
+	char  cstr[81];
+	bool  flag=true;
+
+	if(flag) _pprintLine_("          name: \"" << name << "\"");
+	if(flag) _pprintLine_("         numel: " << numel);
+	if(flag) _pprintLine_("         ndims: " << ndims);
+	if(size){
+		StringFromSize(cstr,size,ndims);
+		if(flag) _pprintLine_("          size: " << cstr);
+	}
+	else if(flag) _pprintLine_("          size: [empty]");
+}
+/*}}}*/
+/*FUNCTION Option::DeepEcho() {{{*/
+void  Option::DeepEcho(){
+
+	char  indent[81]="";
+
+	Option::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Option::DeepEcho(char* indent) {{{*/
+void  Option::DeepEcho(char* indent){
+
+	char  cstr[81];
+	bool  flag=true;
+
+	if(flag) _pprintLine_(indent << "          name: \"" << name << "\"");
+	if(flag) _pprintLine_(indent << "         numel: " << numel);
+	if(flag) _pprintLine_(indent << "         ndims: " << ndims);
+	if(size){
+		StringFromSize(cstr,size,ndims);
+		if(flag) _pprintLine_(indent << "          size: " << cstr);
+	}
+	else if(flag) _pprintLine_(indent << "          size: [empty]");
+}
+/*}}}*/
+/*FUNCTION Option::Name {{{*/
+char* Option::Name(){
+
+	return(name);
+}
+/*}}}*/
+/*FUNCTION Option::NumEl {{{*/
+int   Option::NumEl(){
+
+	return(numel);
+}
+/*}}}*/
+/*FUNCTION Option::NDims {{{*/
+int   Option::NDims(){
+
+	return(ndims);
+}
+/*}}}*/
+/*FUNCTION Option::Size {{{*/
+int*  Option::Size(){
+
+	return(size);
+}
+/*}}}*/
+/*FUNCTION Option::Get {{{*/
+//void* Option::Get(){
+
+//	;
+
+//	return;
+//}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/Option.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/Option.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/Option.h	(revision 12878)
@@ -0,0 +1,55 @@
+/*! \file Option.h 
+ *  \brief: header file for option abstract object
+ */
+
+#ifndef _OPTIONOBJECT_H_
+#define _OPTIONOBJECT_H_
+
+/*Headers:{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+
+#include "../Object.h"
+/*}}}*/
+
+class Option: public Object {
+
+	public:
+
+		char* name;
+		int   numel;
+		int   ndims;
+		int*  size;
+
+		/*Option constructors, destructors {{{*/
+		Option();
+		~Option();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		virtual void  Echo();
+		virtual void  DeepEcho();
+		virtual void  DeepEcho(char* indent);
+		int   Id(){_error2_("Not implemented yet");};
+		int   MyRank(){_error2_("Not implemented yet");};
+		int   ObjectEnum(){return OptionEnum;};
+		Object* copy(){_error2_("Not implemented yet");};
+		/*}}}*/
+
+		/*virtual functions: */
+		virtual char* Name()=0;
+		virtual int   NumEl()=0;
+		virtual int   NDims()=0;
+		virtual int*  Size()=0;
+		virtual void  Get(int* pvalue)=0;
+		virtual void  Get(IssmDouble* pvalue)=0;
+		virtual void  Get(bool* pvalue)=0;
+		virtual void  Get(char** pvalue)=0;
+		virtual void  Get(char*** ppvalue,int *pnumel)=0;
+		virtual void  Get(IssmDouble** pvalue,int *pnumel)=0;
+		virtual void  Get(Options** pvalue)=0;
+		virtual void  Get(Options*** ppvalue,int *pnumel)=0;
+
+};
+#endif  /* _OPTIONOBJECT_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionCell.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionCell.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionCell.cpp	(revision 12878)
@@ -0,0 +1,127 @@
+/*!\file OptionCell.cpp
+ * \brief: implementation of the optionscell 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 "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION OptionCell::OptionCell(){{{*/
+OptionCell::OptionCell(){
+
+	values    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION OptionCell::~OptionCell(){{{*/
+OptionCell::~OptionCell(){
+
+	if (values){
+		delete values;
+		values    =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION OptionCell::Echo {{{*/
+void  OptionCell::Echo(){
+
+	char cstr[81];
+	bool flag     = true;
+
+	if(flag) _pprintLine_("OptionCell Echo:");
+	Option::Echo();
+
+	if (values && size) {
+		StringFromSize(cstr,size,ndims);
+		if(flag) _pprintLine_("        values: " << cstr << " " << "cell");
+	}
+	else if(flag) _pprintLine_("        values: [empty]");
+}
+/*}}}*/
+/*FUNCTION OptionCell::DeepEcho() {{{*/
+void  OptionCell::DeepEcho(){
+
+	char  indent[81]="";
+
+	OptionCell::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION OptionCell::DeepEcho(char* indent) {{{*/
+void  OptionCell::DeepEcho(char* indent){
+
+	int   i;
+	int*  dims;
+	char  indent2[81];
+	char  cstr[81];
+	bool  flag=true;
+
+	if(flag) _pprintLine_(indent << "OptionCell DeepEcho:");
+	Option::DeepEcho(indent);
+
+	xMemCpy<char>(indent2,indent,(strlen(indent)+1));
+	strcat(indent2,"  ");
+
+	if (values->Size()) {
+		dims=xNew<int>(ndims);
+		for (i=0; i<values->Size(); i++) {
+			ColumnWiseDimsFromIndex(dims,i,size,ndims);
+			StringFromDims(cstr,dims,ndims);
+			if(flag) _pprintLine_(indent << "        values: -------- begin " << cstr << " --------");
+			((Option *)values->GetObjectByOffset(i))->DeepEcho(indent2);
+			if(flag) _pprintLine_(indent << "        values: --------  end  " << cstr << " --------");
+		}
+		xDelete<int>(dims);
+	}
+	else if(flag) _pprintLine_(indent << "        values: [empty]");
+}
+/*}}}*/
+/*FUNCTION OptionCell::Name {{{*/
+char* OptionCell::Name(){
+
+	return(Option::Name());
+}
+/*}}}*/
+/*FUNCTION OptionCell::NumEl {{{*/
+int   OptionCell::NumEl(){
+
+	return(Option::NumEl());
+}
+/*}}}*/
+/*FUNCTION OptionCell::NDims {{{*/
+int   OptionCell::NDims(){
+
+	return(Option::NDims());
+}
+/*}}}*/
+/*FUNCTION OptionCell::Size {{{*/
+int*  OptionCell::Size(){
+
+	return(Option::Size());
+}
+/*}}}*/
+/*FUNCTION OptionCell::Get(Options** pvalue) {{{*/
+void OptionCell::Get(Options** pvalue){
+
+	/*Assign output pointer*/
+	*pvalue=this->values;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionCell.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionCell.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionCell.h	(revision 12878)
@@ -0,0 +1,52 @@
+/*! \file OptionCell.h 
+ *  \brief: header file for optioncell object
+ */
+
+#ifndef _OPTIONCELL_H_
+#define _OPTIONCELL_H_
+
+/*Headers:{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./Option.h"
+/*}}}*/
+
+class OptionCell: public Option {
+
+	public:
+
+		Options* values;
+
+		/*OptionCell constructors, destructors {{{*/
+		OptionCell();
+		~OptionCell();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(char* indent);
+		int   Id(){_error2_("Not implemented yet");};
+		int   MyRank(){_error2_("Not implemented yet");};
+		int   ObjectEnum(){return OptionCellEnum;};
+		Object* copy(){_error2_("Not implemented yet");};
+		/*}}}*/
+
+		/*virtual functions: */
+		char* Name();
+		int   NumEl();
+		int   NDims();
+		int*  Size();
+		void  Get(int* pvalue){_error2_("An OptionCell object cannot return a int");};
+		void  Get(IssmDouble* pvalue){_error2_("An OptionCell object cannot return a IssmDouble");};
+		void  Get(bool* pvalue){  _error2_("An OptionCell object cannot return a bool");};
+		void  Get(char** pvalue){ _error2_("An OptionCell object cannot return a string");};
+		void  Get(char*** ppvalue,int *pnumel){ _error2_("An OptionCell object cannot return a string vec");};
+		void  Get(IssmDouble** pvalue,int *pnumel){ _error2_("An OptionCell object cannot return a IssmDouble vec");};
+		void  Get(Options** pvalue);
+		void  Get(Options*** ppvalue,int *pnumel){ _error2_("An OptionCell object cannot return an Options DataSet vec");};
+
+};
+#endif  /* _OPTIONCELL_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionChar.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionChar.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionChar.cpp	(revision 12878)
@@ -0,0 +1,176 @@
+/*!\file OptionChar.cpp
+ * \brief: implementation of the optionschar 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 "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION OptionChar::OptionChar(){{{*/
+OptionChar::OptionChar(){
+
+	values    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION OptionChar::~OptionChar(){{{*/
+OptionChar::~OptionChar(){
+
+	if (values) xDelete<char>(values);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION OptionChar::Echo {{{*/
+void  OptionChar::Echo(){
+
+	char  cstr[81];
+	bool  flag=true;
+
+	if(flag) _pprintLine_("OptionChar Echo:");
+	Option::Echo();
+
+	if (values && size) {
+//		if (numel == 1) {
+		if (1) {
+//			if(flag) _pprintLine_("        values: \"" << values[0] << "\"");
+			if(flag) _pprintLine_("        values: \"" << values << "\"");
+		}
+		else {
+			StringFromSize(cstr,size,ndims);
+			if(flag) _pprintLine_("        values: " << cstr << " " << "char");
+		}
+	}
+	else if(flag) _pprintLine_("        values: [empty]");
+}
+/*}}}*/
+/*FUNCTION OptionChar::DeepEcho() {{{*/
+void  OptionChar::DeepEcho(){
+
+	char  indent[81]="";
+
+	OptionChar::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION OptionChar::DeepEcho(char* indent) {{{*/
+void  OptionChar::DeepEcho(char* indent){
+
+	int   i,nstr,ipt=0;
+	int*  dims;
+	char  indent2[81];
+	char  cstr[81];
+	bool  flag=true;
+
+	if(flag) _pprintLine_(indent << "OptionChar DeepEcho:");
+	Option::DeepEcho(indent);
+
+	xMemCpy<char>(indent2,indent,(strlen(indent)+1));
+	strcat(indent2,"  ");
+
+	if (values) {
+		if (ndims == 2 && size[0] == 1) {
+			if(flag) _pprintLine_(indent << "        values: \"" << values << "\"");
+		}
+		else {
+			nstr=size[0];
+			for (i=2; i<ndims; i++) nstr*=size[i];
+
+			dims=xNew<int>(ndims);
+			for (i=0; i<nstr; i++) {
+				RowWiseDimsFromIndex(dims,ipt,size,ndims);
+				StringFromDims(cstr,dims,ndims);
+				if(flag) _pprintLine_(indent << "        values" << cstr << ": \"" << size[1] << "*s\"");
+				ipt+=size[1];
+			}
+			xDelete<int>(dims);
+		}
+	}
+	else if(flag) _pprintLine_(indent << "        values: [empty]");
+}
+/*}}}*/
+/*FUNCTION OptionChar::Name {{{*/
+char* OptionChar::Name(){
+
+	return(Option::Name());
+}
+/*}}}*/
+/*FUNCTION OptionChar::NumEl {{{*/
+int   OptionChar::NumEl(){
+
+	return(Option::NumEl());
+}
+/*}}}*/
+/*FUNCTION OptionChar::NDims {{{*/
+int   OptionChar::NDims(){
+
+	return(Option::NDims());
+}
+/*}}}*/
+/*FUNCTION OptionChar::Size {{{*/
+int*  OptionChar::Size(){
+
+	return(Option::Size());
+}
+/*}}}*/
+/*FUNCTION OptionChar::Get(char** pvalue) {{{*/
+void OptionChar::Get(char** pvalue){
+
+	char* outstring=NULL;
+	int   stringsize;
+
+	stringsize=strlen(this->values)+1;
+
+	outstring=xNew<char>(stringsize);
+	xMemCpy<char>(outstring,this->values,stringsize);
+
+	*pvalue=outstring;
+}
+/*}}}*/
+/*FUNCTION OptionChar::Get(char*** ppvalue,int *pnumel) {{{*/
+void OptionChar::Get(char*** ppvalue,int *pnumel){
+
+	char* outstring=NULL;
+	int   stringsize;
+	int   i,nstr,ipt=0;
+
+	/*We should first check that the size is at least one*/
+	if(this->NumEl()<=0){
+		_error2_("option \"" << this->name << "\" is empty and cannot return a string vector");
+	}
+
+	/*Calculate the size and number of strings*/
+	stringsize=this->size[1]+1;
+	nstr=this->size[0];
+	for (i=2; i<this->ndims; i++) nstr*=this->size[i];
+
+	/*Break concatenated string into individual strings*/
+	*ppvalue=xNew<char*>(nstr);
+	for (i=0; i<nstr; i++) {
+		outstring=xNew<char>(stringsize);
+		xMemCpy<char>(outstring,&(this->values[ipt]),(stringsize-1));
+		outstring[stringsize-1]='\0';
+		(*ppvalue)[i]=outstring;
+		ipt+=stringsize-1;
+	}
+
+	/*Assign output pointer*/
+	if(numel) *pnumel=nstr;
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionChar.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionChar.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionChar.h	(revision 12878)
@@ -0,0 +1,52 @@
+/*! \file OptionChar.h 
+ *  \brief: header file for optionchar object
+ */
+
+#ifndef _OPTIONCHAR_H_
+#define _OPTIONCHAR_H_
+
+/*Headers:{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./Option.h"
+/*}}}*/
+
+class OptionChar: public Option {
+
+	public:
+
+		char* values;
+
+		/*OptionChar constructors, destructors {{{*/
+		OptionChar();
+		~OptionChar();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(char* indent);
+		int   Id(){_error2_("Not implemented yet");};
+		int   MyRank(){_error2_("Not implemented yet");};
+		int   ObjectEnum(){return OptionCharEnum;};
+		Object* copy(){_error2_("Not implemented yet");};
+		/*}}}*/
+
+		/*virtual functions: */
+		char* Name();
+		int   NumEl();
+		int   NDims();
+		int*  Size();
+		void  Get(int* pvalue){_error2_("An OptionChar object cannot return a int");};
+		void  Get(IssmDouble* pvalue){_error2_("An OptionChar object cannot return a IssmDouble");};
+		void  Get(bool* pvalue){  _error2_("An OptionChar object cannot return a bool");};
+		void  Get(char** pvalue);
+		void  Get(char*** ppvalue,int *pnumel);
+		void  Get(IssmDouble** pvalue,int *pnumel){ _error2_("An OptionChar object cannot return a IssmDouble vec");};
+		void  Get(Options** pvalue){ _error2_("An OptionChar object cannot return an Options DataSet");};
+		void  Get(Options*** ppvalue,int *pnumel){ _error2_("An OptionChar object cannot return an Options DataSet vec");};
+
+};
+#endif  /* _OPTIONCHAR_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionDouble.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionDouble.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionDouble.cpp	(revision 12878)
@@ -0,0 +1,162 @@
+/*!\file OptionDouble.cpp
+ * \brief: implementation of the optionsIssmDouble 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 "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION OptionDouble::OptionDouble(){{{*/
+OptionDouble::OptionDouble(){
+
+	values    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION OptionDouble::~OptionDouble(){{{*/
+OptionDouble::~OptionDouble(){
+
+	if (values) xDelete<IssmDouble>(values);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION OptionDouble::Echo {{{*/
+void  OptionDouble::Echo(){
+
+	char  cstr[81];
+	bool  flag=true;
+
+	if(flag) _pprintLine_("OptionDouble Echo:");
+	Option::Echo();
+
+	if (values && size) {
+		if(numel == 1) if(flag) _pprintLine_("        values: " << values[0]);
+		else {
+			StringFromSize(cstr,size,ndims);
+			if(flag) _pprintLine_("        values: " << cstr << " " << "IssmDouble");
+		}
+	}
+	else if(flag) _pprintLine_("        values: [empty]");
+}
+/*}}}*/
+/*FUNCTION OptionDouble::DeepEcho() {{{*/
+void  OptionDouble::DeepEcho(){
+
+	char  indent[81]="";
+
+	OptionDouble::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION OptionDouble::DeepEcho(char* indent) {{{*/
+void  OptionDouble::DeepEcho(char* indent){
+
+	int   i;
+	int*  dims;
+	char  indent2[81];
+	char  cstr[81];
+	bool  flag=true;
+
+	if(flag) _pprintLine_(indent << "OptionDouble DeepEcho:");
+	Option::DeepEcho(indent);
+
+	xMemCpy<char>(indent2,indent,(strlen(indent)+1));
+	strcat(indent2,"  ");
+
+	if (values) {
+		dims=xNew<int>(ndims);
+		if(numel==1) if(flag) _pprintLine_(indent << "        values: " << values[0]);
+		else{
+			for (i=0; i<numel; i++) {
+				RowWiseDimsFromIndex(dims,i,size,ndims);
+				StringFromDims(cstr,dims,ndims);
+				if(flag) _pprintLine_(indent << "        values" << cstr << ": " << values[i]);
+			}
+		}
+		xDelete<int>(dims);
+	}
+	else if(flag) _pprintLine_(indent << "        values: [empty]");
+}
+/*}}}*/
+/*FUNCTION OptionDouble::Name {{{*/
+char* OptionDouble::Name(){
+
+	return(Option::Name());
+}
+/*}}}*/
+/*FUNCTION OptionDouble::NumEl {{{*/
+int   OptionDouble::NumEl(){
+
+	return(Option::NumEl());
+}
+/*}}}*/
+/*FUNCTION OptionDouble::NDims {{{*/
+int   OptionDouble::NDims(){
+
+	return(Option::NDims());
+}
+/*}}}*/
+/*FUNCTION OptionDouble::Size {{{*/
+int*  OptionDouble::Size(){
+
+	return(Option::Size());
+}
+/*}}}*/
+/*FUNCTION OptionDouble::Get(int* pvalue) {{{*/
+void OptionDouble::Get(int* pvalue){
+
+	/*We should first check that the size is one*/
+	if(this->NumEl()!=1){
+		_error2_("option \"" << this->name << "\" has " << this->NumEl() << " elements and cannot return a single int");
+	}
+
+	/*Assign output pointer*/
+	*pvalue=reCast<int>(values[0]);
+}
+/*}}}*/
+/*FUNCTION OptionDouble::Get(IssmDouble* pvalue) {{{*/
+void OptionDouble::Get(IssmDouble* pvalue){
+
+	/*We should first check that the size is one*/
+	if(this->NumEl()!=1){
+		_error2_("option \"" << this->name << "\" has " << this->NumEl() << " elements and cannot return a single IssmDouble");
+	}
+
+	/*Assign output pointer*/
+	*pvalue=this->values[0];
+}
+/*}}}*/
+/*FUNCTION OptionDouble::Get(IssmDouble** pvalue,int* numel) {{{*/
+void OptionDouble::Get(IssmDouble** pvalue,int* numel){
+
+	/*We should first check that the size is at least one*/
+	if(this->NumEl()<=0){
+		_error2_("option \"" << this->name << "\" is empty and cannot return a IssmDouble vector");
+	}
+
+	/*Copy vector*/
+	IssmDouble* outvalue=xNew<IssmDouble>(this->NumEl());
+	for(int i=0;i<this->NumEl();i++) outvalue[i]=this->values[i];
+
+	/*Assign output pointer*/
+	*pvalue=outvalue;
+	if(numel) *numel=this->NumEl();
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionDouble.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionDouble.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionDouble.h	(revision 12878)
@@ -0,0 +1,52 @@
+/*! \file OptionDouble.h 
+ *  \brief: header file for optionIssmDouble object
+ */
+
+#ifndef _OPTIONDOUBLE_H_
+#define _OPTIONDOUBLE_H_
+
+/*Headers:{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./Option.h"
+/*}}}*/
+
+class OptionDouble: public Option {
+
+	public:
+
+		IssmDouble* values;
+
+		/*OptionDouble constructors, destructors {{{*/
+		OptionDouble();
+		~OptionDouble();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(char* indent);
+		int   Id(){_error2_("Not implemented yet");};
+		int   MyRank(){_error2_("Not implemented yet");};
+		int   ObjectEnum(){return OptionDoubleEnum;};
+		Object* copy(){_error2_("Not implemented yet");};
+		/*}}}*/
+
+		/*virtual functions: */
+		char* Name();
+		int   NumEl();
+		int   NDims();
+		int*  Size();
+		void  Get(int* pvalue);
+		void  Get(IssmDouble* pvalue);
+		void  Get(bool* pvalue){  _error2_("An OptionDouble object cannot return a bool");};
+		void  Get(char** pvalue){ _error2_("An OptionDouble object cannot return a string");};
+		void  Get(char*** ppvalue,int *pnumel){ _error2_("An OptionDouble object cannot return a string vec");};
+		void  Get(IssmDouble** pvalue,int* pnumel);
+		void  Get(Options** pvalue){ _error2_("An OptionDouble object cannot return an Options DataSet");};
+		void  Get(Options*** ppvalue,int *pnumel){ _error2_("An OptionDouble object cannot return an Options DataSet vec");};
+
+};
+#endif  /* _OPTIONDOUBLE_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionLogical.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionLogical.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionLogical.cpp	(revision 12878)
@@ -0,0 +1,133 @@
+/*!\file OptionLogical.cpp
+ * \brief: implementation of the optionslogical 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 "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION OptionLogical::OptionLogical(){{{*/
+OptionLogical::OptionLogical(){
+
+	values    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION OptionLogical::~OptionLogical(){{{*/
+OptionLogical::~OptionLogical(){
+
+	if (values) xDelete<bool>(values);
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION OptionLogical::Echo {{{*/
+void  OptionLogical::Echo(){
+
+	char  cstr[81];
+	bool  flag=true;
+
+	if(flag) _pprintLine_("OptionLogical Echo:");
+	Option::Echo();
+
+	if (values && size) {
+		if(numel == 1) if(flag) _pprintLine_("        values: " << (values[0] ? "true" : "false"));
+		else{
+			StringFromSize(cstr,size,ndims);
+			if(flag) _pprintLine_("        values: " << cstr << " " << "logical");
+		}
+	}
+	else if(flag) _pprintLine_("        values: [empty]");
+}
+/*}}}*/
+/*FUNCTION OptionLogical::DeepEcho() {{{*/
+void  OptionLogical::DeepEcho(){
+
+	char  indent[81]="";
+
+	OptionLogical::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION OptionLogical::DeepEcho(char* indent) {{{*/
+void  OptionLogical::DeepEcho(char* indent){
+
+	int   i;
+	int*  dims;
+	char  indent2[81];
+	char  cstr[81];
+	bool  flag=true;
+
+	if(flag) _pprintLine_(indent << "OptionLogical DeepEcho:");
+	Option::DeepEcho(indent);
+
+	xMemCpy<char>(indent2,indent,(strlen(indent)+1));
+	strcat(indent2,"  ");
+
+	if (values) {
+		if(numel==1) if(flag) _pprintLine_(indent << "        values: " << (values[0] ? "true" : "false"));
+		else{
+			dims=xNew<int>(ndims);
+			for (i=0; i<numel; i++) {
+				RowWiseDimsFromIndex(dims,i,size,ndims);
+				StringFromDims(cstr,dims,ndims);
+				if(flag) _pprintLine_(indent << "        values" << cstr << ": " << (values[i] ? "true" : "false"));
+			}
+			xDelete<int>(dims);
+		}
+	}
+	else if(flag) _pprintLine_(indent << "        values: [empty]");
+}
+/*}}}*/
+/*FUNCTION OptionLogical::Name {{{*/
+char* OptionLogical::Name(){
+
+	return(Option::Name());
+}
+/*}}}*/
+/*FUNCTION OptionLogical::NumEl {{{*/
+int   OptionLogical::NumEl(){
+
+	return(Option::NumEl());
+}
+/*}}}*/
+/*FUNCTION OptionLogical::NDims {{{*/
+int   OptionLogical::NDims(){
+
+	return(Option::NDims());
+}
+/*}}}*/
+/*FUNCTION OptionLogical::Size {{{*/
+int*  OptionLogical::Size(){
+
+	return(Option::Size());
+}
+/*}}}*/
+/*FUNCTION OptionLogical::Get(bool* pvalue) {{{*/
+void OptionLogical::Get(bool* pvalue){
+
+	/*We should first check that the size is one*/
+	if(this->NumEl()!=1){
+		_error2_("option \"" << this->name << "\" has " << this->NumEl() << " elements and cannot return a single bool");
+	}
+
+	/*Assign output pointer*/
+	*pvalue=this->values[0];
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionLogical.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionLogical.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionLogical.h	(revision 12878)
@@ -0,0 +1,52 @@
+/*! \file OptionLogical.h 
+ *  \brief: header file for optionlogical object
+ */
+
+#ifndef _OPTIONLOGICAL_H_
+#define _OPTIONLOGICAL_H_
+
+/*Headers:{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./Option.h"
+/*}}}*/
+
+class OptionLogical: public Option {
+
+	public:
+
+		bool* values;
+
+		/*OptionLogical constructors, destructors {{{*/
+		OptionLogical();
+		~OptionLogical();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(char* indent);
+		int   Id(){_error2_("Not implemented yet");};
+		int   MyRank(){_error2_("Not implemented yet");};
+		int   ObjectEnum(){return OptionLogicalEnum;};
+		Object* copy(){_error2_("Not implemented yet");};
+		/*}}}*/
+
+		/*virtual functions: */
+		char* Name();
+		int   NumEl();
+		int   NDims();
+		int*  Size();
+		void  Get(int* pvalue){_error2_("An OptionLogical object cannot return a int");};
+		void  Get(IssmDouble* pvalue){_error2_("An OptionLogical object cannot return a IssmDouble");};
+		void  Get(bool* pvalue);
+		void  Get(char** pvalue){ _error2_("An OptionLogical object cannot return a string");};
+		void  Get(char*** ppvalue,int *pnumel){ _error2_("An OptionLogical object cannot return a string vec");};
+		void  Get(IssmDouble** pvalue,int *pnumel){ _error2_("An OptionLogical object cannot return a IssmDouble vec");};
+		void  Get(Options** pvalue){ _error2_("An OptionLogical object cannot return an Options DataSet");};
+		void  Get(Options*** ppvalue,int *pnumel){ _error2_("An OptionLogical object cannot return an Options DataSet vec");};
+
+};
+#endif  /* _OPTIONLOGICAL_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionStruct.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionStruct.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionStruct.cpp	(revision 12878)
@@ -0,0 +1,153 @@
+/*!\file OptionStruct.cpp
+ * \brief: implementation of the optionsstruct 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 "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../io/io.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*Constructors/destructor/copy*/
+/*FUNCTION OptionStruct::OptionStruct(){{{*/
+OptionStruct::OptionStruct(){
+
+	values    =NULL;
+
+}
+/*}}}*/
+/*FUNCTION OptionStruct::~OptionStruct(){{{*/
+OptionStruct::~OptionStruct(){
+
+	int   i;
+
+	if(values){
+		for(i=0; i<numel; i++) {
+			delete values[i];
+			values[i] =NULL;
+		}
+		xDelete<Options*>(values);
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION OptionStruct::Echo {{{*/
+void  OptionStruct::Echo(){
+
+	char  cstr[81];
+	bool  flag=true;
+
+	if(flag) _pprintLine_("OptionStruct Echo:");
+	Option::Echo();
+
+	if (values && size) {
+		StringFromSize(cstr,size,ndims);
+		if(flag) _pprintLine_("        values: " << cstr << " " << "struct");
+	}
+	else if(flag) _pprintLine_("        values: [empty]");
+}
+/*}}}*/
+/*FUNCTION OptionStruct::DeepEcho() {{{*/
+void  OptionStruct::DeepEcho(){
+
+	char  indent[81]="";
+
+	OptionStruct::DeepEcho(indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION OptionStruct::DeepEcho(char* indent) {{{*/
+void  OptionStruct::DeepEcho(char* indent){
+
+	int   i,j;
+	int*  dims;
+	char  indent2[81];
+	char  cstr[81];
+	bool  flag=true;
+
+	if(flag) _pprintLine_(indent << "OptionStruct DeepEcho:");
+	Option::DeepEcho(indent);
+
+	xMemCpy<char>(indent2,indent,(strlen(indent)+1));
+	strcat(indent2,"  ");
+
+	if (values) {
+		dims=xNew<int>(ndims);
+		for (i=0; i<numel; i++) {
+			ColumnWiseDimsFromIndex(dims,i,size,ndims);
+			StringFromDims(cstr,dims,ndims);
+			if (values[i]->Size()){
+				if(flag) _pprintLine_(indent << "        values: -------- begin " << cstr << " --------");
+				for (j=0; j<values[i]->Size(); j++) ((Option *)values[i]->GetObjectByOffset(j))->DeepEcho(indent2);
+				if(flag) _pprintLine_(indent << "        values: --------  end  " << cstr << " --------");
+			}
+			else if(flag) _pprintLine_(indent << "        values: " << cstr << " [empty]");
+		}
+		xDelete<int>(dims);
+	}
+	else if(flag) _pprintLine_(indent << "        values: [empty]");
+}
+/*}}}*/
+/*FUNCTION OptionStruct::Name {{{*/
+char* OptionStruct::Name(){
+
+	return(Option::Name());
+}
+/*}}}*/
+/*FUNCTION OptionStruct::NumEl {{{*/
+int   OptionStruct::NumEl(){
+
+	return(Option::NumEl());
+}
+/*}}}*/
+/*FUNCTION OptionStruct::NDims {{{*/
+int   OptionStruct::NDims(){
+
+	return(Option::NDims());
+}
+/*}}}*/
+/*FUNCTION OptionStruct::Size {{{*/
+int*  OptionStruct::Size(){
+
+	return(Option::Size());
+}
+/*}}}*/
+/*FUNCTION OptionStruct::Get(Options** pvalue) {{{*/
+void OptionStruct::Get(Options** pvalue){
+
+	/*We should first check that the size is one*/
+	if(this->NumEl()!=1){
+		_error2_("option \"" << this->name << "\" has " << this->NumEl() << " elements and cannot return a single options dataset");
+	}
+
+	/*Assign output pointer*/
+	*pvalue=this->values[0];
+}
+/*}}}*/
+/*FUNCTION OptionStruct::Get(Options*** ppvalue,int* numel) {{{*/
+void OptionStruct::Get(Options*** ppvalue,int* numel){
+
+	/*We should first check that the size is at least one*/
+	if(this->NumEl()<=0){
+		_error2_("option \"" << this->name << "\" is empty and cannot return an options dataset vector");
+	}
+
+	/*Assign output pointer*/
+	*ppvalue=this->values;
+	if(numel) *numel=this->NumEl();
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionStruct.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionStruct.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionStruct.h	(revision 12878)
@@ -0,0 +1,52 @@
+/*! \file OptionStruct.h 
+ *  \brief: header file for optionstruct object
+ */
+
+#ifndef _OPTIONSTRUCT_H_
+#define _OPTIONSTRUCT_H_
+
+/*Headers:{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+
+#include "./Option.h"
+/*}}}*/
+
+class OptionStruct: public Option {
+
+	public:
+
+		Options** values;
+
+		/*OptionStruct constructors, destructors {{{*/
+		OptionStruct();
+		~OptionStruct();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		void  Echo();
+		void  DeepEcho();
+		void  DeepEcho(char* indent);
+		int   Id(){_error2_("Not implemented yet");};
+		int   MyRank(){_error2_("Not implemented yet");};
+		int   ObjectEnum(){return OptionStructEnum;};
+		Object* copy(){_error2_("Not implemented yet");};
+		/*}}}*/
+
+		/*virtual functions: */
+		char* Name();
+		int   NumEl();
+		int   NDims();
+		int*  Size();
+		void  Get(int* pvalue){_error2_("An OptionStruct object cannot return a int");};
+		void  Get(IssmDouble* pvalue){_error2_("An OptionStruct object cannot return a IssmDouble");};
+		void  Get(bool* pvalue){  _error2_("An OptionStruct object cannot return a bool");};
+		void  Get(char** pvalue){ _error2_("An OptionStruct object cannot return a string");};
+		void  Get(char*** ppvalue,int *pnumel){ _error2_("An OptionStruct object cannot return a string vec");};
+		void  Get(IssmDouble** pvalue,int *pnumel){ _error2_("An OptionStruct object cannot return a IssmDouble vec");};
+		void  Get(Options** pvalue);
+		void  Get(Options*** ppvalue,int *pnumel);
+
+};
+#endif  /* _OPTIONSTRUCT_H */
+
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionUtilities.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionUtilities.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionUtilities.cpp	(revision 12878)
@@ -0,0 +1,114 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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) _error2_("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]) _error2_("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) _error2_("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]) _error2_("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/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionUtilities.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionUtilities.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Options/OptionUtilities.h	(revision 12878)
@@ -0,0 +1,24 @@
+/*! \file OptionUtilities.h 
+ *  \brief: header file for option object utilities
+ */
+
+#ifndef _OPTIONUTILITIES_H_
+#define _OPTIONUTILITIES_H_
+
+/*Headers:{{{*/
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../EnumDefinitions/EnumDefinitions.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/branches/trunk-jpl-damage/src/c/classes/objects/Params/BoolParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/BoolParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/BoolParam.cpp	(revision 12878)
@@ -0,0 +1,89 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*BoolParam constructors and destructor*/
+/*FUNCTION BoolParam::BoolParam(){{{*/
+BoolParam::BoolParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolParam::BoolParam(int enum_type,IssmBool value){{{*/
+BoolParam::BoolParam(int in_enum_type,IssmBool 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){
+
+	_printLine_("BoolParam:");
+	_printLine_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " <<(this->value?"true":"false"));
+}
+/*}}}*/
+/*FUNCTION BoolParam::Id{{{*/
+int    BoolParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION BoolParam::MyRank{{{*/
+int    BoolParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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);
+}
+/*}}}*/
+/*FUNCTION BoolParam::UnitConversion{{{*/
+void  BoolParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/BoolParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/BoolParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/BoolParam.h	(revision 12878)
@@ -0,0 +1,77 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/shared.h"
+/*}}}*/
+
+class BoolParam: public Param{
+
+	public:
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		IssmBool value;
+
+		/*BoolParam constructors, destructors: {{{*/
+		BoolParam();
+		BoolParam(int enum_type,IssmBool value);
+		~BoolParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){*pbool=value;}
+		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot return a FILE");}
+
+		void  SetValue(bool boolean){this->value=boolean;}
+		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold an int");}
+		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold an IssmPDouble");}
+		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+		
+		void GetParameterName(char**pname);
+		/*}}}*/
+};
+#endif  /* _BOOLPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatArrayParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatArrayParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatArrayParam.cpp	(revision 12878)
@@ -0,0 +1,252 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("DoubleMatArrayParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   array size: " << this->M);
+	_printLine_("   array pointer: " << this->array);
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::DeepEcho{{{*/
+void DoubleMatArrayParam::DeepEcho(void){
+
+	int i,j,k;
+	int m,n;
+	IssmDouble* matrix=NULL;
+	
+	_printLine_("DoubleMatArrayParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   array size: " << this->M);
+	for(i=0;i<M;i++){
+		_printLine_("   array " << i << " (" << mdim_array[i] << "x" << ndim_array[i] << "):");
+		matrix=array[i];
+		m=mdim_array[i];
+		n=ndim_array[i];
+
+		for(j=0;j<m;j++){
+			_printString_("   ");
+			for(k=0;k<n;k++)_printString_(*(matrix+n*j+k) << " ");
+			_printLine_("");
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::Id{{{*/
+int    DoubleMatArrayParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::MyRank{{{*/
+int    DoubleMatArrayParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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;
+	}
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatArrayParam::UnitConversion{{{*/
+void  DoubleMatArrayParam::UnitConversion(int direction_enum){
+	/*go through all matrices and convert: */
+	for (int i=0;i<this->M;i++){
+		IssmDouble* matrix=this->array[i];
+		int     m=this->mdim_array[i];
+		int     n=this->ndim_array[i];
+		::UnitConversion(matrix,m*n,direction_enum,this->enum_type);
+	}
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatArrayParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatArrayParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatArrayParam.h	(revision 12878)
@@ -0,0 +1,81 @@
+/*! \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 "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims);
+		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << "cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a boolean");}
+		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a scalar");}
+		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a int mat array");}
+		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << "cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("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  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _DOUBLEMATARRAYPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatParam.cpp	(revision 12878)
@@ -0,0 +1,136 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("DoubleMatParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   matrix size: " << this->M << "x" << this->N);
+
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::DeepEcho{{{*/
+void DoubleMatParam::DeepEcho(void){
+
+	int i,j;
+	
+	_printLine_("DoubleMatParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   matrix size: " << this->M << "x" << this->N);
+	for(i=0;i<this->M;i++){
+		for(i=0;i<this->N;i++){
+			_printLine_(i << " " << j << " " << *(this->value+N*i+j));
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::Id{{{*/
+int    DoubleMatParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleMatParam::MyRank{{{*/
+int    DoubleMatParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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){
+	_error2_("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;
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::UnitConversion{{{*/
+void  DoubleMatParam::UnitConversion(int direction_enum){
+	::UnitConversion(this->value,this->M*this->N,direction_enum,this->enum_type);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleMatParam.h	(revision 12878)
@@ -0,0 +1,80 @@
+/*! \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 "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("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){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N);
+		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _DOUBLEMATPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleParam.cpp	(revision 12878)
@@ -0,0 +1,116 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("DoubleParam:");
+	_printLine_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " << this->value);
+}
+/*}}}*/
+/*FUNCTION DoubleParam::Id{{{*/
+int    DoubleParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleParam::MyRank{{{*/
+int    DoubleParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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){
+	_error2_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(bool* pbool){{{*/
+void DoubleParam::GetParameterValue(bool* pbool){
+	_error2_("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){
+	_error2_("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){
+	_error2_("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){
+	_error2_("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){
+	_error2_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::UnitConversion{{{*/
+void  DoubleParam::UnitConversion(int direction_enum){
+	::UnitConversion(&this->value,1,direction_enum,this->enum_type);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleParam.h	(revision 12878)
@@ -0,0 +1,79 @@
+/*! \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 "../../../include/include.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   MyRank();
+		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){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("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){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		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){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _DOUBLEPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleTransientMatParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleTransientMatParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleTransientMatParam.cpp	(revision 12878)
@@ -0,0 +1,30 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+}
+/*}}}*/
+/*FUNCTION DoubleTransientMatParam::UnitConversion{{{*/
+void  DoubleTransientMatParam::UnitConversion(int direction_enum){
+	::UnitConversion(this->value,(this->M-1)*this->N,direction_enum,this->enum_type);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleTransientMatParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleTransientMatParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleTransientMatParam.h	(revision 12878)
@@ -0,0 +1,32 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/shared.h"
+/*}}}*/
+
+class DoubleTransientMatParam: public DoubleMatParam{
+
+	public:
+		/*DoubleTransientMatParam constructors, destructors: {{{*/
+		DoubleTransientMatParam(int enum_type,IssmDouble* value,int M,int N);
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		void  UnitConversion(int direction_enum);
+		/*}}}*/
+};
+#endif  /* _DOUBLETRANSIENTMATPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleVecParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleVecParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleVecParam.cpp	(revision 12878)
@@ -0,0 +1,150 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("DoubleVecParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   vector size: " << this->M);
+
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::DeepEcho{{{*/
+void DoubleVecParam::DeepEcho(void){
+
+	int i;
+	
+	_printLine_("DoubleVecParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   vector size: " << this->M);
+	for(i=0;i<this->M;i++){
+		_printLine_(i << " " << this->values[i]);
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::Id{{{*/
+int    DoubleVecParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DoubleVecParam::MyRank{{{*/
+int    DoubleVecParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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){
+	_error2_("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;
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::UnitConversion{{{*/
+void  DoubleVecParam::UnitConversion(int direction_enum){
+	::UnitConversion(this->values,this->M,direction_enum,this->enum_type);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleVecParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleVecParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/DoubleVecParam.h	(revision 12878)
@@ -0,0 +1,78 @@
+/*! \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 "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param virtual functions definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM);
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");};
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("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){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M);
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");}
+		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+		
+		void GetParameterName(char**pname);
+		/*}}}*/
+};
+#endif  /* _DOUBLEVECPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/FileParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/FileParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/FileParam.cpp	(revision 12878)
@@ -0,0 +1,89 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("FileParam:");
+	_printLine_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " << this->value);
+}
+/*}}}*/
+/*FUNCTION FileParam::Id{{{*/
+int    FileParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION FileParam::MyRank{{{*/
+int    FileParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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);
+}
+/*}}}*/
+/*FUNCTION FileParam::UnitConversion{{{*/
+void  FileParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/FileParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/FileParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/FileParam.h	(revision 12878)
@@ -0,0 +1,78 @@
+/*! \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 "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){  _error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){*pfid=value;};
+
+		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("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){_error2_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntMatParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntMatParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntMatParam.cpp	(revision 12878)
@@ -0,0 +1,131 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("IntMatParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   matrix size: " << this->M << "x" << this->N);
+
+}
+/*}}}*/
+/*FUNCTION IntMatParam::DeepEcho{{{*/
+void IntMatParam::DeepEcho(void){
+
+	int i,j;
+	
+	_printLine_("IntMatParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   matrix size: " << this->M << "x" << this->N);
+	for(i=0;i<this->M;i++){
+		for(i=0;i<this->N;i++){
+			_printLine_("(" << i << "," << j << ") " << *(this->value+N*i+j));
+		}
+	}
+}
+/*}}}*/
+/*FUNCTION IntMatParam::Id{{{*/
+int    IntMatParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntMatParam::MyRank{{{*/
+int    IntMatParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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;
+}
+/*}}}*/
+/*FUNCTION IntMatParam::UnitConversion{{{*/
+void  IntMatParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntMatParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntMatParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntMatParam.h	(revision 12878)
@@ -0,0 +1,80 @@
+/*! \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 "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");};
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");};
+		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int vec array");};
+		void  SetValue(int* intarray,int M,int N);
+		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _INTMATPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntParam.cpp	(revision 12878)
@@ -0,0 +1,89 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("IntParam:");
+	_printLine_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " << this->value);
+}
+/*}}}*/
+/*FUNCTION IntParam::Id{{{*/
+int    IntParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntParam::MyRank{{{*/
+int    IntParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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);
+}
+/*}}}*/
+/*FUNCTION IntParam::UnitConversion{{{*/
+void  IntParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntParam.h	(revision 12878)
@@ -0,0 +1,79 @@
+/*! \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 "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){*pinteger=value;}
+		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a bool");}
+		void  SetValue(int integer){this->value=integer;}
+		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an int array");}
+		void  SetValue(int* intarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an int array");}
+		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an IssmDouble");}
+		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntVecParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntVecParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntVecParam.cpp	(revision 12878)
@@ -0,0 +1,147 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("IntVecParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   vector size: " << this->M);
+
+}
+/*}}}*/
+/*FUNCTION IntVecParam::DeepEcho{{{*/
+void IntVecParam::DeepEcho(void){
+
+	int i;
+	
+	_printLine_("IntVecParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   vector size: " << this->M);
+	for(i=0;i<this->M;i++){
+		_printLine_(i << " " << this->values[i]);
+	}
+}
+/*}}}*/
+/*FUNCTION IntVecParam::Id{{{*/
+int    IntVecParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IntVecParam::MyRank{{{*/
+int    IntVecParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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;
+}
+/*}}}*/
+/*FUNCTION IntVecParam::UnitConversion{{{*/
+void  IntVecParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntVecParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntVecParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/IntVecParam.h	(revision 12878)
@@ -0,0 +1,79 @@
+/*! \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 "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param virtual functions definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM);
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array (maybe in serial?)");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M);
+		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");}
+		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+		
+		void GetParameterName(char**pname);
+		/*}}}*/
+};
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/MatrixParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/MatrixParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/MatrixParam.cpp	(revision 12878)
@@ -0,0 +1,117 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*MatrixParam constructors and destructor*/
+/*FUNCTION MatrixParam::MatrixParam(){{{*/
+MatrixParam::MatrixParam(){
+	return;
+}
+/*}}}*/
+/*FUNCTION MatrixParam::MatrixParam(int enum_type,Matrix* value){{{*/
+MatrixParam::MatrixParam(int in_enum_type,Matrix* in_value){
+
+	enum_type=in_enum_type;
+	value=NULL;
+
+	if(in_value){
+		value=in_value->Duplicate();
+	}
+}
+/*}}}*/
+/*FUNCTION MatrixParam::~MatrixParam(){{{*/
+MatrixParam::~MatrixParam(){
+	xdelete(&value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION MatrixParam::Echo {{{*/
+void MatrixParam::Echo(void){
+
+	_printLine_("MatrixParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+
+}
+/*}}}*/
+/*FUNCTION MatrixParam::DeepEcho{{{*/
+void MatrixParam::DeepEcho(void){
+
+	int i;
+	_printLine_("MatrixParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	this->value->Echo();
+}
+/*}}}*/
+/*FUNCTION MatrixParam::Id{{{*/
+int    MatrixParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION MatrixParam::MyRank{{{*/
+int    MatrixParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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** poutput){
+	Matrix* 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* matrix){
+	
+	/*avoid leak: */
+	xdelete(&value);
+	
+	/*copy: */
+	value=matrix->Duplicate();
+}
+/*}}}*/
+/*FUNCTION MatrixParam::UnitConversion{{{*/
+void  MatrixParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/MatrixParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/MatrixParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/MatrixParam.h	(revision 12878)
@@ -0,0 +1,79 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/shared.h"
+/*}}}*/
+
+class MatrixParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		Matrix* value;
+
+	public:
+		/*MatrixParam constructors, destructors: {{{*/
+		MatrixParam();
+		MatrixParam(int enum_type,Matrix* value);
+		~MatrixParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a vec");}
+		void  GetParameterValue(Matrix** poutput);
+		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat);
+		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _MATRIXPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/Param.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/Param.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/Param.h	(revision 12878)
@@ -0,0 +1,60 @@
+/*!\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 "../Object.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** pvec)=0;
+		virtual void  GetParameterValue(Matrix** pmat)=0;
+		virtual void  GetParameterValue(FILE** pfid)=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* vec)=0;
+		virtual void  SetValue(Matrix* mat)=0;
+		virtual void  SetValue(FILE* fid)=0;
+		virtual void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array)=0;
+		virtual void  UnitConversion(int direction_enum)=0;
+		virtual void  GetParameterName(char**pname)=0;
+};
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringArrayParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringArrayParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringArrayParam.cpp	(revision 12878)
@@ -0,0 +1,179 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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;
+
+	_printLine_("StringArrayParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	for(i=0;i<this->numstrings;i++){
+		string=this->value[i];
+		_printLine_("   " << i << ": " << string);
+	}
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::Id{{{*/
+int    StringArrayParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION StringArrayParam::MyRank{{{*/
+int    StringArrayParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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;
+	}
+}
+/*}}}*/
+/*FUNCTION StringArrayParam::UnitConversion{{{*/
+void  StringArrayParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringArrayParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringArrayParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringArrayParam.h	(revision 12878)
@@ -0,0 +1,80 @@
+/*! \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 "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM);
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Vec param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M);
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+		/*}}}*/
+};
+#endif  /* _STRINGARRAYPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringParam.cpp	(revision 12878)
@@ -0,0 +1,121 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+	_printLine_("StringParam:");
+	_printLine_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   value: " << this->value);
+}
+/*}}}*/
+/*FUNCTION StringParam::Id{{{*/
+int    StringParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION StringParam::MyRank{{{*/
+int    StringParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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);
+
+}
+/*}}}*/
+/*FUNCTION StringParam::UnitConversion{{{*/
+void  StringParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/StringParam.h	(revision 12878)
@@ -0,0 +1,79 @@
+/*! \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 "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring);
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error2_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string);
+		void  SetValue(char** stringarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector* vec){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _STRINGPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/TransientParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/TransientParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/TransientParam.cpp	(revision 12878)
@@ -0,0 +1,151 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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){
+
+	_printLine_("TransientParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   size: " << this->N);
+
+}
+/*}}}*/
+/*FUNCTION TransientParam::DeepEcho{{{*/
+void TransientParam::DeepEcho(void){
+
+	int i,j;
+	
+	_printLine_("TransientParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	_printLine_("   size: " << this->N);
+	for(i=0;i<this->N;i++){
+		_printLine_(   "time: " << this->timesteps[i] << " value: " << this->values[i]);
+	}
+}
+/*}}}*/
+/*FUNCTION TransientParam::Id{{{*/
+int    TransientParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION TransientParam::MyRank{{{*/
+int    TransientParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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){
+
+	double 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)_error2_("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);
+}
+/*}}}*/
+/*FUNCTION TransientParam::UnitConversion{{{*/
+void  TransientParam::UnitConversion(int direction_enum){
+	::UnitConversion(this->values,this->N,direction_enum,this->enum_type);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/TransientParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/TransientParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/TransientParam.h	(revision 12878)
@@ -0,0 +1,80 @@
+/*! \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 "../../../include/include.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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time);
+		void  GetParameterValue(char** pstring){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector** pvec){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(Vector* vec){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix* mat){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _TRANSIENTPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/VectorParam.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/VectorParam.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/VectorParam.cpp	(revision 12878)
@@ -0,0 +1,121 @@
+/*!\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 <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.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* 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(){
+	xdelete(&value);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION VectorParam::Echo {{{*/
+void VectorParam::Echo(void){
+
+	_printLine_("VectorParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+
+}
+/*}}}*/
+/*FUNCTION VectorParam::DeepEcho{{{*/
+void VectorParam::DeepEcho(void){
+
+	int i;
+	_printLine_("VectorParam:");
+	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	value->Echo();
+}
+/*}}}*/
+/*FUNCTION VectorParam::Id{{{*/
+int    VectorParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION VectorParam::MyRank{{{*/
+int    VectorParam::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*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** poutput){
+	Vector*  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* vector){
+
+	/*avoid leak: */
+	xdelete(&value);
+	
+	/*copy: */
+	value=vector->Duplicate();
+	vector->Copy(value);
+}
+/*}}}*/
+/*FUNCTION VectorParam::UnitConversion{{{*/
+void  VectorParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/VectorParam.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/VectorParam.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Params/VectorParam.h	(revision 12878)
@@ -0,0 +1,79 @@
+/*! \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 "../../../include/include.h"
+#include "../../../shared/shared.h"
+/*}}}*/
+
+class VectorParam: public Param{
+
+	private: 
+		/*just hold 3 values for 3 vertices: */
+		int enum_type;
+		Vector* value;
+
+	public:
+		/*VectorParam constructors, destructors: {{{*/
+		VectorParam();
+		VectorParam(int enum_type,Vector* value);
+		~VectorParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Matrix** pmat){_error2_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(Vector** poutput);
+		void  GetParameterValue(FILE** pfid){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a boolean");}
+		void  SetValue(int integer){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a scalar");}
+		void  SetValue(char* string){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(Vector* vec);
+		void  SetValue(Matrix* mat){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error2_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error2_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _VECTORPARAM_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Segment.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Segment.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Segment.cpp	(revision 12878)
@@ -0,0 +1,86 @@
+/*!\file Segment.c
+ * \brief: implementation of the Segment object
+ */
+
+/*Include files: {{{*/
+#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 "./objects.h"
+#include "../../Container/Container.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+/*}}}*/
+
+/*Segment constructors and destructors:*/
+/*FUNCTION Segment::Segment() default constructor {{{*/
+Segment::Segment(){
+	this->eid=UNDEF;
+	this->x1=UNDEF;
+	this->y1=UNDEF;
+	this->x2=UNDEF;
+	this->y2=UNDEF;
+}
+/*}}}*/
+/*FUNCTION Segment::Segment(int eid, IssmDouble x1,IssmDouble y1,IssmDouble x2, IssmDouble y2){{{*/
+Segment::Segment(int segment_eid, IssmDouble segment_x1,IssmDouble segment_y1,IssmDouble segment_x2, IssmDouble 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(){{{*/
+Segment::~Segment(){
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Segment::Echo{{{*/
+void Segment::Echo(void){
+
+	_printLine_("Segment:");
+	_printLine_("   eid: " << eid);
+	_printLine_("   node 1: " << this->x1 << "|" << this->y1);
+	_printLine_("   node 2: " << this->x2 << "|" << this->y2);
+
+}
+/*}}}*/
+/*FUNCTION Segment::DeepEcho{{{*/
+void Segment::DeepEcho(void){
+	this->Echo();
+}
+/*}}}*/
+/*FUNCTION Segment::Id{{{*/
+int    Segment::Id(void){ return eid; }
+/*}}}*/
+/*FUNCTION Segment::MyRank{{{*/
+int    Segment::MyRank(void){ 
+	extern int my_rank;
+
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION Segment::ObjectEnum{{{*/
+int Segment::ObjectEnum(void){
+
+	return SegmentEnum;
+
+}
+/*}}}*/
+/*FUNCTION Segment::copy {{{*/
+Object* Segment::copy() {
+	return new Segment(this->eid,this->x1,this->y1,this->x2,this->y2);
+
+}
+
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Segment.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Segment.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Segment.h	(revision 12878)
@@ -0,0 +1,37 @@
+/*!\file Segment.h
+ * \brief: header file for node object
+ */
+
+#ifndef _SEGMENT_H_
+#define _SEGMENT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Object.h"
+/*}}}*/
+
+class Segment: public Object{
+
+	public:
+		int eid;
+		IssmDouble x1;
+		IssmDouble y1;
+		IssmDouble x2;
+		IssmDouble y2;
+
+		/*Segment constructors, destructors {{{*/
+		Segment();
+		Segment(int eid,IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2);
+		~Segment();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+};
+
+#endif  /* _SEGMENT_H_ */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Vertex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Vertex.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Vertex.cpp	(revision 12878)
@@ -0,0 +1,218 @@
+/*!\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 "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../include/include.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->x=vertex_x;
+	this->y=vertex_y;
+	this->z=vertex_z;
+	this->sigma=vertex_sigma;
+	this->connectivity=vertex_connectivity;
+	this->dof=UNDEF;
+
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Vertex::Echo{{{*/
+void Vertex::Echo(void){
+
+	_printLine_("Vertex:");
+	_printLine_("   id: " << id);
+	_printLine_("   sid: " << sid);
+	_printLine_("   x: " << x);
+	_printLine_("   y: " << y);
+	_printLine_("   z: " << z);
+	_printLine_("   sigma: " << sigma);
+	_printLine_("   connectivity: " << connectivity);
+	_printLine_("   dof: " << dof);
+	_printLine_("   clone: " << clone);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Vertex::DeepEcho{{{*/
+void Vertex::DeepEcho(void){
+	this->Echo();
+}
+/*}}}*/
+/*FUNCTION Vertex::Id{{{*/
+int    Vertex::Id(void){ return id; }
+/*}}}*/
+/*FUNCTION Vertex::MyRank {{{*/
+int    Vertex::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION Vertex::ObjectEnum{{{*/
+int Vertex::ObjectEnum(void){
+
+	return VertexEnum;
+
+}
+/*}}}*/
+/*FUNCTION Vertex::copy {{{*/
+Object* Vertex::copy() {
+
+	return new Vertex(*this); 
+
+}
+/*}}}*/
+
+/* DofObject routines: */
+/*FUNCTION Vertex::DistributeDofs{{{*/
+void  Vertex::DistributeDofs(int* pdofcount){
+
+	int i;
+	extern int my_rank;
+	int dofcount;
+
+	dofcount=*pdofcount;
+	
+	if(this->clone){
+		/*This vertex is a clone! Don't distribute dofs, it will get them from another cpu!*/
+		return;
+	}
+
+	/*This vertex should distribute his dof, go ahead: */
+	this->dof=dofcount;
+	dofcount++;
+
+	/*Assign output pointers: */
+	*pdofcount=dofcount;
+
+}
+/*}}}*/
+/*FUNCTION Vertex::OffsetDofs{{{*/
+void  Vertex::OffsetDofs(int dofcount){
+	
+	int i;
+	extern int my_rank;
+	
+	if(this->clone){
+		/*This vertex is a clone, don't offset the dofs!: */
+		return;
+	}
+
+	/*This vertex should offset his dof, go ahead: */
+	this->dof+=dofcount;
+}
+/*}}}*/
+/*FUNCTION Vertex::ShowTrueDofs{{{*/
+void  Vertex::ShowTrueDofs(int* truedofs){
+
+	int j;
+	extern int my_rank;
+	
+	/*Are we a clone? : */
+	if(this->clone)return;
+
+	/*Ok, we are not a clone, just plug our dof into truedofs: */
+	truedofs[this->id-1]=this->dof;
+
+}
+/*}}}*/
+/*FUNCTION Vertex::UpdateCloneDofs{{{*/
+void  Vertex::UpdateCloneDofs(int* alltruedofs){
+
+	int j;
+	extern int my_rank;
+	
+	/*If we are not a clone, don't update, we already have dofs!: */
+	if(this->clone==0)return;
+
+	/*Ok, we are a clone node, but we did not create the dof for this vertex 
+	 * Therefore, our dof is garbage right now. Go pick it up in the alltruedofs: */
+	this->dof=alltruedofs[id-1];
+}
+/*}}}*/
+/*FUNCTION Vertex::SetClone {{{*/
+void  Vertex::SetClone(int* minranks){
+
+	extern int my_rank;
+
+	if (minranks[id-1]==my_rank){
+		this->clone=0;
+	}
+	else{
+		/*!there is a cpu with lower rank that has the same vertex, 
+		therefore, I am a clone*/
+		this->clone=1; 	
+	}
+
+}
+/*}}}*/
+
+/*Vertex management: */
+/*FUNCTION Vertex::Connectivity{{{*/
+int    Vertex::Connectivity(void){return connectivity;}
+/*}}}*/
+/*FUNCTION Vertex::Sid{{{*/
+int    Vertex::Sid(void){ return sid; }
+/*}}}*/
+/*FUNCTION Vertex::UpdateVertexPosition {{{*/
+void  Vertex::UpdatePosition(Vector* 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->dof]+sigma*thickness[this->dof];
+	velz = (newz-oldz)/dt;
+	this->z = newz;
+
+	/*put vz in vector*/
+	vz->SetValue(this->dof,velz,INS_VAL);
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/Vertex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/Vertex.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/Vertex.h	(revision 12878)
@@ -0,0 +1,65 @@
+/*! \file Vertex.h 
+ *  \brief: header file for vertex object
+ */
+
+#ifndef _VERTEX_H_
+#define _VERTEX_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../classes.h"
+class IoModel;
+class Vector;
+class Parameters;
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../toolkits/toolkits.h"
+#include "../../include/include.h"
+
+/*}}}*/
+
+
+class Vertex: public Object{
+
+	public: 
+
+		int    id;
+		int    sid;            //sid for "serial" id, ie the rank of this vertex in the vertices dataset, if the dataset was serial on 1 cpu.
+		IssmDouble x;
+		IssmDouble y;
+		IssmDouble z;
+		IssmDouble sigma;          //sigma coordinate: (z-bed)/thickness
+		int    connectivity;   //number of vertices connected to this vertex
+
+		/*dof management: */
+		int    clone;
+		int    dof; //dof to recover values in a vertex indexed vector
+
+		/*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   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*DofObject routines {{{*/
+		void  DistributeDofs(int* pdofcount);
+		void  OffsetDofs(int dofcount);
+		void  ShowTrueDofs(int* borderdofs);
+		void  UpdateCloneDofs(int* allborderdofs);
+		void  SetClone(int* minranks);
+		/*}}}*/
+		/*Vertex management: {{{*/
+		int   Sid(void); 
+		int   Connectivity(void); 
+		void  UpdatePosition(Vector* vz,Parameters* parameters,IssmDouble* thickness,IssmDouble* bed);
+		/*}}}*/
+};
+#endif  /* _VERTEX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/classes/objects/objects.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/classes/objects/objects.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/classes/objects/objects.h	(revision 12878)
@@ -0,0 +1,130 @@
+/* \file objects.h
+ * \brief: prototype header for all objects.
+ */
+
+#ifndef ALL_OBJECTS_H_
+#define ALL_OBJECTS_H_
+
+/*Abstract classes: */
+#include "./Object.h"
+
+/*Objects: */
+#include "./Contour.h"
+#include "./Vertex.h"
+#include "./Node.h"
+#include "./Segment.h"
+
+/*Constraints: */
+#include "./Constraints/Constraint.h"
+#include "./Constraints/SpcStatic.h"
+#include "./Constraints/SpcTransient.h"
+#include "./Constraints/SpcDynamic.h"
+
+/*Loads: */
+#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/Element.h"
+#include "./Elements/Penta.h"
+#include "./Elements/PentaHook.h"
+#include "./Elements/PentaRef.h"
+#include "./Elements/Tria.h"
+#include "./Elements/TriaHook.h"
+#include "./Elements/TriaRef.h"
+
+/*KML parsing objects: */
+#include "./KML/KML_Attribute.h"
+#include "./KML/KML_Comment.h"
+#include "./KML/KML_ColorStyle.h"
+#include "./KML/KML_Container.h"
+#include "./KML/KML_Document.h"
+#include "./KML/KML_Feature.h"
+#include "./KML/KML_File.h"
+#include "./KML/KML_Folder.h"
+#include "./KML/KML_Geometry.h"
+#include "./KML/KML_GroundOverlay.h"
+#include "./KML/KML_Icon.h"
+#include "./KML/KML_LatLonBox.h"
+#include "./KML/KML_LinearRing.h"
+#include "./KML/KML_LineString.h"
+#include "./KML/KML_LineStyle.h"
+#include "./KML/KML_MultiGeometry.h"
+#include "./KML/KML_Object.h"
+#include "./KML/KML_Overlay.h"
+#include "./KML/KML_Point.h"
+#include "./KML/KML_Placemark.h"
+#include "./KML/KML_Polygon.h"
+#include "./KML/KML_PolyStyle.h"
+#include "./KML/KML_Style.h"
+#include "./KML/KML_StyleSelector.h"
+#include "./KML/KML_SubStyle.h"
+#include "./KML/KML_Unknown.h"
+#include "./KML/KMLFileReadUtils.h"
+
+/*Option parsing objects: */
+#include "./Options/Option.h"
+#include "./Options/OptionDouble.h"
+#include "./Options/OptionLogical.h"
+#include "./Options/OptionChar.h"
+#include "./Options/OptionStruct.h"
+#include "./Options/OptionCell.h"
+#include "./Options/OptionUtilities.h"
+
+/*Inputs: */
+#include "./Inputs/Input.h"
+#include "./Inputs/BoolInput.h"
+#include "./Inputs/DoubleInput.h"
+#include "./Inputs/IntInput.h"
+#include "./Inputs/PentaP1Input.h"
+#include "./Inputs/TriaP1Input.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/ExternalResult.h"
+#include "./ExternalResults/BoolExternalResult.h"
+#include "./ExternalResults/DoubleExternalResult.h"
+#include "./ExternalResults/DoubleVecExternalResult.h"
+#include "./ExternalResults/DoubleMatExternalResult.h"
+#include "./ExternalResults/IntExternalResult.h"
+#include "./ExternalResults/PetscVecExternalResult.h"
+#include "./ExternalResults/StringExternalResult.h"
+
+/*Materials: */
+#include "./Materials/Material.h"
+#include "./Materials/Matice.h"
+#include "./Materials/Matpar.h"
+
+/*Params: */
+#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/Param.h"
+#include "./Params/MatrixParam.h"
+#include "./Params/VectorParam.h"
+#include "./Params/StringArrayParam.h"
+#include "./Params/StringParam.h"
+#include "./Params/TransientParam.h"
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/include/include.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/include/include.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/include/include.h	(revision 12878)
@@ -10,5 +10,3 @@
 #include "./types.h"
 
-
 #endif //ifndef _INCLUDE_H_
-
Index: /issm/branches/trunk-jpl-damage/src/c/include/macros.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/include/macros.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/include/macros.h	(revision 12878)
@@ -3,8 +3,11 @@
  */
 
-/*Header {{{1*/
+/*Header {{{*/
 #ifndef _MACROS_H_
 #define _MACROS_H_
 
+#include <iostream>
+#include <sstream>
+#include <iomanip>
 #include "./typedefs.h"
 
@@ -16,9 +19,9 @@
 /*}}}*/
 
-/* _printf_ {{{1*/
+/* _printf_ {{{*/
 /*Printing macro: only cpu number 0 */
-#define _printf_(flag,...) do { if(flag) PrintfFunction(__VA_ARGS__); }while (0)
+#define _printf_(flag,...) do{if(flag) PrintfFunction(__VA_ARGS__);}while(0)
 /*}}}*/
-/* _error_ {{{1*/
+/* _error_ {{{*/
 /*Error exception macro*/
 #ifdef _INTEL_WIN_
@@ -30,5 +33,43 @@
 #endif
 /*}}}*/
-/* _assert_ {{{1*/
+/* _error2_ {{{*/
+/*new Error exception macro*/
+#ifdef _INTEL_WIN_
+#define _error2_(StreamArgs)\
+   do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
+   aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
+   throw ErrorException(aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
+#else
+#define _error2_(StreamArgs)\
+	do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
+   aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
+   throw ErrorException(__FILE__,__func__,__LINE__,aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
+#endif
+/*}}}*/
+/* _printLine_ {{{*/
+/* macro to print a line, adds std::endl */
+#define _printLine_(StreamArgs)\
+   do{std::cout << StreamArgs << std::endl;}while(0)
+/*}}}*/
+/* _printString_ {{{*/
+/* macro to print some string */
+#define _printString_(StreamArgs)\
+   do{std::cout << StreamArgs;}while(0)
+/*}}}*/
+/* _pprintLine_ {{{*/
+/* macro to print a line, adds std::endl, only on cpu 0 */
+#define _pprintLine_(StreamArgs)\
+  do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
+	  aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
+	  PrintfFunction(aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
+/*}}}*/
+/* _pprintString_ {{{*/
+/* macro to print some string. Only on cpu0 */
+#define _pprintString_(StreamArgs)\
+  do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
+	  aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
+	  PrintfFunction2(aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
+/*}}}*/
+/* _assert_ {{{*/
 /*Assertion macro: do nothing if macro _ISSM_DEBUG_ undefined*/
 #ifdef _ISSM_DEBUG_ 
@@ -40,5 +81,5 @@
 #endif
 /*}}}*/
-/* ISSMBOOT/ISSMEND {{{1*/
+/* ISSMBOOT/ISSMEND {{{*/
 
 /*The following macros hide the error exception handling in a matlab module. Just put 
Index: /issm/branches/trunk-jpl-damage/src/c/include/typedefs.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/include/typedefs.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/include/typedefs.h	(revision 12878)
@@ -16,5 +16,4 @@
 #define NDOF3 3
 #define NDOF4 4
-
 
 #define DIM2 2
@@ -40,6 +39,3 @@
 #endif
 
-
-
-
 #endif //ifndef _ISSMTYPEDEFS_H_
Index: /issm/branches/trunk-jpl-damage/src/c/include/types.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/include/types.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/include/types.h	(revision 12878)
@@ -27,7 +27,18 @@
 #endif  
 
-typedef double IssmDouble;
+#ifdef _HAVE_ADOLC_
+#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
+
 typedef bool IssmBool;
 
-
 #endif //ifndef _TYPES_H_
Index: /issm/branches/trunk-jpl-damage/src/c/io/Disk/diskio.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/io/Disk/diskio.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/io/Disk/diskio.h	(revision 12878)
@@ -6,10 +6,7 @@
 #define _DISK_IO_H_
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 #include "../../include/include.h"
-
-class DataSet;
-class Parameters;
 
 FILE* pfopen(char* filename,const char* format);
Index: /issm/branches/trunk-jpl-damage/src/c/io/Disk/pfclose.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/io/Disk/pfclose.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/io/Disk/pfclose.cpp	(revision 12878)
@@ -18,4 +18,4 @@
 	extern int my_rank;
 	_assert_(fid);
-	if(fclose(fid)!=0)_error_("%s%s","could not close file ",filename);
+	if(fclose(fid)!=0)_error2_("could not close file " << filename);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/io/Disk/pfopen.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/io/Disk/pfopen.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/io/Disk/pfopen.cpp	(revision 12878)
@@ -20,5 +20,5 @@
 	/*Open handle to data on disk: */
 	fid=fopen(filename,format);
-	if(fid==NULL) _error_("%s%s%s","could not open file ",filename," for binary reading or writing"); 
+	if(fid==NULL) _error2_("could not open file " << filename << " for binary reading or writing"); 
 
 	return fid;
Index: /issm/branches/trunk-jpl-damage/src/c/io/PrintfFunction.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/io/PrintfFunction.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/io/PrintfFunction.cpp	(revision 12878)
@@ -25,13 +25,9 @@
 
 		/*allocate buffer for given string size*/
-		buffer=(char*)xmalloc(size*sizeof(char));
+		buffer=xNew<char>(size);
 
 		/* Try to print in the allocated space. */
 		va_start(args, format);
-#ifndef WIN32
 		n=vsnprintf(buffer,size,format,args);
-#else
-		n=vsnprintf(buffer,size,format,args);
-#endif
 		va_end(args);
 
@@ -45,12 +41,26 @@
 		 size*=2;  /* twice the old size */
 
-		xfree((void**)&buffer);
+		xDelete<char>(buffer);
 	}
 
 	/*Ok, if we are running in parallel, get node 0 to print*/
-	if(my_rank==0)printf(buffer);
+	if(my_rank==0)_printString_(buffer);
 
 	/*Clean up and return*/
-	xfree((void**)&buffer);
+	xDelete<char>(buffer);
 	return 1;
 }
+int PrintfFunction(const string & message){
+	extern int  my_rank;
+	if(my_rank==0){
+		printf("%s\n",message.c_str());
+	}
+	return 1;
+}
+int PrintfFunction2(const string & message){
+	extern int  my_rank;
+	if(my_rank==0){
+		printf("%s",message.c_str());
+	}
+	return 1;
+}
Index: /issm/branches/trunk-jpl-damage/src/c/io/io.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/io/io.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/io/io.h	(revision 12878)
@@ -6,15 +6,15 @@
 #define _ISSM_IO_H_
 
-#ifdef HAVE_CONFIG_H //config.h {{{1
+#ifdef HAVE_CONFIG_H
 #include <config.h>
 #else
 #error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif 
-//}}}
-
 #include "./Disk/diskio.h"
 
 /*printf: */
 int PrintfFunction(const char* format,...);
+int PrintfFunction(const string & message);
+int PrintfFunction2(const string & message);
 
 #endif	/* _IO_H_ */
Index: /issm/branches/trunk-jpl-damage/src/c/issm.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/issm.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/issm.h	(revision 12878)
@@ -4,5 +4,5 @@
 
 #ifndef _ISSM_H_
-#define  _ISSM_H_
+#define _ISSM_H_
 
 #ifdef HAVE_CONFIG_H
@@ -14,5 +14,5 @@
 #include "./include/include.h"
 #include "./shared/shared.h"
-#include "./objects/objects.h"
+#include "./classes/classes.h"
 #include "./Container/Container.h"
 #include "./EnumDefinitions/EnumDefinitions.h"
@@ -22,4 +22,3 @@
 #include "./modules/modules.h"
 
-
 #endif //ifndef _ISSM_H_
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/include/matlab_macros.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/include/matlab_macros.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/include/matlab_macros.h	(revision 12878)
@@ -3,5 +3,5 @@
  */
 
-/*Header {{{1*/
+/*Header {{{*/
 #ifndef _MATLAB_MACROS_H_
 #define _MATLAB_MACROS_H_
@@ -15,5 +15,5 @@
 
 #ifdef _HAVE_MATLAB_
-/* MODULEBOOT/MODULEEND {{{1*/
+/* MODULEBOOT/MODULEEND {{{*/
 
 /*The following macros hide the error exception handling in a matlab module. Just put 
@@ -36,9 +36,9 @@
 	}
 //}}}
-/* WRAPPER {{{1*/
+/* WRAPPER {{{*/
 #define WRAPPER(modulename,...) void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) 
 
 /*}}}*/
-/* CHECKARGUMENTS {{{1*/
+/* CHECKARGUMENTS {{{*/
 #define CHECKARGUMENTS(NLHS,NRHS,functionpointer) CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,functionpointer)
 /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/CheckNumMatlabArguments.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/CheckNumMatlabArguments.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/CheckNumMatlabArguments.cpp	(revision 12878)
@@ -22,9 +22,9 @@
 		/* special case: */
 		function();
-		_error_("usage: see above");
+		_error2_("usage: see above");
 	}
 	else if (nlhs!=NLHS || nrhs!=NRHS ) {
 		function(); 
-		_error_("usage error.");
+		_error2_("usage error.");
 	}
 	return 1;
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/FetchMatlabData.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/FetchMatlabData.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/FetchMatlabData.cpp	(revision 12878)
@@ -15,5 +15,5 @@
 
 /*Primitive data types*/
-/*FUNCTION FetchData(double** pmatrix,int* pM,int *pN,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(double** pmatrix,int* pM,int *pN,const mxArray* dataref){{{*/
 void FetchData(double** pmatrix,int* pM,int *pN,const mxArray* dataref){
 
@@ -27,5 +27,9 @@
 		outmatrix=NULL;
 	}
-	else if(mxIsClass(dataref,"double") || mxIsClass(dataref,"single")){
+	else if( mxIsClass(dataref,"double") || 
+				mxIsClass(dataref,"single") || 
+				mxIsClass(dataref,"int16") || 
+				mxIsClass(dataref,"int8") || 
+				mxIsClass(dataref,"uint8")){
 		/*Check dataref is not pointing to NaN: */
 		if ( mxIsNaN(*(mxGetPr(dataref))) && (mxGetM(dataref)==1) && (mxGetN(dataref)==1) ){
@@ -35,4 +39,7 @@
 		}
 		else{
+			if(!mxIsClass(dataref,"double") && !mxIsClass(dataref,"single")){
+				_printLine_("Warning: converting matlab data from '" << mxGetClassName(dataref) << "' to 'double'");
+			}
 			/*Convert matlab matrix to double* matrix: */
 			MatlabMatrixToDoubleMatrix(&outmatrix,&outmatrix_rows,&outmatrix_cols,dataref);
@@ -41,5 +48,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 			
@@ -51,5 +58,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(double** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(double** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){{{*/
 void FetchData(double** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){
 
@@ -82,5 +89,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 			
@@ -90,9 +97,9 @@
 	if (pndims)*pndims=outmatrix_ndims;
 	if (psize )*psize =outmatrix_size;
-	else xfree((void**)&outmatrix_size);
-
-}
-/*}}}*/
-/*FUNCTION FetchData(int** pmatrix,int* pM,int *pN,const mxArray* dataref){{{1*/
+	else xDelete<int>(outmatrix_size);
+
+}
+/*}}}*/
+/*FUNCTION FetchData(int** pmatrix,int* pM,int *pN,const mxArray* dataref){{{*/
 void FetchData(int** pmatrix,int* pM,int *pN,const mxArray* dataref){
 
@@ -121,5 +128,5 @@
 
 			/*Convert double matrix into integer matrix: */
-			outmatrix=(int*)xmalloc(outmatrix_rows*outmatrix_cols*sizeof(int));
+			outmatrix=xNew<int>(outmatrix_rows*outmatrix_cols);
 			for(i=0;i<outmatrix_rows*outmatrix_cols;i++)outmatrix[i]=(int)doublematrix[i];
 		}
@@ -127,5 +134,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -136,5 +143,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(bool** pmatrix,int* pM,int *pN,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(bool** pmatrix,int* pM,int *pN,const mxArray* dataref){{{*/
 void FetchData(bool** pmatrix,int* pM,int *pN,const mxArray* dataref){
 
@@ -163,5 +170,5 @@
 
 			/*Convert double matrix into integer matrix: */
-			outmatrix=(bool*)xmalloc(outmatrix_rows*outmatrix_cols*sizeof(bool));
+			outmatrix=xNew<bool>(outmatrix_rows*outmatrix_cols);
 			for(i=0;i<outmatrix_rows;i++)outmatrix[i]=(bool)doublematrix[i];
 		}
@@ -169,5 +176,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -178,5 +185,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(bool** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(bool** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){{{*/
 void FetchData(bool** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){
 
@@ -224,12 +231,12 @@
 
 			/*Convert double matrix into bool matrix: */
-			outmatrix=(bool*)xmalloc(outmatrix_numel*sizeof(bool));
+			outmatrix=xNew<bool>(outmatrix_numel);
 			for(i=0;i<outmatrix_numel;i++)outmatrix[i]=(bool)doublematrix[i];
-			xfree((void**)&doublematrix);
-		}
-	}
-	else{
-		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+			xDelete<double>(doublematrix);
+		}
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 			
@@ -239,9 +246,9 @@
 	if (pndims)*pndims=outmatrix_ndims;
 	if (psize )*psize =outmatrix_size;
-	else xfree((void**)&outmatrix_size);
-
-}
-/*}}}*/
-/*FUNCTION FetchData(double** pvector,int* pM,const mxArray* dataref){{{1*/
+	else xDelete<int>(outmatrix_size);
+
+}
+/*}}}*/
+/*FUNCTION FetchData(double** pvector,int* pM,const mxArray* dataref){{{*/
 void FetchData(double** pvector,int* pM,const mxArray* dataref){
 
@@ -262,5 +269,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -270,5 +277,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(int** pvector,int* pM,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(int** pvector,int* pM,const mxArray* dataref){{{*/
 void FetchData(int** pvector,int* pM,const mxArray* dataref){
 
@@ -289,10 +296,10 @@
 
 		/*Convert double vector into integer vector: */
-		outvector=(int*)xmalloc(outvector_rows*sizeof(int));
+		outvector=xNew<int>(outvector_rows);
 		for(i=0;i<outvector_rows;i++)outvector[i]=(int)doublevector[i];
 	}
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -302,5 +309,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(bool** pvector,int* pM,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(bool** pvector,int* pM,const mxArray* dataref){{{*/
 void FetchData(bool** pvector,int* pM,const mxArray* dataref){
 
@@ -321,10 +328,10 @@
 
 		/*Convert double vector into integer vector: */
-		outvector=(bool*)xmalloc(outvector_rows*sizeof(bool));
+		outvector=xNew<bool>(outvector_rows);
 		for(i=0;i<outvector_rows;i++)outvector[i]=(bool)doublevector[i];
 	}
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -334,5 +341,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(float** pvector,int* pM,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(float** pvector,int* pM,const mxArray* dataref){{{*/
 void FetchData(float** pvector,int* pM,const mxArray* dataref){
 
@@ -353,10 +360,10 @@
 
 		/*Convert double vector into float vector: */
-		outvector=(float*)xmalloc(outvector_rows*sizeof(float));
+		outvector=xNew<float>(outvector_rows);
 		for(i=0;i<outvector_rows;i++)outvector[i]=(float)doublevector[i];
 	}
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -366,5 +373,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(char** pstring,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(char** pstring,const mxArray* dataref){{{*/
 void FetchData(char** pstring,const mxArray* dataref){
 
@@ -374,5 +381,5 @@
 	/*Ok, the string should be coming directly from the matlab workspace: */
 	if (!mxIsClass(dataref,"char")){
-		_error_("input data_type is not a string!");
+		_error2_("input data_type is not a string!");
 	}
 	else{
@@ -381,5 +388,5 @@
 		
 		stringlen = mxGetM(dataref)*mxGetN(dataref)+1;
-		outstring = (char*)xmalloc(sizeof(mxChar)*stringlen);
+		outstring =xNew<char>(stringlen);
 		mxGetString(dataref,outstring,stringlen);
 	}
@@ -387,6 +394,6 @@
 	/*Assign output pointers:*/
 	*pstring=outstring;
-}
-/*FUNCTION FetchData(char** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){{{1*/
+}/*}}}*/
+/*FUNCTION FetchData(char** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){{{*/
 void FetchData(char** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){
 
@@ -409,5 +416,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 			
@@ -417,9 +424,9 @@
 	if (pndims)*pndims=outmatrix_ndims;
 	if (psize )*psize =outmatrix_size;
-	else xfree((void**)&outmatrix_size);
-
-}
-/*}}}*/
-/*FUNCTION FetchData(double* pscalar,const mxArray* dataref){{{1*/
+	else xDelete<int>(outmatrix_size);
+
+}
+/*}}}*/
+/*FUNCTION FetchData(double* pscalar,const mxArray* dataref){{{*/
 void FetchData(double* pscalar,const mxArray* dataref){
 
@@ -427,5 +434,5 @@
 
 	if (!mxIsClass(dataref,"double")){
-		_error_("input data_type is not a double!");
+		_error2_("input data_type is not a double!");
 	}
 	else{
@@ -438,5 +445,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(int* pinteger,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(int* pinteger,const mxArray* dataref){{{*/
 void FetchData(int* pinteger,const mxArray* dataref){
 
@@ -444,5 +451,5 @@
 
 	if (!mxIsClass(dataref,"double")){
-		_error_("input data_type is not a scalar!");
+		_error2_("input data_type is not a scalar!");
 	}
 	else{
@@ -455,5 +462,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(bool* pboolean,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(bool* pboolean,const mxArray* dataref){{{*/
 void FetchData(bool* pboolean,const mxArray* dataref){
 
@@ -461,10 +468,10 @@
 
 	if (mxIsClass(dataref,"logical")){
-		if(mxGetM(dataref)!=1) _error_("input data is not of size 1x1");
-		if(mxGetN(dataref)!=1) _error_("input data is not of size 1x1");
+		if(mxGetM(dataref)!=1) _error2_("input data is not of size 1x1");
+		if(mxGetN(dataref)!=1) _error2_("input data is not of size 1x1");
 		mxbool_ptr=mxGetLogicals(dataref);
 	}
 	else{
-		_error_("input data_type is not a bool!");
+		_error2_("input data_type is not a bool!");
 	}
 
@@ -474,5 +481,5 @@
 
 /*ISSM objects*/
-/*FUNCTION FetchData(Matrix** pmatrix,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(Matrix** pmatrix,const mxArray* dataref){{{*/
 void FetchData(Matrix** pmatrix,const mxArray* dataref){
 
@@ -488,5 +495,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -495,5 +502,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(Vector** pvector,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(Vector** pvector,const mxArray* dataref){{{*/
 void FetchData(Vector** pvector,const mxArray* dataref){
 
@@ -512,5 +519,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class %s not supported yet",mxGetClassName(dataref));
+		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -519,5 +526,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(BamgGeom** pbamggeom,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(BamgGeom** pbamggeom,const mxArray* dataref){{{*/
 void FetchData(BamgGeom** pbamggeom,const mxArray* dataref){
 
@@ -538,5 +545,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(BamgMesh** pbamgmesh,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(BamgMesh** pbamgmesh,const mxArray* dataref){{{*/
 void FetchData(BamgMesh** pbamgmesh,const mxArray* dataref){
 
@@ -558,5 +565,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(BamgOpts** pbamgopts,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(BamgOpts** pbamgopts,const mxArray* dataref){{{*/
 void FetchData(BamgOpts** pbamgopts,const mxArray* dataref){
 
@@ -602,5 +609,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(Options** poptions,const mxArray* dataref){{{1*/
+/*FUNCTION FetchData(Options** poptions,const mxArray* dataref){{{*/
 void FetchData(Options** poptions,int istart, int nrhs,const mxArray** pdataref){
 
@@ -613,8 +620,8 @@
 	/*Fetch all options*/
 	for (int i=istart; i<nrhs; i=i+2){
-		if (!mxIsClass(pdataref[i],"char")) _error_("Argument %d must be name of option",i+1);
+		if (!mxIsClass(pdataref[i],"char")) _error2_("Argument " << i+1 << " must be name of option");
 
 		FetchData(&name,pdataref[i]);
-		if(i+1 == nrhs) _error_("Argument %d must exist and be value of option \"%s\".",i+2,name);
+		if(i+1 == nrhs) _error2_("Argument " << i+2 << " must exist and be value of option \"" << name << "\".");
 
 		option=(Option*)OptionParse(name,&pdataref[i+1]);
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToDoubleMatrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToDoubleMatrix.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToDoubleMatrix.cpp	(revision 12878)
@@ -2,5 +2,4 @@
  * \brief: convert a sparse or dense matlab matrix to a double* pointer
  */
-
 
 #ifdef HAVE_CONFIG_H
@@ -10,15 +9,11 @@
 #endif
 
-
 /*Matlab includes: */
 #include "mex.h"
-
 #include "../../shared/shared.h"
 
 int MatlabMatrixToDoubleMatrix(double** pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){
 
-	int     i,j,count,rows,cols;
-	double *pmxdoublematrix = NULL;
-	float  *pmxsinglematrix = NULL;
+	int        i,j,count,rows,cols;
 
 	/*output: */
@@ -33,10 +28,10 @@
 
 		/*Dealing with sparse matrix: recover size first: */
-		pmxdoublematrix=(double*)mxGetPr(mxmatrix);
+		double* pmxmatrix=(double*)mxGetPr(mxmatrix);
 		rows=mxGetM(mxmatrix);
 		cols=mxGetN(mxmatrix);
 		
 		if(rows*cols){
-			matrix=(double*)xcalloc(rows*cols,sizeof(double));
+			matrix=xNewZeroInit<double>(rows*cols);
 
 			/*Now, get ir,jc and pr: */
@@ -48,5 +43,5 @@
 			for(i=0;i<cols;i++){
 				for(j=0;j<(jc[i+1]-jc[i]);j++){
-					matrix[rows*ir[count]+i]=pmxdoublematrix[count];
+					matrix[rows*ir[count]+i]=pmxmatrix[count];
 					count++;
 				}
@@ -57,5 +52,5 @@
 	else if(mxIsClass(mxmatrix,"double")){
 		/*Dealing with dense matrix: recover pointer and size: */
-		pmxdoublematrix=(double*)mxGetPr(mxmatrix);
+		double* pmxmatrix=(double*)mxGetPr(mxmatrix);
 		rows=mxGetM(mxmatrix);
 		cols=mxGetN(mxmatrix);
@@ -63,9 +58,9 @@
 		/*Create serial matrix: */
 		if(rows*cols){
-			matrix=(double*)xcalloc(rows*cols,sizeof(double));
+			matrix=xNewZeroInit<double>(rows*cols);
 
 			for(i=0;i<rows;i++){
 				for(j=0;j<cols;j++){
-					matrix[cols*i+j]=(double)pmxdoublematrix[rows*j+i];
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
 				}
 			}
@@ -74,5 +69,5 @@
 	else if(mxIsClass(mxmatrix,"single")){
 		/*Dealing with dense matrix: recover pointer and size: */
-		pmxsinglematrix=(float*)mxGetPr(mxmatrix);
+		float *pmxmatrix=(float*)mxGetPr(mxmatrix);
 		rows=mxGetM(mxmatrix);
 		cols=mxGetN(mxmatrix);
@@ -80,9 +75,43 @@
 		/*Create serial matrix: */
 		if(rows*cols){
-			matrix=(double*)xcalloc(rows*cols,sizeof(double));
+			matrix=xNewZeroInit<double>(rows*cols);
 
 			for(i=0;i<rows;i++){
 				for(j=0;j<cols;j++){
-					matrix[cols*i+j]=(double)pmxsinglematrix[rows*j+i];
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else if(mxIsClass(mxmatrix,"int16")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		short int *pmxmatrix=(short*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else if(mxIsClass(mxmatrix,"uint8")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		char *pmxmatrix=(char*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
 				}
 			}
@@ -90,5 +119,5 @@
 	}
 	else{
-		_error_("Matlab matrix type Not implemented yet");
+		_error2_("Matlab matrix type Not implemented yet");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToMatrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToMatrix.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToMatrix.cpp	(revision 12878)
@@ -3,5 +3,5 @@
 
 /*Headers:*/
-/*{{{1*/
+/*{{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -14,5 +14,5 @@
 #include <string.h>
 #include "./matlabio.h"
-#include "../../objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../shared/shared.h"
 #include "../../Container/Container.h"
@@ -31,7 +31,7 @@
 
 	#ifdef _HAVE_PETSC_
-	MatlabMatrixToPetscMatrix(&matrix->matrix,NULL,NULL,mxmatrix);
+	matrix->pmatrix=MatlabMatrixToPetscMat(mxmatrix);
 	#else
-	matrix->matrix=MatlabMatrixToSeqMat(mxmatrix);
+	matrix->smatrix=MatlabMatrixToSeqMat(mxmatrix);
 	#endif
 	
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToPetscMat.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToPetscMat.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToPetscMat.cpp	(revision 12878)
@@ -0,0 +1,124 @@
+/* \file MatlabMatrixToPetscMatrix.cpp
+ * \brief: convert a sparse or dense matlab matrix to a serial Petsc matrix:
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "../../shared/shared.h"
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscvec.h"
+#include "petscksp.h"
+
+/*Matlab includes: */
+#include "mex.h"
+#include "matlabio.h"
+
+PetscMat* MatlabMatrixToPetscMat(const mxArray* mxmatrix){
+
+	int dummy;
+	PetscMat* matrix=new PetscMat();
+
+	MatlabMatrixToPetscMat(&matrix->matrix, &dummy, &dummy, mxmatrix);
+
+	return matrix;
+}
+int MatlabMatrixToPetscMat(Mat* pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){
+
+	int rows, cols;
+	double *mxmatrix_ptr = NULL;
+	double *tmatrix      = NULL;
+	int ierr;
+	int i,j;
+
+	/*output: */
+	Mat matrix = NULL;
+
+	/*matlab indices: */
+	mwIndex *ir = NULL;
+	mwIndex *jc = NULL;
+	double  *pr = NULL;
+	int     count;
+	int     nnz;
+	int     nz;
+
+	/*petsc indices: */
+	int *idxm = NULL;
+	int *idxn = NULL;
+	
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+		nnz=mxGetNzmax(mxmatrix);
+		if(rows){
+			nz=(int)((double)nnz/(double)rows);
+		}
+		else{
+			nz=0;
+		}
+
+		ierr=MatCreateSeqAIJ(PETSC_COMM_SELF,rows,cols,nz,PETSC_NULL,&matrix);CHKERRQ(ierr);
+
+		/*Now, get ir,jc and pr: */
+		pr=mxGetPr(mxmatrix);
+		ir=mxGetIr(mxmatrix);
+		jc=mxGetJc(mxmatrix);
+
+		/*Now, start inserting data into sparse matrix: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				MatSetValue(matrix,ir[count],i,pr[count],INSERT_VALUES);
+				count++;
+			}
+		}
+	}
+	else{
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*transpose, as Petsc now does not allows MAT_COLUMN_ORIENTED matrices in MatSetValues: */
+		tmatrix=xNew<double>(rows*cols);
+		for(i=0;i<cols;i++){
+			for(j=0;j<rows;j++){
+				*(tmatrix+rows*i+j)=*(mxmatrix_ptr+cols*j+i);
+			}
+		}
+
+		/*Create serial matrix: */
+		ierr=MatCreateSeqDense(PETSC_COMM_SELF,rows,cols,NULL,&matrix);CHKERRQ(ierr);
+
+		/*Insert mxmatrix_ptr values into petsc matrix: */
+		idxm=xNew<int>(rows);
+		idxn=xNew<int>(cols);
+
+		for(i=0;i<rows;i++)idxm[i]=i;
+		for(i=0;i<cols;i++)idxn[i]=i;
+
+		ierr=MatSetValues(matrix,rows,idxm,cols,idxn,tmatrix,INSERT_VALUES); CHKERRQ(ierr);
+
+		xDelete<double>(tmatrix);
+	}
+
+	/*Assemble matrix: */
+	MatAssemblyBegin(matrix,MAT_FINAL_ASSEMBLY); 
+	MatAssemblyEnd(matrix,MAT_FINAL_ASSEMBLY);
+
+	/*Assign output pointer: */
+	*pmatrix=matrix;
+	if(pmatrix_rows) *pmatrix_rows=rows;
+	if(pmatrix_cols) *pmatrix_cols=cols;
+
+	return 1;
+}
Index: sm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToPetscMatrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToPetscMatrix.cpp	(revision 12877)
+++ 	(revision )
@@ -1,120 +1,0 @@
-/* \file MatlabMatrixToPetscMatrix.cpp
- * \brief: convert a sparse or dense matlab matrix to a serial Petsc matrix:
- */
-
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-
-/*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
-
-/*Matlab includes: */
-#include "mex.h"
-
-#include "../../shared/shared.h"
-
-int MatlabMatrixToPetscMatrix(Mat* pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){
-
-	int rows, cols;
-	double* mxmatrix_ptr=NULL;
-	double* tmatrix=NULL;
-	int ierr;
-	int i,j;
-
-	/*output: */
-	Mat matrix=NULL;
-
-	/*matlab indices: */
-	mwIndex*    ir=NULL;
-	mwIndex*    jc=NULL;
-	double* pr=NULL;
-	int     count;
-	int     nnz;
-	int     nz;
-
-	/*petsc indices: */
-	int* idxm=NULL;
-	int* idxn=NULL;
-	
-	/*Ok, first check if we are dealing with a sparse or full matrix: */
-	if (mxIsSparse(mxmatrix)){
-
-		/*Dealing with sparse matrix: recover size first: */
-		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-		nnz=mxGetNzmax(mxmatrix);
-		if(rows){
-			nz=(int)((double)nnz/(double)rows);
-		}
-		else{
-			nz=0;
-		}
-
-		ierr=MatCreateSeqAIJ(PETSC_COMM_SELF,rows,cols,nz,PETSC_NULL,&matrix);CHKERRQ(ierr);
-
-		/*Now, get ir,jc and pr: */
-		pr=mxGetPr(mxmatrix);
-		ir=mxGetIr(mxmatrix);
-		jc=mxGetJc(mxmatrix);
-
-		/*Now, start inserting data into sparse matrix: */
-		count=0;
-		for(i=0;i<cols;i++){
-			for(j=0;j<(jc[i+1]-jc[i]);j++){
-				MatSetValue(matrix,ir[count],i,pr[count],INSERT_VALUES);
-				count++;
-			}
-		}
-
-	}
-	else{
-
-		/*Dealing with dense matrix: recover pointer and size: */
-		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-
-		/*transpose, as Petsc now does not allows MAT_COLUMN_ORIENTED matrices in MatSetValues: */
-		tmatrix=(double*)xmalloc(rows*cols*sizeof(double));
-		for(i=0;i<cols;i++){
-			for(j=0;j<rows;j++){
-				*(tmatrix+rows*i+j)=*(mxmatrix_ptr+cols*j+i);
-			}
-		}
-
-		/*Create serial matrix: */
-		ierr=MatCreateSeqDense(PETSC_COMM_SELF,rows,cols,NULL,&matrix);CHKERRQ(ierr);
-
-		/*Insert mxmatrix_ptr values into petsc matrix: */
-		idxm=(int*)xmalloc(rows*sizeof(int));
-		idxn=(int*)xmalloc(cols*sizeof(int));
-
-		for(i=0;i<rows;i++)idxm[i]=i;
-		for(i=0;i<cols;i++)idxn[i]=i;
-
-		ierr=MatSetValues(matrix,rows,idxm,cols,idxn,tmatrix,INSERT_VALUES); CHKERRQ(ierr);
-
-		xfree((void**)&tmatrix);
-
-	}
-
-	/*Assemble matrix: */
-	MatAssemblyBegin(matrix,MAT_FINAL_ASSEMBLY); 
-	MatAssemblyEnd(matrix,MAT_FINAL_ASSEMBLY);
-
-
-	/*Assign output pointer: */
-	*pmatrix=matrix;
-	if(pmatrix_rows) *pmatrix_rows=rows;
-	if(pmatrix_cols) *pmatrix_cols=cols;
-
-	return 1;
-}
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToSeqMat.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToSeqMat.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabMatrixToSeqMat.cpp	(revision 12878)
@@ -3,5 +3,5 @@
 
 /*Headers:*/
-/*{{{1*/
+/*{{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabNArrayToNArray.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabNArrayToNArray.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabNArrayToNArray.cpp	(revision 12878)
@@ -15,5 +15,5 @@
 #include <mex.h>
 
-/*FUNCTION MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{1*/
+/*FUNCTION MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
 int MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
 
@@ -39,6 +39,6 @@
 	ndims=mxGetNumberOfDimensions(mxmatrix);
 	ipt  =mxGetDimensions(mxmatrix);
-	size =(int *) xcalloc(ndims,sizeof(int));
-	for (i=0; i<ndims; i++) size[i]=(int)ipt[i];
+	size =xNew<int>(ndims);
+	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
 
 	/*Ok, first check if we are dealing with a sparse or full matrix: */
@@ -51,5 +51,5 @@
 		nz=(int)((double)nnz/(double)rows);
 
-		matrix=(double*)xcalloc(rows*cols,sizeof(double));
+		matrix=xNewZeroInit<double>(rows*cols);
 
 		/*Now, get ir,jc and pr: */
@@ -74,7 +74,7 @@
 		
 		/*Create serial matrix: */
-		matrix=(double*)xcalloc(numel,sizeof(double));
-
-		dims=(int *) xcalloc(ndims,sizeof(int));
+		matrix=xNewZeroInit<double>(numel);
+
+		dims=xNew<int>(ndims);
 		for(i=0;i<numel;i++){
 			ColumnWiseDimsFromIndex(dims,i,size,ndims);
@@ -82,5 +82,5 @@
 			*(matrix+j)=*(mxmatrix_ptr+i);
 		}
-		xfree((void**)&dims);
+		xDelete<int>(dims);
 		
 	}
@@ -95,5 +95,5 @@
 }
 /*}}}*/
-/*FUNCTION MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{1*/
+/*FUNCTION MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
 int MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
 
@@ -119,6 +119,6 @@
 	ndims=mxGetNumberOfDimensions(mxmatrix);
 	ipt  =mxGetDimensions(mxmatrix);
-	size =(int *) xcalloc(ndims,sizeof(int));
-	for (i=0; i<ndims; i++) size[i]=(int)ipt[i];
+	size =xNew<int>(ndims);
+	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
 
 	/*Ok, first check if we are dealing with a sparse or full matrix: */
@@ -131,5 +131,5 @@
 		nz=(int)((double)nnz/(double)rows);
 
-		matrix=(bool*)xcalloc(rows*cols,sizeof(bool));
+		matrix=xNewZeroInit<bool>(rows*cols);
 
 		/*Now, get ir,jc and pm: */
@@ -154,7 +154,6 @@
 		
 		/*Create serial matrix: */
-		matrix=(bool*)xcalloc(numel,sizeof(bool));
-
-		dims=(int *) xcalloc(ndims,sizeof(int));
+		matrix=xNew<bool>(numel);
+		dims=xNew<int>(ndims);
 		for(i=0;i<numel;i++){
 			ColumnWiseDimsFromIndex(dims,i,size,ndims);
@@ -162,6 +161,5 @@
 			*(matrix+j)=(bool)*(mxmatrix_ptr+i);
 		}
-		xfree((void**)&dims);
-		
+		xDelete<int>(dims);
 	}
 
@@ -175,12 +173,12 @@
 }
 /*}}}*/
-/*FUNCTION MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{1*/
+/*FUNCTION MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
 int MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
 
-	int  i,j,rows,cols;
-	int  numel,ndims;
-	int *size,*dims;
-	mxChar* mxmatrix_ptr=NULL;
-	const mwSize* ipt=NULL;
+	int           i,j,rows,cols;
+	int           numel,ndims;
+	int          *size , *dims;
+	mxChar       *mxmatrix_ptr = NULL;
+	const mwSize *ipt          = NULL;
 
 	/*output: */
@@ -188,10 +186,10 @@
 
 	/*matlab indices: */
-	mwIndex*    ir=NULL;
-	mwIndex*    jc=NULL;
-	char*   pm=NULL;
-	int     count;
-	int     nnz;
-	int     nz;
+	mwIndex *ir    = NULL;
+	mwIndex *jc    = NULL;
+	char    *pm    = NULL;
+	int      count;
+	int      nnz;
+	int      nz;
 
 	/*get Matlab matrix information: */
@@ -199,6 +197,6 @@
 	ndims=mxGetNumberOfDimensions(mxmatrix);
 	ipt  =mxGetDimensions(mxmatrix);
-	size =(int *) xcalloc(ndims,sizeof(int));
-	for (i=0; i<ndims; i++) size[i]=(int)ipt[i];
+	size =xNew<int>(ndims);
+	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
 
 	/*Ok, first check if we are dealing with a sparse or full matrix: */
@@ -211,5 +209,5 @@
 		nz=(int)((double)nnz/(double)rows);
 
-		matrix=(char*)xcalloc(rows*cols,sizeof(double));
+		matrix=xNew<char>(rows*cols);
 
 		/*Now, get ir,jc and pm: */
@@ -234,5 +232,6 @@
 		
 		/*Create serial matrix: */
-		matrix=(char*)xcalloc(numel+1,sizeof(mxChar));
+		matrix=xNew<char>(numel+1);
+		matrix[numel]='\0';
 
 		/*looping code adapted from Matlab example explore.c: */
@@ -259,5 +258,4 @@
 			}
 		}
-
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToDoubleVector.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToDoubleVector.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToDoubleVector.cpp	(revision 12878)
@@ -46,10 +46,10 @@
 		
 		/*Check that input is actualy a vector*/
-		if (cols!=1) _error_("input vector of size %ix%i should have only one column",rows,cols);
+		if (cols!=1) _error2_("input vector of size " << rows << "x" << cols << " should have only one column");
 
 		nz=(int)((double)nnz/(double)rows);
 
 		if(rows){
-			vector=(double*)xcalloc(rows,sizeof(double));
+			vector=xNewZeroInit<double>(rows);
 
 			/*Now, get ir,jc and pr: */
@@ -77,9 +77,9 @@
 
 		/*Check that input is actualy a vector*/
-		if (cols!=1) _error_("input vector of size %ix%i should have only one column",rows,cols);
+		if (cols!=1) _error2_("input vector of size " << rows << "x" << cols << " should have only one column");
 
 		/*allocate and memcpy*/
 		if(rows){
-			vector=(double*)xmalloc(rows*sizeof(double));
+			vector=xNew<double>(rows);
 			memcpy(vector,mxvector_ptr,rows*sizeof(double));
 		}
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToPetscVec.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToPetscVec.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToPetscVec.cpp	(revision 12878)
@@ -0,0 +1,109 @@
+/* \file MatlabVectorToPetscVector.cpp
+ * \brief: convert a sparse or dense matlab vector to a serial Petsc vector:
+ */
+
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*Petsc includes: */
+#include "petscmat.h"
+#include "petscvec.h"
+#include "petscksp.h"
+
+/*Matlab includes: */
+#include "mex.h"
+
+#include "../../shared/shared.h"
+#include "matlabio.h"
+
+PetscVec* MatlabVectorToPetscVec(const mxArray* mxvector){
+
+	int dummy;
+	PetscVec* vector=new PetscVec();
+	
+	MatlabVectorToPetscVec(&vector->vector,&dummy, mxvector);
+
+	return vector;
+}
+
+int MatlabVectorToPetscVec(Vec* pvector,int* pvector_rows,const mxArray* mxvector){
+
+	int rows, cols;
+	double* mxvector_ptr=NULL;
+	int ierr;
+	int i,j;
+
+	/*output: */
+	Vec vector=NULL;
+
+	/*matlab indices: */
+	mwIndex*    ir=NULL;
+	mwIndex*    jc=NULL;
+	double* pr=NULL;
+	int     count;
+	int     nnz;
+	int     nz;
+
+	/*petsc indices: */
+	int* idxm=NULL;
+	
+	/*Ok, first check if we are dealing with a sparse or full vector: */
+	if (mxIsSparse(mxvector)){
+
+		/*Dealing with sparse vector: recover size first: */
+		mxvector_ptr=(double*)mxGetPr(mxvector);
+		rows=mxGetM(mxvector);
+		cols=mxGetN(mxvector);
+		nnz=mxGetNzmax(mxvector);
+		nz=(int)((double)nnz/(double)rows);
+
+		ierr=VecCreateSeq(PETSC_COMM_SELF,rows,&vector);CHKERRQ(ierr);
+
+		/*Now, get ir,jc and pr: */
+		pr=mxGetPr(mxvector);
+		ir=mxGetIr(mxvector);
+		jc=mxGetJc(mxvector);
+
+		/*Now, start inserting data into sparse vector: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				VecSetValue(vector,ir[count],pr[count],INSERT_VALUES);
+				count++;
+			}
+		}
+
+	}
+	else{
+
+		/*Dealing with dense vector: recover pointer and size: */
+		mxvector_ptr=(double*)mxGetPr(mxvector);
+		rows=mxGetM(mxvector);
+		cols=mxGetN(mxvector);
+
+		/*Create serial vector: */
+		ierr=VecCreateSeq(PETSC_COMM_SELF,rows,&vector);CHKERRQ(ierr);
+
+		/*Insert mxvector_ptr values into petsc vector: */
+		idxm=xNew<int>(rows);
+
+		for(i=0;i<rows;i++)idxm[i]=i;
+
+		ierr=VecSetValues(vector,rows,idxm,mxvector_ptr,INSERT_VALUES);CHKERRQ(ierr);
+
+	}
+
+	/*Assemble vector: */
+	VecAssemblyBegin(vector);
+	VecAssemblyEnd(vector);
+
+	/*Assign output pointer: */
+	*pvector=vector;
+	*pvector_rows=rows;
+
+	return 1;
+}
Index: sm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToPetscVector.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToPetscVector.cpp	(revision 12877)
+++ 	(revision )
@@ -1,98 +1,0 @@
-/* \file MatlabVectorToPetscVector.cpp
- * \brief: convert a sparse or dense matlab vector to a serial Petsc vector:
- */
-
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-/*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
-
-/*Matlab includes: */
-#include "mex.h"
-
-#include "../../shared/shared.h"
-
-int MatlabVectorToPetscVector(Vec* pvector,int* pvector_rows,const mxArray* mxvector){
-
-	int rows, cols;
-	double* mxvector_ptr=NULL;
-	int ierr;
-	int i,j;
-
-	/*output: */
-	Vec vector=NULL;
-
-	/*matlab indices: */
-	mwIndex*    ir=NULL;
-	mwIndex*    jc=NULL;
-	double* pr=NULL;
-	int     count;
-	int     nnz;
-	int     nz;
-
-	/*petsc indices: */
-	int* idxm=NULL;
-	
-	/*Ok, first check if we are dealing with a sparse or full vector: */
-	if (mxIsSparse(mxvector)){
-
-		/*Dealing with sparse vector: recover size first: */
-		mxvector_ptr=(double*)mxGetPr(mxvector);
-		rows=mxGetM(mxvector);
-		cols=mxGetN(mxvector);
-		nnz=mxGetNzmax(mxvector);
-		nz=(int)((double)nnz/(double)rows);
-
-		ierr=VecCreateSeq(PETSC_COMM_SELF,rows,&vector);CHKERRQ(ierr);
-
-		/*Now, get ir,jc and pr: */
-		pr=mxGetPr(mxvector);
-		ir=mxGetIr(mxvector);
-		jc=mxGetJc(mxvector);
-
-		/*Now, start inserting data into sparse vector: */
-		count=0;
-		for(i=0;i<cols;i++){
-			for(j=0;j<(jc[i+1]-jc[i]);j++){
-				VecSetValue(vector,ir[count],pr[count],INSERT_VALUES);
-				count++;
-			}
-		}
-
-	}
-	else{
-
-		/*Dealing with dense vector: recover pointer and size: */
-		mxvector_ptr=(double*)mxGetPr(mxvector);
-		rows=mxGetM(mxvector);
-		cols=mxGetN(mxvector);
-
-		/*Create serial vector: */
-		ierr=VecCreateSeq(PETSC_COMM_SELF,rows,&vector);CHKERRQ(ierr);
-
-		/*Insert mxvector_ptr values into petsc vector: */
-		idxm=(int*)xmalloc(rows*sizeof(int));
-
-		for(i=0;i<rows;i++)idxm[i]=i;
-
-		ierr=VecSetValues(vector,rows,idxm,mxvector_ptr,INSERT_VALUES);CHKERRQ(ierr);
-
-	}
-
-	/*Assemble vector: */
-	VecAssemblyBegin(vector);
-	VecAssemblyEnd(vector);
-
-	/*Assign output pointer: */
-	*pvector=vector;
-	*pvector_rows=rows;
-
-	return 1;
-}
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToSeqVec.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToSeqVec.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToSeqVec.cpp	(revision 12878)
@@ -3,5 +3,5 @@
 
 /*Headers:*/
-/*{{{1*/
+/*{{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToVector.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToVector.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/MatlabVectorToVector.cpp	(revision 12878)
@@ -3,5 +3,5 @@
 
 /*Headers:*/
-/*{{{1*/
+/*{{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -14,5 +14,5 @@
 #include <string.h>
 #include "./matlabio.h"
-#include "../../objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../shared/shared.h"
 #include "../../Container/Container.h"
@@ -31,7 +31,7 @@
 
 	#ifdef _HAVE_PETSC_
-	MatlabVectorToPetscVector(&vector->vector,&dummy,mxvector);
+	vector->pvector=MatlabVectorToPetscVec(mxvector);
 	#else
-	vector->vector=MatlabVectorToSeqVec(mxvector);
+	vector->svector=MatlabVectorToSeqVec(mxvector);
 	#endif
 	
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/OptionParse.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/OptionParse.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/OptionParse.cpp	(revision 12878)
@@ -8,4 +8,6 @@
 #endif
 
+#include <cstring> 
+#include <mex.h>
 #include "../../shared/shared.h"
 #include "../../io/io.h"
@@ -13,7 +15,5 @@
 #include "./matlabio.h"
 
-#include <mex.h>
-
-/*FUNCTION OptionDoubleParse {{{1*/
+/*FUNCTION OptionDoubleParse {{{*/
 OptionDouble* OptionDoubleParse( char* name, const mxArray* prhs[]){
 
@@ -22,17 +22,16 @@
 	/*check and parse the name  */
 	odouble=new OptionDouble;
-	odouble->name =(char *) xmalloc((strlen(name)+1)*sizeof(char));
+	odouble->name =xNew<char>(strlen(name)+1);
 	memcpy(odouble->name,name,(strlen(name)+1)*sizeof(char));
 
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"double")){
-		_error_("Value of option \"%s\" must be class \"%s\", not class \"%s\".",odouble->name,"double",odouble->name,mxGetClassName(prhs[0]));
+		_error2_("Value of option \"" << odouble->name  << "\" must be class \"double\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
-
 	FetchData(&odouble->values,&odouble->numel,&odouble->ndims,&odouble->size,prhs[0]);
 
 	return(odouble);
 }/*}}}*/
-/*FUNCTION OptionLogicalParse {{{1*/
+/*FUNCTION OptionLogicalParse {{{*/
 OptionLogical* OptionLogicalParse( char* name, const mxArray* prhs[]){
 
@@ -41,17 +40,16 @@
 	/*check and parse the name  */
 	ological=new OptionLogical;
-	ological->name =(char*)xmalloc((strlen(name)+1)*sizeof(char));
+	ological->name =xNew<char>(strlen(name)+1);
 	memcpy(ological->name,name,(strlen(name)+1)*sizeof(char));
 
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"logical")){
-		_error_("Value of option \"%s\" must be class \"%s\", not class \"%s\".",ological->name,"logical",ological->name,mxGetClassName(prhs[0]));
+		_error2_("Value of option \"" << ological->name  << "\" must be class \"logical\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
-
 	FetchData(&ological->values,&ological->numel,&ological->ndims,&ological->size,prhs[0]);
 
 	return(ological);
 }/*}}}*/
-/*FUNCTION OptionCharParse {{{1*/
+/*FUNCTION OptionCharParse {{{*/
 OptionChar* OptionCharParse( char* name, const mxArray* prhs[]){
 
@@ -60,17 +58,16 @@
 	/*check and parse the name  */
 	ochar=new OptionChar();
-	ochar->name =(char*)xmalloc((strlen(name)+1)*sizeof(char));
+	ochar->name =xNew<char>(strlen(name)+1);
 	memcpy(ochar->name,name,(strlen(name)+1)*sizeof(char));
 
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"char")){
-		_error_("Value of option \"%s\" must be class \"%s\", not class \"%s\".",ochar->name,"char",ochar->name,mxGetClassName(prhs[0]));
+		_error2_("Value of option \"" << ochar->name  << "\" must be class \"char\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
-
 	FetchData(&ochar->values,&ochar->numel,&ochar->ndims,&ochar->size,prhs[0]);
 
 	return(ochar);
 }/*}}}*/
-/*FUNCTION OptionStructParse {{{1*/
+/*FUNCTION OptionStructParse {{{*/
 OptionStruct* OptionStructParse( char* name, const mxArray* prhs[]){
 
@@ -85,18 +82,17 @@
 	/*check and parse the name  */
 	ostruct=new OptionStruct;
-	ostruct->name =(char*)xmalloc((strlen(name)+1)*sizeof(char));
+	ostruct->name =xNew<char>(strlen(name)+1);
 	memcpy(ostruct->name,name,(strlen(name)+1)*sizeof(char));
 
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"struct")){
-		_error_("Value of option \"%s\" must be class \"%s\", not class \"%s\".",ostruct->name,"struct",ostruct->name,mxGetClassName(prhs[0]));
+		_error2_("Value of option \"" << ostruct->name  << "\" must be class \"struct\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
-
 	ostruct->numel=mxGetNumberOfElements(prhs[0]);
 	ostruct->ndims=mxGetNumberOfDimensions(prhs[0]);
 	ipt           =mxGetDimensions(prhs[0]);
-	ostruct->size =(int *) xmalloc(ostruct->ndims*sizeof(int));
+	ostruct->size =xNew<int>(ostruct->ndims);
 	for (i=0; i<ostruct->ndims; i++) ostruct->size[i]=(int)ipt[i];
-	if (ostruct->numel) ostruct->values=(Options**) xmalloc(ostruct->numel*sizeof(Options *));
+	if (ostruct->numel) ostruct->values=xNew<Options*>(ostruct->numel);
 
 	/*loop through and process each element of the struct array  */
@@ -117,5 +113,5 @@
 	return(ostruct);
 }/*}}}*/
-/*FUNCTION OptionCellParse {{{1*/
+/*FUNCTION OptionCellParse {{{*/
 OptionCell* OptionCellParse( char* name, const mxArray* prhs[]){
 
@@ -132,10 +128,10 @@
 	/*check and parse the name  */
 	ocell=new OptionCell;
-	ocell->name =(char *) xmalloc((strlen(name)+1)*sizeof(char));
+	ocell->name =xNew<char>(strlen(name)+1);
 	memcpy(ocell->name,name,(strlen(name)+1)*sizeof(char));
 
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"cell")){
-		_error_("Value of option \"%s\" must be class \"%s\", not class \"%s\".",ocell->name,"cell",ocell->name,mxGetClassName(prhs[0]));
+		_error2_("Value of option \"" << ocell->name  << "\" must be class \"cell\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
 
@@ -143,10 +139,10 @@
 	ocell->ndims=mxGetNumberOfDimensions(prhs[0]);
 	ipt         =mxGetDimensions(prhs[0]);
-	ocell->size =(int *) xmalloc(ocell->ndims*sizeof(int));
+	ocell->size =xNew<int>(ocell->ndims);
 	for (i=0; i<ocell->ndims; i++) ocell->size[i]=(int)ipt[i];
 	ocell->values=new Options;
 
 	/*loop through and process each element of the cell array  */
-	dims=(int *) xmalloc(ocell->ndims*sizeof(int));
+	dims=xNew<int>(ocell->ndims);
 	for (cindex=0; cindex<ocell->numel; cindex++) {
 		ColumnWiseDimsFromIndex(dims,(int)cindex,ocell->size,ocell->ndims);
@@ -163,9 +159,9 @@
 		option=NULL;
 	}
-	xfree((void**)&dims);
+	xDelete<int>(dims);
 
 	return(ocell);
 }/*}}}*/
-/*FUNCTION OptionParse{{{1*/
+/*FUNCTION OptionParse{{{*/
 Option* OptionParse(char* name, const mxArray* prhs[]){
 
@@ -180,10 +176,10 @@
 	else if(mxIsClass(prhs[0],"cell"))    option=(Option*)OptionCellParse(name,prhs);
 	else {
-		_printf_(true,"  Converting value of option \"%s\" from unrecognized class \"%s\" to class \"%s\".\n",name,mxGetClassName(prhs[0]),"struct");
+		_pprintLine_("  Converting value of option \"" << name << "\" from unrecognized class \"" << mxGetClassName(prhs[0]) << "\" to class \"" << "struct" << "\".");
 		if (!mexCallMATLAB(1,lhs,1,(mxArray**)prhs,"struct")) {
 			option=(Option*)OptionStructParse(name,(const mxArray**)lhs);
 			mxDestroyArray(lhs[0]);
 		}
-		else _error_("Second argument value of option \"%s\" is of unrecognized class \"%s\".",name,mxGetClassName(prhs[0]));
+		else _error2_("Second argument value of option \""<< name <<"\" is of unrecognized class \""<< mxGetClassName(prhs[0]) <<"\".");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/PrintfFunction.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/PrintfFunction.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/PrintfFunction.cpp	(revision 12878)
@@ -27,5 +27,5 @@
 
 		/*allocate buffer for given string size*/
-		buffer=(char*)xmalloc(size*sizeof(char));
+		buffer=xNew<char>(size);
 
 		/* Try to print in the allocated space. */
@@ -47,12 +47,12 @@
 		 size*=2;  /* twice the old size */
 
-		xfree((void**)&buffer);
+		xDelete<char>(buffer);
 	}
 
 	/*Ok, if we are running in parallel, get node 0 to print*/
-	if(my_rank==0)printf(buffer);
+	if(my_rank==0)_printString_(buffer);
 
 	/*Clean up and return*/
-	xfree((void**)&buffer);
+	xDelete<char>(buffer);
 	return 1;
 }
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/WriteMatlabData.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/WriteMatlabData.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/WriteMatlabData.cpp	(revision 12878)
@@ -17,5 +17,5 @@
 
 /*Primitive data types*/
-/*FUNCTION WriteData(mxArray** pdataref,double* matrix, int M,int N){{{1*/
+/*FUNCTION WriteData(mxArray** pdataref,double* matrix, int M,int N){{{*/
 void WriteData(mxArray** pdataref,double* matrix, int M,int N){
 
@@ -42,5 +42,5 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,int* matrix, int M,int N){{{1*/
+/*FUNCTION WriteData(mxArray** pdataref,int* matrix, int M,int N){{{*/
 void WriteData(mxArray** pdataref,int* matrix, int M,int N){
 
@@ -67,5 +67,5 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,double* vector, int M){{{1*/
+/*FUNCTION WriteData(mxArray** pdataref,double* vector, int M){{{*/
 void WriteData(mxArray** pdataref,double* vector, int M){
 	
@@ -90,5 +90,5 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,double scalar){{{1*/
+/*FUNCTION WriteData(mxArray** pdataref,double scalar){{{*/
 void WriteData(mxArray** pdataref,double scalar){
 
@@ -96,5 +96,5 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,int integer){{{1*/
+/*FUNCTION WriteData(mxArray** pdataref,int integer){{{*/
 void WriteData(mxArray** pdataref,int integer){
 
@@ -103,5 +103,5 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,int boolean){{{1*/
+/*FUNCTION WriteData(mxArray** pdataref,int boolean){{{*/
 void WriteData(mxArray** pdataref,bool boolean){
 
@@ -110,5 +110,5 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,char* string){{{1*/
+/*FUNCTION WriteData(mxArray** pdataref,char* string){{{*/
 void WriteData(mxArray** pdataref,char* string){
 
@@ -118,5 +118,5 @@
 
 /*ISSM objects*/
-/*FUNCTION WriteData(mxArray** pdataref,BamgGeom* bamggeom){{{1*/
+/*FUNCTION WriteData(mxArray** pdataref,BamgGeom* bamggeom){{{*/
 void WriteData(mxArray** pdataref,BamgGeom* bamggeom){
 
@@ -158,5 +158,5 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,BamgMesh* bamgmesh){{{1*/
+/*FUNCTION WriteData(mxArray** pdataref,BamgMesh* bamgmesh){{{*/
 void WriteData(mxArray** pdataref,BamgMesh* bamgmesh){
 
@@ -216,5 +216,5 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,Matrix* matrix){{{1*/
+/*FUNCTION WriteData(mxArray** pdataref,Matrix* matrix){{{*/
 void WriteData(mxArray** pdataref,Matrix* matrix){
 		
@@ -227,10 +227,6 @@
 	if(matrix){
 		
-		#ifdef _HAVE_PETSC_
-		PetscMatrixToDoubleMatrix(&matrix_ptr,&rows,&cols,matrix->matrix);
-		#else
-		matrix_ptr=matrix->matrix->ToSerial();
-		matrix->matrix->GetSize(&rows,&cols);
-		#endif
+		matrix_ptr=matrix->ToSerial();
+		matrix->GetSize(&rows,&cols);
 
 		/*Now transpose the matrix and allocate with Matlab's memory manager: */
@@ -249,15 +245,15 @@
 
 		/*Free ressources:*/
-		xfree((void**)&matrix_ptr);
-
-	}
-	else{
-		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
-	}
-
-	*pdataref=dataref;
-}
-/*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,Vector* vector){{{1*/
+		xDelete<double>(matrix_ptr);
+
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,Vector* vector){{{*/
 void WriteData(mxArray** pdataref,Vector* vector){
 	
@@ -269,10 +265,6 @@
 	if(vector){
 		/*call toolkit routine: */
-		#ifdef _HAVE_PETSC_
-		PetscVectorToDoubleVector(&vector_ptr,&rows,vector->vector);
-		#else
-		vector_ptr=vector->vector->ToMPISerial();
-		vector->vector->GetSize(&rows);
-		#endif
+		vector_ptr=vector->ToMPISerial();
+		vector->GetSize(&rows);
 		
 		/*now create the matlab vector with Matlab's memory manager */
@@ -290,5 +282,5 @@
 
 	/*Clean-up and return*/
-	xfree((void**)&vector_ptr);
+	xDelete<double>(vector_ptr);
 	*pdataref=dataref;
 }
@@ -296,5 +288,5 @@
 
 /*Toolkit*/
-/*FUNCTION SetStructureField{{{1*/
+/*FUNCTION SetStructureField{{{*/
 void SetStructureField(mxArray* dataref,const char* fieldname,int M,int N,double* fieldpointer){
 
Index: /issm/branches/trunk-jpl-damage/src/c/matlab/io/matlabio.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/matlab/io/matlabio.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/matlab/io/matlabio.h	(revision 12878)
@@ -12,5 +12,5 @@
 #endif 
 
-#include "../../objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../Container/Container.h"
 #include "../../include/include.h"
@@ -79,6 +79,8 @@
 /*Matlab to Petsc routines: */
 #ifdef _HAVE_PETSC_
-int MatlabMatrixToPetscMatrix(Mat* matrix,int* prows,int* pcols, const mxArray* mxmatrix);
-int MatlabVectorToPetscVector(Vec* pvector,int* pvector_rows,const mxArray* mxvector);
+int MatlabMatrixToPetscMat(Mat* matrix,int* prows,int* pcols, const mxArray* mxmatrix);
+PetscMat* MatlabMatrixToPetscMat(const mxArray* mxmatrix);
+int MatlabVectorToPetscVec(Vec* pvector,int* pvector_rows,const mxArray* mxvector);
+PetscVec* MatlabVectorToPetscVec(const mxArray* mxvector);
 #endif
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/AddExternalResultx/AddExternalResultx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/AddExternalResultx/AddExternalResultx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/AddExternalResultx/AddExternalResultx.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../Container/Container.h"
 #include "../../io/io.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 		
 void AddExternalResultx( DataSet* results, int enumtype, double value){
Index: /issm/branches/trunk-jpl-damage/src/c/modules/AverageFilterx/AverageFilterx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/AverageFilterx/AverageFilterx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/AverageFilterx/AverageFilterx.cpp	(revision 12878)
@@ -18,7 +18,7 @@
 
 	/*output: */
-	double*         imageout=NULL;
+	double* imageout=NULL;
 
-	imageout=(double*)xmalloc(samps*lines*sizeof(double));
+	imageout=xNew<double>(samps*lines);
 
   	for ( i = 0; i < lines; i++ ){
Index: /issm/branches/trunk-jpl-damage/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 12878)
@@ -65,5 +65,5 @@
 
 	/*Free ressources:*/
-	xfree((void**)&qmu_part);
+	xDelete<double>(qmu_part);
 	xdelete(&partition_contributions);
 	xdelete(&partition_areas);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _AVERAGEONTOPARTITIONXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp	(revision 12878)
@@ -7,35 +7,24 @@
 #include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../objects/objects.h"
+#include "../../classes/bamg/bamgobjects.h"
 
 using namespace bamg;
 using namespace std;
 
-int BamgConvertMeshx(BamgMesh* bamgmesh,BamgGeom* bamggeom,double* index,double* x,double* y,int nods,int nels){
-
-	/*Intermediary*/
-	int i,j,k;
-	int verbose=0;
-	int noerr=1;
+int BamgConvertMeshx(BamgMesh* bamgmesh,BamgGeom* bamggeom,int* index,double* x,double* y,int nods,int nels){
 
 	/*Options*/
-	BamgOpts* bamgopts=NULL;
-	bamgopts=new BamgOpts();
+	BamgOpts* bamgopts=new BamgOpts();
 
-	// read mesh
-	if(verbose) printf("Reading mesh\n");
+	/*read mesh*/
 	Mesh Th(index,x,y,nods,nels); 
 
-	//write mesh and geometry
-	if (verbose) printf("Write Geometry\n");
+	/*write mesh and geometry*/
 	Th.Gh.WriteGeometry(bamggeom,bamgopts);
-	if (verbose) printf("Write Mesh\n");
 	Th.WriteMesh(bamgmesh,bamgopts);
 
-	//clean up
+	/*clean up and return*/
 	delete bamgopts;
-
-	/*No error return*/
-	return noerr;
+	return 1;
 
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h	(revision 12878)
@@ -6,8 +6,8 @@
 #define _BAMGCONVERTMESHX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-int BamgConvertMeshx(BamgMesh* bamgmesh,BamgGeom* bamggeom,double* index,double* x,double* y,int nods,int nels);
+int BamgConvertMeshx(BamgMesh* bamgmesh,BamgGeom* bamggeom,int* index,double* x,double* y,int nods,int nels);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 using namespace bamg;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/BamgTriangulatex/BamgTriangulatex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/BamgTriangulatex/BamgTriangulatex.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/BamgTriangulatex/BamgTriangulatex.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _BAMGTRIANGULATEX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Bamgx/Bamgx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Bamgx/Bamgx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Bamgx/Bamgx.cpp	(revision 12878)
@@ -3,5 +3,5 @@
  */
 #include "./Bamgx.h"
-#include "../../objects/objects.h"
+#include "../../classes/bamg/bamgobjects.h"
 #include "../../shared/shared.h"
 #include "../../include/include.h"
@@ -38,9 +38,9 @@
 	/*If no mesh in input, generate one*/
 	if(bamgmesh_in->TrianglesSize[0]==0){
-		/*Mesh generation {{{1*/
+		/*Mesh generation {{{*/
 
 		//Step1: generate geometry Gh
-		if (verbosity>0) printf("Construction of a mesh from a given geometry\n");
-		if (verbosity>1) printf("   Processing geometry...\n");
+		if (verbosity>0) _printLine_("Construction of a mesh from a given geometry");
+		if (verbosity>1) _printLine_("   Processing geometry...");
 		Geometry Gh(bamggeom_in,bamgopts);
 
@@ -50,5 +50,5 @@
 
 		//build metric using geometry
-		if (verbosity>1) printf("   Generating Metric...\n");
+		if (verbosity>1) _printLine_("   Generating Metric...");
 		for(i=0;i<Gh.nbv;i++){
 			Metric M=Gh[i];
@@ -60,5 +60,5 @@
 
 		//generate mesh
-		if (verbosity>1) printf("   Generating Mesh...\n");
+		if (verbosity>1) _printLine_("   Generating Mesh...");
 		Mesh Th(maxnbv,Gh,bamgopts);
 
@@ -73,7 +73,7 @@
 
 		//Build output
-		if (verbosity>1) printf("   Write Mesh...\n");
+		if (verbosity>1) _printLine_("   Write Mesh...");
 		Th.WriteMesh(bamgmesh_out,bamgopts);
-		if (verbosity>1) printf("   Write Geometry...\n");
+		if (verbosity>1) _printLine_("   Write Geometry...");
 		Gh.WriteGeometry(bamggeom_out,bamgopts);
 
@@ -84,9 +84,9 @@
 	}
 	else{
-		/*Anisotropic mesh adaptation {{{1*/
+		/*Anisotropic mesh adaptation {{{*/
 
 		// read background mesh 
-		if (verbosity>0) printf("Anisotropic mesh adaptation\n");
-		if (verbosity>1) printf("   Processing initial mesh and geometry...\n");
+		if (verbosity>0) _printLine_("Anisotropic mesh adaptation");
+		if (verbosity>1) _printLine_("   Processing initial mesh and geometry...");
 		Mesh BTh(bamggeom_in,bamgmesh_in,bamgopts); 
 
@@ -100,9 +100,9 @@
 		//Generate initial metric
 		if (bamgopts->metric){
-			if (verbosity>1) printf("   Processing Metric...\n");
+			if (verbosity>1) _printLine_("   Processing Metric...");
 			BTh.ReadMetric(bamgopts);
 		}
 		else { 
-			if (verbosity>1) printf("   Generating initial Metric...\n");
+			if (verbosity>1) _printLine_("   Generating initial Metric...");
 			Metric Mhmax(bamgopts->hmax);
 			for (int iv=0;iv<BTh.nbv;iv++) BTh[iv].m = Mhmax;
@@ -111,5 +111,5 @@
 		//use present fields to generate metric if present
 		if (bamgopts->field){
-			if (verbosity>1) printf("   Merge metric with field provided...\n");
+			if (verbosity>1) _printLine_("   Merge metric with field provided...");
 			BTh.AddMetric(bamgopts);
 		}
@@ -117,7 +117,7 @@
 		// change using hVertices if provided
 		if(bamgopts->hVertices && bamgopts->hVerticesSize[0]==BTh.nbv){
-			if (verbosity>1) printf("   Merging Metric with hVertices...\n");
+			if (verbosity>1) _printLine_("   Merging Metric with hVertices...");
 			for (i=0;i<BTh.nbv;i++){
-				if (!isnan(bamgopts->hVertices[i])){
+				if (!xIsNan<IssmDouble>(bamgopts->hVertices[i])){
 					BTh[i].m=Metric((float)bamgopts->hVertices[i]);
 				}
@@ -127,7 +127,7 @@
 		// change using hminVertices if provided
 		if (bamgopts->hminVertices){
-			if (verbosity>1) printf("   Merging Metric with hminVertices...\n");
+			if (verbosity>1) _printLine_("   Merging Metric with hminVertices...");
 			for (i=0;i<BTh.nbv;i++){
-				if (!isnan(bamgopts->hminVertices[i])){
+				if (!xIsNan<IssmDouble>(bamgopts->hminVertices[i])){
 					Metric M=BTh.vertices[i].m;
 					EigenMetric Vp(M/coef);
@@ -140,7 +140,7 @@
 		// change using hmaxVertices if provided
 		if (bamgopts->hmaxVertices){
-			if (verbosity>1) printf("   Merging Metric with hmaxVertices...\n");
+			if (verbosity>1) _printLine_("   Merging Metric with hmaxVertices...");
 			for (i=0;i<BTh.nbv;i++){
-				if (!isnan(bamgopts->hmaxVertices[i])){
+				if (!xIsNan<IssmDouble>(bamgopts->hmaxVertices[i])){
 					Metric M=BTh.vertices[i].m;
 					EigenMetric Vp(M/coef);
@@ -164,5 +164,5 @@
 
 		//Build new mesh
-		if (verbosity>1) printf("   Generating Mesh...\n");
+		if (verbosity>1) _printLine_("   Generating Mesh...");
 		Thr=&BTh,Thb=0;
 		Mesh & Th( *(0 ?  new Mesh(*Thr,&Thr->Gh,Thb,maxnbv) :  new Mesh(maxnbv,BTh,bamgopts,bamgopts->KeepVertices)));
@@ -185,17 +185,17 @@
 		if(verbosity>0) {
 			if (Th.nbt-Th.nbtout-Th.nbq*2){
-				printf("   new number of triangles = %i\n",(Th.nbt-Th.nbtout-Th.nbq*2));
+				_printLine_("   new number of triangles = " << (Th.nbt-Th.nbtout-Th.nbq*2));
 			}
 			if (Th.nbq ){
-				printf("   new number of quads = %i\n",Th.nbq);
+				_printLine_("   new number of quads = " << Th.nbq);
 			}
 		}
 
 		//Build output
-		if (verbosity>1) printf("   Write Mesh...\n");
+		if (verbosity>1) _printLine_("   Write Mesh...");
 		Th.WriteMesh(bamgmesh_out,bamgopts);
-		if (verbosity>1) printf("   Write Geometry...\n");
+		if (verbosity>1) _printLine_("   Write Geometry...");
 		Th.Gh.WriteGeometry(bamggeom_out,bamgopts);
-		if (verbosity>1) printf("   Write Metric...\n");
+		if (verbosity>1) _printLine_("   Write Metric...");
 		BTh.WriteMetric(bamgopts);
 
@@ -207,5 +207,5 @@
 
 	/*No error return*/
-	if (verbosity>1) printf("   Exiting Bamg.\n");
+	if (verbosity>1) _printLine_("   Exiting Bamg.");
 	return noerr;
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Bamgx/Bamgx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Bamgx/Bamgx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Bamgx/Bamgx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _BAMGX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/bamg/bamgobjects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Chacox/Chacox.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Chacox/Chacox.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Chacox/Chacox.cpp	(revision 12878)
@@ -66,10 +66,10 @@
 
 	if (DEBUG_TRACE > 0) {
-		printf("<Entering main>\n");
+		_printLine_("<Entering main>");
 	}
 
 	if (PRINT_HEADERS) {
-		printf("\n                    Chaco 2.0\n");
-		printf("          Sandia National Laboratories\n\n");
+		_printLine_("\n                    Chaco 2.0");
+		_printLine_("          Sandia National Laboratories\n");
 	}
 
@@ -177,5 +177,5 @@
 
 	if (DEBUG_MEMORY > 0) {
-		printf("\n");
+		_printLine_("");
 		smalloc_stats();
 	}
@@ -185,5 +185,5 @@
 
 	if (DEBUG_TRACE > 1) {
-		printf("<Leaving main>\n");
+		_printLine_("<Leaving main>");
 	}
 	
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Chacox/Chacox.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Chacox/Chacox.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Chacox/Chacox.h	(revision 12878)
@@ -33,5 +33,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Chacox/input_parse.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Chacox/input_parse.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Chacox/input_parse.cpp	(revision 12878)
@@ -38,13 +38,13 @@
 
 	if (DEBUG_TRACE > 0) {
-		printf("<Entering input_parse>\n");
+		_printLine_("<Entering input_parse>");
 	}
 
 	if (PROMPT) {
-		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");
+		_printLine_("Parallel machine architecture:");
+		_printLine_("  (0) Hypercube");
+		_printLine_("  (1) One-dimensional mesh");
+		_printLine_("  (2) Two-dimensional mesh");
+		_printLine_("  (3) Three-dimensional mesh");
 	}
 	*architecture = (int)options[OPT_ARCH];
@@ -57,10 +57,10 @@
 	/* Name output assignment file. */
 	if (PROMPT)
-		printf("Assignment output file: ");
+		_printString_("Assignment output file: ");
 	outassignname = NULL;
 
 	/* Name output results file. */
 	if (PROMPT)
-		printf("File name for saving run results: ");
+		_printString_("File name for saving run results: ");
 	outfilename = NULL;
 
@@ -75,12 +75,12 @@
 	else {
 		if (PROMPT) {
-			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");
+			_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");
 		}
 		*global_method = (int)options[OPT_GLOBAL];
@@ -94,17 +94,17 @@
 	if (*global_method == 7) {	/* Name and open input assignment file. */
 		if (PROMPT)
-			printf("Assignment input file: ");
+			_printString_("Assignment input file: ");
 	}
 
 	else if (*global_method == 3) {
 		if (PROMPT)
-			printf("Geometry input file name: ");
+			_printString_("Geometry input file name: ");
 	}
 
 	else if (*global_method == 2) {
 		if (PROMPT) {
-			printf("Eigensolver:\n");
-			printf("  (1) Multilevel RQI/Symmlq\n");
-			printf("  (2) Lanczos\n"); 
+			_printLine_("Eigensolver:");
+			_printLine_("  (1) Multilevel RQI/Symmlq");
+			_printLine_("  (2) Lanczos"); 
 		}
 		eigensolver = (int)options[OPT_RQI];
@@ -117,9 +117,9 @@
 			if (MATCH_TYPE == 5) {	/* geometric matching */
 				if (PROMPT)
-					printf("Geometry input file name: ");
+					_printString_("Geometry input file name: ");
 			}
 			*rqi_flag = 1;
 			if (PROMPT)
-				printf("Number of vertices to coarsen down to: ");
+				_printString_("Number of vertices to coarsen down to: ");
 			*vmax = (int)options[OPT_VMAX];
 			if (*vmax <= 0) {
@@ -137,8 +137,8 @@
 		if (MATCH_TYPE == 5) {		/* geometric matching */
 			if (PROMPT)
-				printf("Geometry input file name: ");
-		}
-		if (PROMPT)
-			printf("Number of vertices to coarsen down to: ");
+				_printString_("Geometry input file name: ");
+		}
+		if (PROMPT)
+			_printString_("Number of vertices to coarsen down to: ");
 		*vmax = (int)options[OPT_VMAX];
 		if (*vmax <= 0) {
@@ -168,7 +168,7 @@
 	else {
 		if (PROMPT) {
-			printf("Local refinement method:\n");
-			printf("  (1) Kernighan-Lin\n");
-			printf("  (2) None\n");
+			_printLine_("Local refinement method:");
+			_printLine_("  (1) Kernighan-Lin");
+			_printLine_("  (2) None");
 		}
 		*local_method = (int)options[OPT_LOCAL];
@@ -185,8 +185,8 @@
 		*ndims_tot = 0;
 		if (PROMPT)
-			printf("Total number of target hypercube dimensions: ");
+			_printString_("Total number of target hypercube dimensions: ");
 		*ndims_tot = nparts[0];
 		if (*ndims_tot < 1) {
-			printf(" Number of divisions must be at least 1\n");
+			_printLine_(" Number of divisions must be at least 1");
 			printf("%s -- Number of divisions %d must be at least 1.\n",
 				   __FUNCT__,nparts[0]);
@@ -200,5 +200,5 @@
 		if (*architecture == 2) {
 			if (PROMPT)
-				printf("X and Y extent of of 2-D mesh: ");
+				_printString_("X and Y extent of of 2-D mesh: ");
 			mesh_dims[0] = nparts[0];
 			mesh_dims[1] = nparts[1];
@@ -206,5 +206,5 @@
 		else if (*architecture == 3) {
 			if (PROMPT)
-				printf("X, Y and Z extent of 3-D mesh: ");
+				_printString_("X, Y and Z extent of 3-D mesh: ");
 			mesh_dims[0] = nparts[0];
 			mesh_dims[1] = nparts[1];
@@ -213,5 +213,5 @@
 		else {			/* Anything else => 1-D mesh */
 			if (PROMPT)
-				printf("Size of 1-D mesh: ");
+				_printString_("Size of 1-D mesh: ");
 			mesh_dims[0] = nparts[0];
 			*architecture = 1;
@@ -227,7 +227,7 @@
 	else if (*nprocs <= 7) {
 		if (PROMPT) {
-			printf("Partitioning dimension: \n");
-			printf("  (1) Bisection\n");
-			printf("  (2) Quadrisection\n");
+			_printLine_("Partitioning dimension: ");
+			_printLine_("  (1) Bisection");
+			_printLine_("  (2) Quadrisection");
 		}
 		*ndims = (int)options[OPT_NDIMS];
@@ -240,8 +240,8 @@
 	else {
 		if (PROMPT) {
-			printf("Partitioning dimension: \n");
-			printf("  (1) Bisection\n");
-			printf("  (2) Quadrisection\n");
-			printf("  (3) Octasection\n");
+			_printLine_("Partitioning dimension: ");
+			_printLine_("  (1) Bisection");
+			_printLine_("  (2) Quadrisection");
+			_printLine_("  (3) Octasection");
 		}
 		*ndims = (int)options[OPT_NDIMS];
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp	(revision 12878)
@@ -15,5 +15,5 @@
 	int i;
 	int      found=0;
-	double   numberofelements;
+	IssmDouble   numberofelements;
 	Element* element=NULL;
 
@@ -25,5 +25,5 @@
 
 	/*Allocate sigma on numberofelements: */
-	sigma=new Vector((int)numberofelements);
+	sigma=new Vector(reCast<int>(numberofelements));
 
 	/*Compute basal stress for each element: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _COMPUTEBASALSTRESSX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _COMPUTESTRAINRATEX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 12878)
@@ -25,10 +25,10 @@
 	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
 	
-	_printf_(VerboseMProcessor(),"      Configuring elements...\n");
+	if(VerboseMProcessor()) _pprintLine_("      Configuring elements...");
 	for (i=0;i<elements->Size();i++){
 		element=(Element*)elements->GetObjectByOffset(i);
 		element->Configure(elements,loads,nodes,materials,parameters);
 	}
-	_printf_(VerboseMProcessor(),"      Configuring loads...\n");
+	if(VerboseMProcessor()) _pprintLine_("      Configuring loads...");
 	for (i=0;i<loads->Size();i++){
 		load=(Load*)loads->GetObjectByOffset(i);
@@ -37,5 +37,5 @@
 		}
 	}
-	_printf_(VerboseMProcessor(),"      Configuring nodes...\n");
+	if(VerboseMProcessor()) _pprintLine_("      Configuring nodes...");
 	for (i=0;i<nodes->Size();i++){
 		node=(Node*)nodes->GetObjectByOffset(i);
@@ -45,5 +45,5 @@
 	}
 	
-	_printf_(VerboseMProcessor(),"      Configuring materials...\n");
+	if(VerboseMProcessor()) _pprintLine_("      Configuring materials...");
 	for (i=0;i<materials->Size();i++){
 		material=(Material*)materials->GetObjectByOffset(i);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /*melting: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 12878)
@@ -25,5 +25,5 @@
 
 	/*Display message*/
-	_printf_(VerboseModule(),"   Constraining penalties\n");
+	if(VerboseModule()) _pprintLine_("   Constraining penalties");
 
 	/*recover parameters: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStatex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 12878)
@@ -12,5 +12,5 @@
 
 /*current module: */
-/*RiftIsPresent(Loads* loads,int configuration_type){{{1*/
+/*RiftIsPresent(Loads* loads,int configuration_type){{{*/
 int RiftIsPresent(Loads* loads,int configuration_type){
 
@@ -41,5 +41,5 @@
 }
 /*}}}*/
-/*RiftConstraintsState(int* pconverged, int* pnum_unstable_constraints,Loads* loads,int min_mechanical_constraints,int configuration_type){{{1*/
+/*RiftConstraintsState(int* pconverged, int* pnum_unstable_constraints,Loads* loads,int min_mechanical_constraints,int configuration_type){{{*/
 void RiftConstraintsState(int* pconverged, int* pnum_unstable_constraints,Loads* loads,int min_mechanical_constraints,int configuration_type){
 
@@ -56,5 +56,5 @@
 	}
 	else if(num_unstable_constraints<=min_mechanical_constraints){
-		_printf_(VerboseModule(),"   freezing constraints\n");
+		if(VerboseModule()) _pprintLine_("   freezing constraints");
 		RiftFreezeConstraints(loads,configuration_type);
 	}
@@ -65,5 +65,5 @@
 }
 /*}}}*/
-/*RiftConstrain(int* pnum_unstable_constraints,Loads* loads,int configuration_type){{{1*/
+/*RiftConstrain(int* pnum_unstable_constraints,Loads* loads,int configuration_type){{{*/
 void RiftConstrain(int* pnum_unstable_constraints,Loads* loads,int configuration_type){
 
@@ -106,5 +106,5 @@
 }
 /*}}}*/
-/*RiftIsFrozen(Loads* loads,int configuration_type){{{1*/
+/*RiftIsFrozen(Loads* loads,int configuration_type){{{*/
 int RiftIsFrozen(Loads* loads,int configuration_type){
 
@@ -144,5 +144,5 @@
 }
 /*}}}*/
-/*RiftFreezeConstraints(Loads* loads,int configuration_type){{{1*/
+/*RiftFreezeConstraints(Loads* loads,int configuration_type){{{*/
 void RiftFreezeConstraints(Loads* loads,int configuration_type){
 
@@ -172,5 +172,5 @@
 
 /*diverse trials and errors: */
-/*RiftIsMaterialStable(Loads* loads){{{1*/
+/*RiftIsMaterialStable(Loads* loads){{{*/
 int RiftIsMaterialStable(Loads* loads){
 
@@ -204,5 +204,5 @@
 }
 /*}}}*/
-/*RiftIsPreStable(Loads* loads){{{1*/
+/*RiftIsPreStable(Loads* loads){{{*/
 int RiftIsPreStable(Loads* loads){
 
@@ -243,5 +243,5 @@
 }
 /*}}}*/
-/*RiftSetPreStable(Loads* loads){{{1*/
+/*RiftSetPreStable(Loads* loads){{{*/
 void RiftSetPreStable(Loads* loads){
 
@@ -264,5 +264,5 @@
 }
 /*}}}*/
-/*RiftPreConstrain(int* pnum_unstable_constraints,Loads* loads){{{1*/
+/*RiftPreConstrain(int* pnum_unstable_constraints,Loads* loads){{{*/
 void RiftPreConstrain(int* pnum_unstable_constraints,Loads* loads){
 
@@ -300,5 +300,5 @@
 }
 /*}}}*/
-/*RiftMaxPenetrationInInputs(Loads* loads){{{1*/
+/*RiftMaxPenetrationInInputs(Loads* loads){{{*/
 void RiftMaxPenetrationInInputs(Loads* loads){
 
@@ -309,7 +309,7 @@
 
 	/*rift penetration: */
-	double max_penetration=0;
-	double mpi_max_penetration;
-	double penetration;
+	IssmDouble max_penetration=0;
+	IssmDouble mpi_max_penetration;
+	IssmDouble penetration;
 
 	/*Ok, we are going to find the node pairs which are not penetrating, even though they 
@@ -342,5 +342,5 @@
 }
 /*}}}*/
-/*RiftPotentialUnstableConstraints(Loads* loads){{{1*/
+/*RiftPotentialUnstableConstraints(Loads* loads){{{*/
 int RiftPotentialUnstableConstraints(Loads* loads){
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 12878)
@@ -70,5 +70,5 @@
 
 	/*Free ressources:*/
-	xfree((void**)&in_nod_serial);
+	xDelete<double>(in_nod_serial);
 
 	return noerr;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ContourToMeshx/ContourToMeshx.h	(revision 12878)
@@ -8,5 +8,5 @@
 
 #include "../../shared/shared.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /*threading: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ContourToNodesx/ContourToNodesx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ContourToNodesx/ContourToNodesx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ContourToNodesx/ContourToNodesx.h	(revision 12878)
@@ -8,5 +8,5 @@
 
 #include "../../shared/shared.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp	(revision 12878)
@@ -33,5 +33,5 @@
 
 	/*Clean up and return*/
-	xfree((void**)&control_type);
+	xDelete<int>(control_type);
 	*pgradient=gradient;
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.h	(revision 12878)
@@ -5,5 +5,5 @@
 #define _CONTROLINPUTGETGRADIENTX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp	(revision 12878)
@@ -37,5 +37,5 @@
 
 	/*Clean up and return*/
-	xfree((void**)&control_type);
-	xfree((void**)&scalar_list);
+	xDelete<int>(control_type);
+	xDelete<double>(scalar_list);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h	(revision 12878)
@@ -5,5 +5,5 @@
 #define _CONTROLINPUTSSCALEGRADIENTX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 12878)
@@ -27,5 +27,5 @@
 
 	/*Clean up and return*/
-	xfree((void**)&control_type);
+	xDelete<int>(control_type);
 
 }
@@ -39,4 +39,4 @@
 
 	/*Clean up and return*/
-	xfree((void**)&serial_gradient);
+	xDelete<double>(serial_gradient);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h	(revision 12878)
@@ -5,5 +5,5 @@
 #define _CONTROLINPUTSSETGRADIENTX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.cpp	(revision 12878)
@@ -35,5 +35,5 @@
 
 	/*Assign output pointers: */
-	xfree((void**)&responses);
+	xDelete<int>(responses);
 	*pJ=J;
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/CostFunctionx/CostFunctionx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp	(revision 12878)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void CreateJacobianMatrixx(Matrix** pJff,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,double kmax){
+void CreateJacobianMatrixx(Matrix** pJff,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,IssmDouble kmax){
 	
 	int      i,connectivity;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h	(revision 12878)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void CreateJacobianMatrixx(Matrix** pJff,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,double kmax);
+void CreateJacobianMatrixx(Matrix** pJff,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,IssmDouble kmax);
 
 #endif  /* _CREATEJACOBIANMATRIXX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h	(revision 12878)
@@ -6,5 +6,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.cpp	(revision 12878)
@@ -30,8 +30,7 @@
 	double femmodel_response;
 	int    flag;
-	double* vertex_response=NULL;
-	double* qmu_response=NULL;
-
-	double* responses_pointer=NULL;
+	double *vertex_response   = NULL;
+	double *qmu_response      = NULL;
+	double *responses_pointer = NULL;
 
 	/*retrieve npart: */
@@ -66,6 +65,6 @@
 
 			/*Free ressources:*/
-			xfree((void**)&vertex_response);
-			xfree((void**)&qmu_response);
+			xDelete<double>(vertex_response);
+			xDelete<double>(qmu_response);
 
 		}
@@ -87,5 +86,5 @@
 		}
 		else if (flag==NodalEnum){
-			_error_(" nodal response functions not supported yet!");
+			_error2_("nodal response functions not supported yet!");
 
 			/*increment response_pointer :*/
@@ -105,5 +104,5 @@
 			}
 		}
-		else _error_("%s%i%s"," flag type ",flag," not supported yet for response analysis");
+		else _error2_("flag type " << flag << " not supported yet for response analysis");
 	}
 
@@ -111,8 +110,8 @@
 	/*Synthesize echo: {{{*/
 	if(my_rank==0){
-		printf("   responses: %i: ",d_numresponses);
-		for(i=0;i<d_numresponses-1;i++)printf("%g|",d_responses[i]);
-		printf("%g",d_responses[d_numresponses-1]);
-		printf("\n");
+		_printString_("   responses: " << d_numresponses << ": ");
+		for(i=0;i<d_numresponses-1;i++)_printString_(d_responses[i] << "|");
+		_printString_(d_responses[d_numresponses-1]);
+		_printLine_("");
 	}
 	/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/DakotaResponsesx/DakotaResponsesx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _DAKOTARESPONSESXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/DakotaFree.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/DakotaFree.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/DakotaFree.cpp	(revision 12878)
@@ -22,8 +22,8 @@
 	extern int my_rank;
 	
-	double* variables=NULL;
-	char**  variables_descriptors=NULL;
-	char**  responses_descriptors=NULL;
-	char*   string=NULL;
+	double  *variables             = NULL;
+	char   **variables_descriptors = NULL;
+	char   **responses_descriptors = NULL;
+	char    *string                = NULL;
 
 	/*recover pointers: */
@@ -35,10 +35,10 @@
 	/*Free variables and variables_descriptors only on cpu !=0*/
 	if(my_rank!=0){
-		xfree((void**)&variables);
+		xDelete<double>(variables);
 		for(i=0;i<numvariables;i++){
 			string=variables_descriptors[i];
-			xfree((void**)&string);
+			xDelete<char>(string);
 		}
-		xfree((void**)&variables_descriptors);
+		xDelete<char*>(variables_descriptors);
 	}
 	
@@ -46,8 +46,8 @@
 	for(i=0;i<numresponses;i++){
 		string=responses_descriptors[i];
-		xfree((void**)&string);
+		xDelete<char>(string);
 	}
 	//rest of dynamic allocations.
-	xfree((void**)&responses_descriptors);
+	xDelete<char*>(responses_descriptors);
 
 	/*Assign output pointers:*/
@@ -56,3 +56,2 @@
 	*presponses_descriptors=responses_descriptors;
 }
-
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/DakotaMPI_Bcast.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/DakotaMPI_Bcast.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/DakotaMPI_Bcast.cpp	(revision 12878)
@@ -38,10 +38,10 @@
 	
 	/*variables:*/
-	if(my_rank!=0)variables=(double*)xmalloc(numvariables*sizeof(double));
+	if(my_rank!=0)variables=xNew<double>(numvariables);
 	MPI_Bcast(variables,numvariables,MPI_DOUBLE,0,MPI_COMM_WORLD); 
 
 	/*variables_descriptors: */
 	if(my_rank!=0){
-		variables_descriptors=(char**)xmalloc(numvariables*sizeof(char*));
+		variables_descriptors=xNew<char*>(numvariables);
 	}
 	for(i=0;i<numvariables;i++){
@@ -51,5 +51,5 @@
 		}
 		MPI_Bcast(&string_length,1,MPI_INT,0,MPI_COMM_WORLD); 
-		if(my_rank!=0)string=(char*)xmalloc(string_length);
+		if(my_rank!=0)string=xNew<char>(string_length);
 		MPI_Bcast(string,string_length,MPI_CHAR,0,MPI_COMM_WORLD); 
 		if(my_rank!=0)variables_descriptors[i]=string;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/Dakotax.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/Dakotax.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/Dakotax.cpp	(revision 12878)
@@ -40,5 +40,5 @@
 #include "../../toolkits/toolkits.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../../objects/DakotaPlugin.h"
+#include "../../classes/dakota/DakotaPlugin.h"
 
 #ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
@@ -121,7 +121,7 @@
 
 	/*Free ressources:*/
-	xfree((void**)&dakota_input_file);
-	xfree((void**)&dakota_error_file);
-	xfree((void**)&dakota_output_file);
+	xDelete<char>(dakota_input_file);
+	xDelete<char>(dakota_error_file);
+	xDelete<char>(dakota_output_file);
 
 	#endif //#ifdef _HAVE_DAKOTA_
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/Dakotax.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/Dakotax.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/Dakotax.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/DescriptorIndex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/DescriptorIndex.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/DescriptorIndex.cpp	(revision 12878)
@@ -23,10 +23,10 @@
 	/*retrieve first token, separated by underscore: */
 	pch = strtok (descriptor,"_");
-	if(!pch)_error_("%s%s%s"," descriptor ",descriptor," is not correctly formatted!");
+	if(!pch)_error2_("descriptor " << descriptor << " is not correctly formatted!");
 
 	if (strncmp(pch,"scaled",6)==0){
 		/*we have a scaled variable. recover the root: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error_("%s%s%s"," scaled descriptor ",descriptor," is not correctly formatted!");
+		if(!pch)_error2_("scaled descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 
@@ -44,9 +44,9 @@
 		/*we have an indexed variable. recover the root: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error_("%s%s%s"," indexed descriptor ",descriptor," is not correctly formatted!");
+		if(!pch)_error2_("indexed descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 		/*now recover  the index: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error_("%s%s%s"," indexed descriptor ",descriptor," is not correctly formatted!");
+		if(!pch)_error2_("indexed descriptor " << descriptor << " is not correctly formatted!");
 		sscanf(pch,"%i",pindex);
 		return IndexedEnum;
@@ -55,9 +55,9 @@
 		/*we have an indexed variable. recover the root: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error_("%s%s%s"," nodal descriptor ",descriptor," is not correctly formatted!");
+		if(!pch)_error2_("nodal descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 		/*now recover  the index: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error_("%s%s%s"," nodal descriptor ",descriptor," is not correctly formatted!");
+		if(!pch)_error2_("nodal descriptor " << descriptor << " is not correctly formatted!");
 		sscanf(pch,"%i",pindex);
 		return NodalEnum;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCore.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCore.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCore.cpp	(revision 12878)
@@ -10,5 +10,5 @@
 
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../io/io.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCoreParallel.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCoreParallel.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Dakotax/SpawnCoreParallel.cpp	(revision 12878)
@@ -26,5 +26,5 @@
 
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../io/io.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
@@ -53,5 +53,5 @@
 	/*synchronize all cpus, as CPU 0 is probably late (it is starting the entire dakota strategy!) : */
 	MPI_Barrier(MPI_COMM_WORLD);
-	_printf_(VerboseQmu(),"qmu iteration: %i\n",counter);
+	if(VerboseQmu()) _pprintLine_("qmu iteration: " << counter);
 	
 	/*retrieve parameters: */
@@ -67,10 +67,10 @@
 
 	/*Determine solution sequence: */
-	_printf_(VerboseQmu(),"%s%s%s\n","Starting ",EnumToStringx(solution_type)," core:");
+	if(VerboseQmu()) _pprintLine_("Starting " << EnumToStringx(solution_type) << " core:");
 	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
 	#ifdef _HAVE_CONTROL_
 	if(control_analysis)solutioncore=&control_core;
 	#else
-	_error_("ISSM was not compiled with control capabilities, exiting!");
+	_error2_("ISSM was not compiled with control capabilities, exiting!");
 	#endif
 
@@ -79,5 +79,5 @@
 
 	/*compute responses: */
-	_printf_(VerboseQmu(),"compute dakota responses:\n");
+	if(VerboseQmu()) _pprintLine_("compute dakota responses:");
 	DakotaResponsesx(d_responses,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,responses_descriptors,numresponsedescriptors,d_numresponses);
 	
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp	(revision 12878)
@@ -0,0 +1,23 @@
+/*!\file Delta18oParameterizationx
+ * \brief: Create past temperature field from present day fields
+ */
+
+#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){
+
+  /*Intermediary*/
+  int    i;
+  Element* element = NULL;
+ 
+  /*Compute temperature and precipitation fields: */
+  for(i=0;i<elements->Size();i++){
+    element=(Element*)elements->GetObjectByOffset(i);
+    element->Delta18oParameterization();
+  }  
+}
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.h	(revision 12878)
@@ -0,0 +1,14 @@
+/*!\file:  Delta18oParameterizationx.cpp
+ * \brief header file for 
+ */ 
+
+#ifndef _DELTA18OPARAMETERIZATIONX_H
+#define _DELTA18OPARAMETERIZATIONX_H
+
+#include "../../Container/Container.h"
+#include "../../classes/objects/objects.h"
+
+/* local prototypes: */
+void Delta18oParameterizationx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters);
+
+#endif  /* _DELTA18OPARAMETERIZATIONX_H*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp	(revision 12878)
@@ -36,5 +36,5 @@
 	maxels=width-1;
 	/*Allocate connectivity: */
-	elementconnectivity=(double*)xcalloc(nel*3,sizeof(double));
+	elementconnectivity=xNewZeroInit<double>(nel*3);
 
 	/*Go through all elements, and for each element, go through its nodes, to get the neighbouring elements. 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.cpp	(revision 12878)
@@ -39,5 +39,5 @@
 	#ifdef _HAVE_MPI_
 	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
-	if(!sumfound)_error_("%s%i%s","could not find material with id",index," to compute ElementResponse");
+	if(!sumfound)_error2_("could not find material with id" << index << " to compute ElementResponse");
 	#endif
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ElementResponsex/ElementResponsex.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/EnumToStringx/EnumToStringx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/EnumToStringx/EnumToStringx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/EnumToStringx/EnumToStringx.cpp	(revision 12878)
@@ -8,4 +8,5 @@
 */
 
+#include <cstring>
 #include "../../shared/shared.h"
 #include "../../include/include.h"
@@ -109,4 +110,5 @@
 		case MaterialsRhoIceEnum : return "MaterialsRhoIce";
 		case MaterialsRhoWaterEnum : return "MaterialsRhoWater";
+		case MaterialsRhoFreshwaterEnum : return "MaterialsRhoFreshwater";
 		case MaterialsMuWaterEnum : return "MaterialsMuWater";
 		case MaterialsThermalExchangeVelocityEnum : return "MaterialsThermalExchangeVelocity";
@@ -154,8 +156,14 @@
 		case SettingsResultsAsPatchesEnum : return "SettingsResultsAsPatches";
 		case SettingsWaitonlockEnum : return "SettingsWaitonlock";
-		case DebugPetscProfilingEnum : return "DebugPetscProfiling";
-		case PetscProfilingCurrentMemEnum : return "PetscProfilingCurrentMem";
-		case PetscProfilingCurrentFlopsEnum : return "PetscProfilingCurrentFlops";
-		case PetscProfilingSolutionTimeEnum : return "PetscProfilingSolutionTime";
+		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";
@@ -166,4 +174,14 @@
 		case SurfaceforcingsPrecipitationEnum : return "SurfaceforcingsPrecipitation";
 		case SurfaceforcingsMassBalanceEnum : return "SurfaceforcingsMassBalance";
+		case SurfaceforcingsIspddEnum : return "SurfaceforcingsIspdd";
+		case SurfaceforcingsIssmbgradientsEnum : return "SurfaceforcingsIssmbgradients";
+		case SurfaceforcingsMonthlytemperaturesEnum : return "SurfaceforcingsMonthlytemperatures";
+		case SurfaceforcingsHcEnum : return "SurfaceforcingsHc";
+		case SurfaceforcingsSmbPosMaxEnum : return "SurfaceforcingsSmbPosMax";
+		case SurfaceforcingsSmbPosMinEnum : return "SurfaceforcingsSmbPosMin";
+		case SurfaceforcingsAPosEnum : return "SurfaceforcingsAPos";
+		case SurfaceforcingsBPosEnum : return "SurfaceforcingsBPos";
+		case SurfaceforcingsANegEnum : return "SurfaceforcingsANeg";
+		case SurfaceforcingsBNegEnum : return "SurfaceforcingsBNeg";
 		case ThermalMaxiterEnum : return "ThermalMaxiter";
 		case ThermalPenaltyFactorEnum : return "ThermalPenaltyFactor";
@@ -257,4 +275,5 @@
 		case IntParamEnum : return "IntParam";
 		case IntVecParamEnum : return "IntVecParam";
+		case TransientParamEnum : return "TransientParam";
 		case MacAyeal2dIceFrontEnum : return "MacAyeal2dIceFront";
 		case MacAyeal3dIceFrontEnum : return "MacAyeal3dIceFront";
@@ -376,4 +395,5 @@
 		case StressTensorzzEnum : return "StressTensorzz";
 		case IceVolumeEnum : return "IceVolume";
+		case TotalSmbEnum : return "TotalSmb";
 		case P0Enum : return "P0";
 		case P1Enum : return "P1";
@@ -464,5 +484,5 @@
 
 	len=strlen(EnumToStringx(enum_in));
-	string=(char*)xmalloc((len+1)*sizeof(char));
+	string=xNew<char>(len+1);
 	memcpy(string,EnumToStringx(enum_in),(len+1)*sizeof(char));
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 12878)
@@ -11,29 +11,22 @@
 #include "../modules.h"
 
-int Exp2Kmlx(char* filexp,char* filkml,
-			 int sgn,
-			 bool holes){
+int Exp2Kmlx(char* filexp,char* filkml,int sgn,bool holes){
 
 	double  cm,sp;
 
 	Xy2lldef(&cm,&sp,sgn);
-
-	return(Exp2Kmlx(filexp,filkml,
-					sgn,cm,sp,
-					holes));
+	return(Exp2Kmlx(filexp,filkml,sgn,cm,sp,holes));
 }
 
-int Exp2Kmlx(char* filexp,char* filkml,
-			 int sgn,double cm,double sp,
-			 bool holes){
-
-	int     i,j,iret=0;
-	int     lwidth=1;
-	double  popac=0.50;
-	int     nprof;
-	int     *pnvert=NULL;
-	double  **pprofx=NULL,**pprofy=NULL;
-	bool    *closed=NULL;
-	double  *lat=NULL,*lon=NULL;
+int Exp2Kmlx(char* filexp,char* filkml,int sgn,double cm,double sp,bool holes){
+
+	int      i        ,j,iret=0;
+	int      lwidth = 1;
+	double   popac  = 0.50;
+	int      nprof;
+	int     *pnvert = NULL;
+	double **pprofx = NULL,**pprofy=NULL;
+	bool    *closed = NULL;
+	double  *lat    = NULL, *lon=NULL;
 
 	char    indent[81]="";
@@ -57,13 +50,13 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_printf_(true,"\nExp2Kmlx Module -- %s",ctime(&time0));
-
-/*  read exp file  */
+	_pprintString_("\nExp2Kmlx Module -- " << ctime(&time0));
+
+	/*read exp file  */
 
 	if (!DomainOutlineRead(&nprof,&pnvert,&pprofx,&pprofy,&closed,filexp))
-		_error_("Error reading exp file.");
-	_printf_(true,"Exp2Kmlx -- Reading %d exp profiles from file \"%s\".\n",nprof,filexp);
+		_error2_("Error reading exp file.");
+	_pprintLine_("Exp2Kmlx -- Reading " << nprof << " exp profiles from file \"" << filexp << "\".");
 //	for (i=0; i<nprof; i++)
-//		printf("i=%d; nvert=%d, closed=%d\n",i,pnvert[i],closed[i]);
+//		_printLine_("i=" << i << "; nvert=" << pnvert[i] << ", closed=" << closed[i]);
 
 /*  construct kml file  */
@@ -128,5 +121,5 @@
 
 	if (holes && nprof && (pnvert[0] <= 1 || pprofx[0][pnvert[0]-1] != pprofx[0][0] || pprofy[0][pnvert[0]-1] != pprofy[0][0])) {
-		_printf_(true,"Warning -- Outer profile is not closed, so \"holes\" option will be ignored.\n");
+		_pprintLine_("Warning -- Outer profile is not closed, so \"holes\" option will be ignored.");
 		holes=false;
 	}
@@ -143,15 +136,15 @@
 
 		kring->ncoord    =pnvert[i]-1;
-		lat=(double *) xmalloc(kring->ncoord*sizeof(double));
-		lon=(double *) xmalloc(kring->ncoord*sizeof(double));
+		lat=xNew<double>(kring->ncoord);
+		lon=xNew<double>(kring->ncoord);
 		Xy2llx(lat,lon,pprofx[i],pprofy[i],kring->ncoord,sgn,cm,sp);
-		kring->coords    =(double (*)[3]) xmalloc(kring->ncoord*3*sizeof(double));
+		kring->coords=xNew<double>(kring->ncoord*3);
 		for (j=0; j<kring->ncoord; j++) {
-			kring->coords[j][0]=lon[j];
-			kring->coords[j][1]=lat[j];
-			kring->coords[j][2]=0.;
+			kring->coords[3*j+0]=lon[j];
+			kring->coords[3*j+1]=lat[j];
+			kring->coords[3*j+2]=0.;
 		}
-		xfree((void**)&lon);
-		xfree((void**)&lat);
+		xDelete<double>(lon);
+		xDelete<double>(lat);
 
 		(kpoly ->outer     )->AddObject((Object*)kring);
@@ -160,5 +153,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]) {
-				_printf_(true,"Warning -- Inner profile %d is not closed with \"holes\" specified, so it will be ignored.\n",i+1);
+				_pprintLine_("Warning -- Inner profile " << i+1 << " is not closed with \"holes\" specified, so it will be ignored.");
 				continue;
 			}
@@ -167,15 +160,15 @@
 
 			kring->ncoord    =pnvert[i]-1;
-			lat=(double *) xmalloc(kring->ncoord*sizeof(double));
-			lon=(double *) xmalloc(kring->ncoord*sizeof(double));
+			lat=xNew<double>(kring->ncoord);
+			lon=xNew<double>(kring->ncoord);
 			Xy2llx(lat,lon,pprofx[i],pprofy[i],kring->ncoord,sgn,cm,sp);
-			kring->coords    =(double (*)[3]) xmalloc(kring->ncoord*3*sizeof(double));
+			kring->coords    =xNew<double>(kring->ncoord*3);
 			for (j=0; j<kring->ncoord; j++) {
-				kring->coords[j][0]=lon[j];
-				kring->coords[j][1]=lat[j];
-				kring->coords[j][2]=0.;
-			}
-			xfree((void**)&lon);
-			xfree((void**)&lat);
+				kring->coords[3*j+0]=lon[j];
+				kring->coords[3*j+1]=lat[j];
+				kring->coords[3*j+2]=0.;
+			}
+			xDelete<double>(lon);
+			xDelete<double>(lat);
 
 			(kpoly ->inner     )->AddObject((Object*)kring);
@@ -204,15 +197,15 @@
 
 				kring->ncoord    =pnvert[i]-1;
-				lat=(double *) xmalloc(kring->ncoord*sizeof(double));
-				lon=(double *) xmalloc(kring->ncoord*sizeof(double));
+				lat=xNew<double>(kring->ncoord);
+				lon=xNew<double>(kring->ncoord);
 				Xy2llx(lat,lon,pprofx[i],pprofy[i],kring->ncoord,sgn,cm,sp);
-				kring->coords    =(double (*)[3]) xmalloc(kring->ncoord*3*sizeof(double));
+				kring->coords    =xNew<double>(kring->ncoord*3);
 				for (j=0; j<kring->ncoord; j++) {
-					kring->coords[j][0]=lon[j];
-					kring->coords[j][1]=lat[j];
-					kring->coords[j][2]=0.;
+					kring->coords[3*j+0]=lon[j];
+					kring->coords[3*j+1]=lat[j];
+					kring->coords[3*j+2]=0.;
 				}
-				xfree((void**)&lon);
-				xfree((void**)&lat);
+				xDelete<double>(lon);
+				xDelete<double>(lat);
 
 				(kpoly ->outer     )->AddObject((Object*)kring);
@@ -231,15 +224,15 @@
 
 				kline->ncoord    =pnvert[i];
-				lat=(double *) xmalloc(kline->ncoord*sizeof(double));
-				lon=(double *) xmalloc(kline->ncoord*sizeof(double));
+				lat=xNew<double>(kline->ncoord);
+				lon=xNew<double>(kline->ncoord);
 				Xy2llx(lat,lon,pprofx[i],pprofy[i],kline->ncoord,sgn,cm,sp);
-				kline->coords    =(double (*)[3]) xmalloc(kline->ncoord*3*sizeof(double));
+				kline->coords    =xNew<double>(kline->ncoord*3);
 				for (j=0; j<kline->ncoord; j++) {
-					kline->coords[j][0]=lon[j];
-					kline->coords[j][1]=lat[j];
-					kline->coords[j][2]=0.;
+					kline->coords[3*j+0]=lon[j];
+					kline->coords[3*j+1]=lat[j];
+					kline->coords[3*j+2]=0.;
 				}
-				xfree((void**)&lon);
-				xfree((void**)&lat);
+				xDelete<double>(lon);
+				xDelete<double>(lat);
 
 				(kplace->geometry  )->AddObject((Object*)kline);
@@ -251,15 +244,16 @@
 				kplace->visibility=true;
 				sprintf(kplace->styleurl  ,"#RandomLineEmptyPoly");
+				int one=1;
 
 				kpoint=new KML_Point();
 
-				lat=(double *) xmalloc(sizeof(double));
-				lon=(double *) xmalloc(sizeof(double));
+				lat=xNew<double>(one);
+				lon=xNew<double>(one);
 				Xy2llx(lat,lon,pprofx[i],pprofy[i],1,sgn,cm,sp);
 				kpoint->coords[0]=lon[0];
 				kpoint->coords[1]=lat[0];
 				kpoint->coords[2]=0.;
-				xfree((void**)&lon);
-				xfree((void**)&lat);
+				xDelete<double>(lon);
+				xDelete<double>(lat);
 
 				(kplace->geometry  )->AddObject((Object*)kpoint);
@@ -281,5 +275,5 @@
 /*  write kml file  */
 
-	_printf_(true,"Exp2Kmlx -- Writing kml document to file \"%s\".\n",filkml);
+	_pprintLine_("Exp2Kmlx -- Writing kml document to file \"" << filkml << "\".");
 	fid=fopen(filkml,"w");
 	fprintf(fid,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
@@ -289,8 +283,8 @@
 	delete kfile;
 	for (i=nprof-1; i>=0; i--) {
-		xfree((void**)&(pprofy[i]));
-		xfree((void**)&(pprofx[i]));
-	}
-	xfree((void**)&pnvert);
+		xDelete<double>(pprofy[i]);
+		xDelete<double>(pprofx[i]);
+	}
+	xDelete<int>(pnvert);
 
 	clock1=clock();
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Exp2Kmlx/Exp2Kmlx.h	(revision 12878)
@@ -8,5 +8,5 @@
 #include <float.h>    /*  DBL_MAX  */
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 12878)
@@ -26,5 +26,5 @@
 	/*Get size of vector: */
 	gsize=nodes->NumberOfDofs(configuration_type,GsetEnum);
-	if (gsize==0) _error_("Allocating a Vec of size 0 as gsize=0 for configuration: %s",EnumToStringx(configuration_type));
+	if (gsize==0) _error2_("Allocating a Vec of size 0 as gsize=0 for configuration: " << EnumToStringx(configuration_type));
 	
 	/*Initialize solution: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _GETSOLUTIONFROMINPUTSXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 12878)
@@ -32,5 +32,5 @@
 
 	/*Assign output pointers:*/
-	xfree((void**)&control_type);
+	xDelete<int>(control_type);
 	*pvector=vector;
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 12878)
@@ -5,5 +5,5 @@
 #define _GETVECTORFROMCONTROLINPUTSXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 12878)
@@ -32,5 +32,5 @@
 	}
 	else{
-		_error_("%s%s%s"," vector type: ",EnumToStringx(type)," not supported yet!");
+		_error2_("vector type: " << EnumToStringx(type) << " not supported yet!");
 	}
 
@@ -41,8 +41,8 @@
 }
 
-void GetVectorFromInputsx( double** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name, int type){
+void GetVectorFromInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name, int type){
 	
 	/*output: */
-	double* vector=NULL;
+	IssmDouble* vector=NULL;
 	
 	/*intermediary: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 12878)
@@ -5,10 +5,10 @@
 #define _GETVECTORFROMINPUTSXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 /* local prototypes: */
 void	GetVectorFromInputsx( Vector** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name,int type);
-void	GetVectorFromInputsx( double** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name,int type);
+void	GetVectorFromInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name,int type);
 
 #endif  /* _GETVECTORFROMINPUTSXX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.cpp	(revision 12878)
@@ -14,9 +14,9 @@
 	int     i,j,numberofvertices;
 	int     num_controls;
-	double  norm_inf;
-	double *norm_list       = NULL;
-	int    *control_type    = NULL;
-	Vector*     gradient        = NULL;
-	Vector*    *gradient_list   = NULL;
+	double   norm_inf;
+	double  *norm_list     = NULL;
+	int     *control_type  = NULL;
+	Vector  *gradient      = NULL;
+	Vector **gradient_list = NULL;
 	
 	/*retrieve some parameters: */
@@ -26,6 +26,6 @@
 
 	/*Allocate gradient_list */
-	gradient_list = (Vector**)xmalloc(num_controls*sizeof(Vector*));
-	norm_list = (double*)xmalloc(num_controls*sizeof(double));
+	gradient_list = xNew<Vector*>(num_controls);
+	norm_list = xNew<double>(num_controls);
 	for(i=0;i<num_controls;i++){
 		gradient_list[i]=new Vector(num_controls*numberofvertices);
@@ -54,6 +54,6 @@
 	/*Check that gradient is clean*/
 	norm_inf=gradient->Norm(NORM_INF);
-	if(norm_inf<=0)    _error_("||∂J/∂α||∞ = 0    gradient norm is zero");
-	if(isnan(norm_inf))_error_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
+	if(norm_inf<=0)    _error2_("||∂J/∂α||∞ = 0    gradient norm is zero");
+	if(xIsNan<IssmDouble>(norm_inf))_error2_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
 
 	/*Clean-up and assign output pointer*/
@@ -62,8 +62,8 @@
 	}
 	else{
-		xfree((void**)&norm_list);
+		xDelete<double>(norm_list);
 	}
 	if(pgradient)  *pgradient=gradient;
-	xfree((void**)&gradient_list);
-	xfree((void**)&control_type);
+	xDelete<Vector*>(gradient_list);
+	xDelete<int>(control_type);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Gradjx/Gradjx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 12878)
@@ -20,5 +20,5 @@
 	Element* element                          = NULL;
 	
-	_printf_(VerboseModule(),"   Migrating grounding line\n");
+	if(VerboseModule()) _pprintLine_("   Migrating grounding line");
 	
 	/*retrieve parameters: */
@@ -27,5 +27,5 @@
 
 	if(migration_style==NoneEnum) return;
-	if(migration_style!=AgressiveMigrationEnum && migration_style!=SoftMigrationEnum) _error_("%s not supported yet!",EnumToStringx(migration_style));
+	if(migration_style!=AgressiveMigrationEnum && migration_style!=SoftMigrationEnum) _error2_(EnumToStringx(migration_style) << " not supported yet!");
 
 	if(migration_style==SoftMigrationEnum){
@@ -49,10 +49,10 @@
 	/*free ressouces: */
 	xdelete(&vec_old_floatingice);
-	xfree((void**)&vertices_potentially_ungrounding);
-	xfree((void**)&vertices_ungrounding);
-	xfree((void**)&old_floatingice);
+	xDelete<double>(vertices_potentially_ungrounding);
+	xDelete<double>(vertices_ungrounding);
+	xDelete<double>(old_floatingice);
 }
 
-/*FUNCTION CreateNodesOnFloatingIce {{{1*/
+/*FUNCTION CreateNodesOnFloatingIce {{{*/
 Vector* CreateNodesOnFloatingIce(Nodes* nodes,int configuration_type){ 
 
@@ -81,5 +81,5 @@
 }
 /*%}}}*/
-/*FUNCTION PotentialSheetUngrounding {{{1*/
+/*FUNCTION PotentialSheetUngrounding {{{*/
 double*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters){ 
 
@@ -108,5 +108,5 @@
 }
 /*}}}*/
-/*FUNCTION PropagateFloatingiceToGroundedNeighbors {{{1*/
+/*FUNCTION PropagateFloatingiceToGroundedNeighbors {{{*/
 double*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,double* vertices_potentially_ungrounding){ 
 
@@ -158,5 +158,5 @@
 		#ifdef _HAVE_MPI_
 		MPI_Allreduce(&local_nflipped,&nflipped,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
-		_printf_(VerboseConvergence(),"   Additional number of vertices allowed to unground: %i\n",nflipped);
+		if(VerboseConvergence()) _pprintLine_("   Additional number of vertices allowed to unground: " << nflipped);
 		#else
 		nflipped=local_nflipped;
@@ -164,6 +164,6 @@
 
 		/*Avoid leaks: */
-		xfree((void**)&elements_neighboring_floatingce);
-		xfree((void**)&nodes_on_floatingice);
+		xDelete<double>(elements_neighboring_floatingce);
+		xDelete<double>(nodes_on_floatingice);
 
 		/*Assemble and serialize:*/
@@ -174,5 +174,5 @@
 	/*Free ressources:*/
 	xdelete(&vec_nodes_on_floatingice);
-	xfree((void**)&elements_neighboring_floatingce);
+	xDelete<double>(elements_neighboring_floatingce);
 
 	return nodes_on_floatingice;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/HoleFillerx/HoleFillerx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/HoleFillerx/HoleFillerx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/HoleFillerx/HoleFillerx.cpp	(revision 12878)
@@ -43,5 +43,5 @@
 
 	 /*^^^^^^^^^^^^^  Remove pixels close to the holes ^^^^^^^^^^^^^*/
-	image2 = (double*) xmalloc( lines*samps*sizeof(double));
+	image2 = xNew<double>(lines*samps);
 	memcpy(image2,image,lines*samps*sizeof(double));
 	
@@ -64,5 +64,5 @@
 	}
 
-	image3 = (double*) xmalloc( lines*samps*sizeof(double));
+	image3 = xNew<double>(lines*samps);
 	memcpy(image3,image2,lines*samps*sizeof(double));
 
@@ -76,6 +76,6 @@
 			}
 		}
-		printf( "\n" );
-		printf("Number of zeroes remaining: %10ld",lines*samps-counter);
+		_printLine_( "" );
+		_printString_("Number of zeroes remaining: " << lines*samps-counter);
 		fflush( stdout );
 	#endif
@@ -95,6 +95,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        
-		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: %10ld",lines*samps-counter);
+		_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);
 		fflush( stdout );
 	#endif
@@ -104,5 +104,5 @@
 /***************** FIRST RUN *********************/
 /*
-fprintf ( stdout, "First  Application:  " ); time(&t2); printf( ctime(&t2) );
+fprintf ( stdout, "First  Application:  " ); time(&t2); _printString_( ctime(&t2) );
 */
 	for ( i = 0; i < lines; i++ ){
@@ -277,5 +277,5 @@
 			
 			#ifdef _DEBUG2_
-				//printf("%g %g %g \n",temp,elev,range);
+				//_printLine_(temp << " " << elev << " " << range << " ");
 			#endif
 
@@ -304,5 +304,5 @@
 /************************ SMOOTH THE RESULT ***********************/		
 		
-	image4 = (double*) xmalloc( lines*samps*sizeof(double));
+	image4 = xNew<double>(lines*samps);
 	memcpy(image4,image3,lines*samps*sizeof(double));
 
@@ -348,5 +348,5 @@
 
 	/*Allocate output image: */
-	imageout=(double*)xmalloc(samps*lines*sizeof(double));
+	imageout=xNew<double>(samps*lines);
 	memcpy(imageout,image3,lines*samps*sizeof(double));
 
@@ -354,6 +354,6 @@
 	
 	#ifdef _DEBUG2_
-		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");
+		_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 ( "\n");
 	#endif
@@ -363,6 +363,4 @@
 	/*Assign output pointers: */
 	*pimageout=imageout;
-
 	return 1;
-	
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/IceVolumex/IceVolumex.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp	(revision 12878)
@@ -9,5 +9,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void InputArtificialNoisex( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int enum_name,double min,double max){
+void InputArtificialNoisex( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int enum_name,IssmDouble min,IssmDouble max){
 
 	int i;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.h	(revision 12878)
@@ -6,9 +6,9 @@
 #define _INPUTARTIFICIALNOISEX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 /* local prototypes: */
-void	InputArtificialNoisex( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int enum_name,double min,double max);
+void	InputArtificialNoisex( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int enum_name,IssmDouble min,IssmDouble max);
 
 #endif  /* _UPDATEINPUTSFROMVECTORXX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputConvergencex/InputConvergencex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputConvergencex/InputConvergencex.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputConvergencex/InputConvergencex.cpp	(revision 12878)
@@ -9,16 +9,16 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-bool InputConvergencex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int* enums, int num_enums, int* criterionenums, double* criterionvalues,int num_criterionenums){
+bool InputConvergencex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int* enums, int num_enums, int* criterionenums, IssmDouble* criterionvalues,int num_criterionenums){
 
 	/*intermediary:*/
-	int         i;
-	bool        converged;
-	int         num_notconverged=0;
-	int         total_notconverged;
-	double     *eps       = NULL;
-	Element*    element=NULL;
+	int      i;
+	bool     converged;
+	int      num_notconverged   = 0;
+	int      total_notconverged;
+	IssmDouble  *eps                = NULL;
+	Element *element            = NULL;
 
 	/*allocate dynamic memory: */
-	eps=(double*)xmalloc(num_criterionenums*sizeof(double));
+	eps=xNew<IssmDouble>(num_criterionenums);
 
 	/*Go through elements, and ask them to do the job: */
@@ -34,8 +34,8 @@
 	num_notconverged=total_notconverged;
 	#endif
-	_printf_(VerboseConvergence(),"      #elements above convergence criterion = %i\n",num_notconverged);
+	if(VerboseConvergence()) _pprintLine_("      #elements above convergence criterion = " << num_notconverged);
 
 	/*Free ressources:*/
-	xfree((void**)&eps);
+	xDelete<IssmDouble>(eps);
 
 	/*return: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputConvergencex/InputConvergencex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputConvergencex/InputConvergencex.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputConvergencex/InputConvergencex.h	(revision 12878)
@@ -8,5 +8,5 @@
 
 /* local prototypes: */
-bool InputConvergencex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int* enums, int num_enums, int* criterionenums, double* criterionvalues,int num_criterionenums);
+bool InputConvergencex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int* enums, int num_enums, int* criterionenums, IssmDouble* criterionvalues,int num_criterionenums);
 
 #endif  /* _INPUTCONVERGENCEX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputScalex/InputScalex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputScalex/InputScalex.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputScalex/InputScalex.cpp	(revision 12878)
@@ -9,5 +9,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void InputScalex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type, double scale_factor){
+void InputScalex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type, IssmDouble scale_factor){
 
 	/*intermediary:*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputScalex/InputScalex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputScalex/InputScalex.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputScalex/InputScalex.h	(revision 12878)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void InputScalex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type, double scale_factor);
+void InputScalex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type, IssmDouble scale_factor);
 
 #endif  /* _SCALEINPUTX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputToResultx/InputToResultx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputToResultx/InputToResultx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputToResultx/InputToResultx.cpp	(revision 12878)
@@ -13,5 +13,5 @@
 	/*intermediary:*/
 	int      step;
-	double   time;
+	IssmDouble   time;
 	Element *element = NULL;
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 12878)
@@ -49,5 +49,5 @@
 	}
 }
-void InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double constant, int name){
+void InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble constant, int name){
 
 	int i;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _UPDATEINPUTSFROMCONSTANTXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
@@ -12,5 +12,5 @@
 void		InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters, bool   constant, int name);
 void		InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters, int    constant, int name);
-void		InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters, double constant, int name);
+void		InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters, IssmDouble constant, int name);
 
 #endif  /* _UPDATEINPUTSFROMCONSTANTXX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 12878)
@@ -21,7 +21,7 @@
 	double *qmu_part  = NULL;
 
-	double* distributed_values=NULL;
-	double* parameter=NULL;
-	char*   descriptor=NULL;
+	double *distributed_values = NULL;
+	double *parameter          = NULL;
+	char   *descriptor         = NULL;
 	char    root[50]; //root name of variable, ex: DragCoefficent, RhoIce, etc ...
 
@@ -49,5 +49,5 @@
 
 
-			distributed_values=(double*)xmalloc(npart*sizeof(double));
+			distributed_values=xNew<double>(npart);
 			for(j=0;j<npart;j++){
 				distributed_values[j]=variables[i+j];
@@ -91,12 +91,12 @@
 
 			/*Free allocations: */
-			xfree((void**)&parameter);
-			xfree((void**)&distributed_values);
+			xDelete<double>(parameter);
+			xDelete<double>(distributed_values);
 		}
 		else if (strncmp(descriptor,"indexed_",8)==0){
-			_error_(" indexed variables not supported yet!");
+			_error2_("indexed variables not supported yet!");
 		}
 		else if (strncmp(descriptor,"nodal_",8)==0){
-			_error_(" nodal variables not supported yet!");
+			_error2_("nodal variables not supported yet!");
 		}
 		else{
@@ -107,5 +107,4 @@
 
 	/*Free ressources:*/
-	xfree((void**)&qmu_part);
-
+	xDelete<double>(qmu_part);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _INPUTUPDATEFROMDAKOTAXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _UPDATEINPUTSFROMMATRIXDAKOTAXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 12878)
@@ -11,5 +11,5 @@
 void InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector* solution){
 
-	double* serial_solution=NULL;
+	IssmDouble* serial_solution=NULL;
 
 	/*Serialize solution, so that elements can index into it on every CPU: */
@@ -20,10 +20,9 @@
 
 	/*Free ressources:*/
-	xfree((void**)&serial_solution);
-
+	xDelete<IssmDouble>(serial_solution);
 }
 
 
-void InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* solution){
+void InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* solution){
 
 	/*Intermediary*/
@@ -36,4 +35,3 @@
 		element->InputUpdateFromSolution(solution);
 	}
-
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 12878)
@@ -6,14 +6,14 @@
 #define _UPDATEINPUTSFROMSOLUTIONXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 /* local prototypes: */
 void		InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector* solution);
-void        InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* solution);
+void        InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* solution);
 
 //with timestep
 void		InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector* solution,int timestep);
-void        InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* solution, int timestep);
+void        InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* solution, int timestep);
 
 #endif  /* _UPDATEINPUTSFROMSOLUTIONXX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 12878)
@@ -18,5 +18,5 @@
 
 	/*Free ressources:*/
-	xfree((void**)&serial_vector);
+	xDelete<double>(serial_vector);
 }
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _UPDATEINPUTSFROMVECTORDAKOTAXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 12878)
@@ -11,5 +11,5 @@
 void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector* vector, int name, int type){
 
-	double* serial_vector=NULL;
+	IssmDouble* serial_vector=NULL;
 
 	serial_vector=vector->ToMPISerial();
@@ -18,9 +18,9 @@
 
 	/*Free ressources:*/
-	xfree((void**)&serial_vector);
+	xDelete<IssmDouble>(serial_vector);
 }
 
 	
-void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vector, int name, int type){
+void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* vector, int name, int type){
 
 	int i;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 12878)
@@ -6,10 +6,10 @@
 #define _UPDATEINPUTSFROMVECTORXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 /* local prototypes: */
 void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector* vector, int name,int type);
-void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,double* vector, int name,int type);
+void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,IssmDouble* vector, int name,int type);
 void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int* vector, int name,int type);
 void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,bool* vector, int name,int type);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 12878)
@@ -13,4 +13,5 @@
 #include "../../shared/shared.h"
 #include "../../include/include.h"
+#include "../../io/io.h"
 /*}}}*/
 
@@ -36,11 +37,11 @@
 	/*Some checks on arguments: */
 	if ((M<2) || (N<2) || (nods<=0)){
-		_error_("nothing to be done according to the dimensions of input matrices and vectors.");
+		_error2_("nothing to be done according to the dimensions of input matrices and vectors.");
 	}
 	if (x_in[1]-x_in[0]<0){
-		_error_("x coordinate vector should be increasing.\n   use Matlab's command x=flipud(x), also flip the data matrix data=fliplr(data)");
+		_error2_("x coordinate vector should be increasing.\n   use Matlab's command x=flipud(x), also flip the data matrix data=fliplr(data)");
 	}
 	if (y_in[1]-y_in[0]<0){
-		_error_("y coordinate vector should be increasing.\n   use Matlab's command y=flipud(y), also flip the data matrix data=flipud(data)");
+		_error2_("y coordinate vector should be increasing.\n   use Matlab's command y=flipud(y), also flip the data matrix data=flipud(data)");
 	}
 
@@ -52,6 +53,6 @@
 
 		/*The coordinates given in input describe the contour of each pixel. Take the center of each pixel*/
-		x=(double*)xmalloc(N*sizeof(double));
-		y=(double*)xmalloc(M*sizeof(double));
+		x=xNew<double>(N);
+		y=xNew<double>(M);
 		for (i=0;i<N;i++) x[i]=(x_in[i]+x_in[i+1])/2;
 		for (i=0;i<M;i++) y[i]=(y_in[i]+y_in[i+1])/2;
@@ -62,11 +63,11 @@
 
 		/*The coordinates given in input describe the center each pixel. Keep them*/
-		x=(double*)xmalloc(N*sizeof(double));
-		y=(double*)xmalloc(M*sizeof(double));
+		x=xNew<double>(N);
+		y=xNew<double>(M);
 		for (i=0;i<N;i++) x[i]=x_in[i];
 		for (i=0;i<M;i++) y[i]=y_in[i];
 	}
 	else{
-		_error_("x and y vectors length should be 1 or 0 more than data number of rows.");
+		_error2_("x and y vectors length should be 1 or 0 more than data number of rows.");
 	}
 
@@ -81,10 +82,12 @@
 	gate.data_mesh=data_mesh;
 	gate.data=data;
+	gate.default_value=default_value;
+	gate.interp=interpenum;
 	gate.M=M;
 	gate.N=N;
-	gate.interp=interpenum;
 
 	/*launch the thread manager with InterpFromGridToMeshxt as a core: */
 	LaunchThread(InterpFromGridToMeshxt,(void*)&gate,num);
+	_printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
 
 	/*Assign output pointers:*/
@@ -92,5 +95,5 @@
 }
 /*}}}*/
-/*InterpFromGridToMeshxt {{{1*/
+/*InterpFromGridToMeshxt {{{*/
 void* InterpFromGridToMeshxt(void* vpthread_handle){
 
@@ -124,5 +127,5 @@
 	double *y             = gate->y;
 	int     nods          = gate->nods;
-	Vector*     data_mesh     = gate->data_mesh;
+	Vector *data_mesh     = gate->data_mesh;
 	double *data          = gate->data;
 	double  default_value = gate->default_value;
@@ -131,8 +134,13 @@
 	int     N             = gate->N;
 
+	bool debug = M*N>1? true:false;
+	debug = true;
+
 	/*partition loop across threads: */
 	PartitionRange(&i0,&i1,nods,num_threads,my_thread);
 	for (i=i0;i<i1;i++) {
 
+		if(debug && my_thread==0)
+		 _printString_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i-i0)/double(i1-i0)*100<<"%");
 		x_grid=*(x_mesh+i);
 		y_grid=*(y_mesh+i);
@@ -170,8 +178,8 @@
 					break;
 				default:
-					printf("Interpolation %s not supported yet\n",EnumToStringx(interpenum));
+					_printLine_("Interpolation " << EnumToStringx(interpenum) << " not supported yet");
 					return NULL; /*WARNING: no error because it would blow up the multithreading!*/
 			}
-			if(isnan(data_value)) data_value=default_value;
+			if(xIsNan<IssmDouble>(data_value)) data_value=default_value;
 		}
 		else{
@@ -183,5 +191,5 @@
 }/*}}}*/
 
-/*findindices {{{1*/
+/*findindices {{{*/
 bool findindices(int* pn,int* pm,double* x,int x_rows, double* y,int y_rows, double xgrid,double ygrid){
 
@@ -218,5 +226,5 @@
 	return (foundx && foundy);
 }/*}}}*/
-/*triangleinterp{{{1*/
+/*triangleinterp{{{*/
 double triangleinterp(double x1,double x2,double y1,double y2,double Q11,double Q12,double Q21,double Q22,double x,double y){
 	/*split the rectangle in 2 triangle and
@@ -259,5 +267,5 @@
 	}
 }/*}}}*/
-/*bilinearinterp{{{1*/
+/*bilinearinterp{{{*/
 double bilinearinterp(double x1,double x2,double y1,double y2,double Q11,double Q12,double Q21,double Q22,double x,double y){
 	/*Bilinear  interpolation: (http://en.wikipedia.org/wiki/Bilinear_interpolation) */
@@ -286,5 +294,5 @@
 }
 /*}}}*/
-/*nearestinterp{{{1*/
+/*nearestinterp{{{*/
 double nearestinterp(double x1,double x2,double y1,double y2,double Q11,double Q12,double Q21,double Q22,double x,double y){
 	/*Nearest neighbor interpolation*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _INTERPFROMGRIDTOMESHX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../toolkits/toolkits.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 12878)
@@ -7,10 +7,9 @@
 #include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../modules.h"
 
 int InterpFromMesh2dx( Vector** 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** contours,int numcontours){
-
 	
 	/*Output*/
@@ -41,5 +40,5 @@
 	/*some checks*/
 	if (nels_data<1 || nods_data<3 || nods_prime==0){
-		_error_("nothing to be done according to the mesh given in input");
+		_error2_("nothing to be done according to the mesh given in input");
 	}
 
@@ -55,9 +54,9 @@
 	}
 	else{
-		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
+		_error2_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
 	}
 
 	if((numcontours) && (interpolation_type==2)){
-		_error_(" element interpolation_type with contours not supported yet!");
+		_error2_("element interpolation_type with contours not supported yet!");
 	}
 
@@ -72,5 +71,5 @@
 
 	/*Initialize output*/
-	data_prime=new Vector(nods_prime);
+	data_prime=new Vector(nods_prime,false,SeqVecType);
 	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);
@@ -84,6 +83,6 @@
 	}
 	else{
-		 incontour=(double*)xmalloc(nods_prime*sizeof(double));
-		 for (i=0;i<nods_prime;i++) incontour[i]=1;
+		 incontour=xNew<double>(nods_prime);
+		 for (i=0;i<nods_prime;i++) incontour[i]=1.0;
 	}
 
@@ -112,5 +111,5 @@
 
 	/*Assign output pointers:*/
-	 xfree((void**)&incontour);
+	 xDelete<double>(incontour);
 	*pdata_prime=data_prime;
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _INTERPFROMMESH2DX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../toolkits/toolkits.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 12878)
@@ -8,60 +8,34 @@
 void* InterpFromMesh2dxt(void* vpthread_handle){
 
-	/*gate variables :*/
-	InterpFromMesh2dxThreadStruct* gate=NULL;
-	pthread_handle* handle=NULL;
-	int     my_thread;
-	int     num_threads;
-	
-	int interpolation_type;
-	bool debug;
-	int  nels_data;
-	double* index_data=NULL;
-	double* x_data=NULL;
-	double* y_data=NULL;
-	double* data=NULL;
-	double xmin,xmax;
-	double ymin,ymax;
-	int    nods_prime;
-	Vector*    data_prime=NULL;
-	double* x_prime=NULL;
-	double* y_prime=NULL;
-	double* default_values=NULL;
-	int     num_default_values;
-	double*    incontour=NULL;
-
 	/*intermediary: */
-	int     i0;
-	int     i1;
-	int     i,j;
-	double  area;
-	double  area_1,area_2,area_3;
+	int     i0,i1,i,j;
+	double  area,area_1,area_2,area_3;
 	double  data_value;
 
 	/*recover handle and gate: */
-	handle=(pthread_handle*)vpthread_handle;
-	gate=(InterpFromMesh2dxThreadStruct*)handle->gate;
-	my_thread=handle->id;
-	num_threads=handle->num;
+	pthread_handle                *handle      = (pthread_handle*)vpthread_handle;
+	InterpFromMesh2dxThreadStruct *gate        = (InterpFromMesh2dxThreadStruct*)handle->gate;
+	int                            my_thread   = handle->id;
+	int                            num_threads = handle->num;
 	
 	/*recover parameters :*/
-	interpolation_type=gate->interpolation_type;
-	debug=gate->debug;
-	nels_data=gate->nels_data;
-	index_data=gate->index_data;
-	x_data=gate->x_data;
-	y_data=gate->y_data;
-	data=gate->data;
-	xmin=gate->xmin;
-	xmax=gate->xmax;
-	ymin=gate->ymin;
-	ymax=gate->ymax;
-	nods_prime=gate->nods_prime;
-	data_prime=gate->data_prime;
-	x_prime=gate->x_prime;
-	y_prime=gate->y_prime;
-	default_values=gate->default_values;
-	num_default_values=gate->num_default_values;
-	incontour=gate->incontour;
+	int     interpolation_type = gate->interpolation_type;
+	bool    debug              = gate->debug;
+	int     nels_data          = gate->nels_data;
+	double *index_data         = gate->index_data;
+	double *x_data             = gate->x_data;
+	double *y_data             = gate->y_data;
+	double *data               = gate->data;
+	double  xmin               = gate->xmin;
+	double  xmax               = gate->xmax;
+	double  ymin               = gate->ymin;
+	double  ymax               = gate->ymax;
+	int     nods_prime         = gate->nods_prime;
+	Vector *data_prime         = gate->data_prime;
+	double *x_prime            = gate->x_prime;
+	double *y_prime            = gate->y_prime;
+	double *default_values     = gate->default_values;
+	int     num_default_values = gate->num_default_values;
+	double *incontour          = gate->incontour;
 
 	/*partition loop across threads: */
@@ -69,10 +43,9 @@
 
 	/*Loop over the elements*/
-	if (debug && my_thread==0) printf("      interpolation progress:   %5.2lf %%",0.0);
-
-	for (i=i0;i<i1;i++){
+	for(i=i0;i<i1;i++){
 
 		/*display current iteration*/
-		if (debug && my_thread==0 && fmod((double)i,(double)100)==0) printf("\b\b\b\b\b\b\b%5.2lf %%",(double)i/nels_data*100*num_threads);
+		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<<"%");
 
 		/*if there is no point inside the domain, go to next iteration*/
@@ -114,5 +87,5 @@
 						data_value=data[i];
 					}
-					if (isnan(data_value)){
+					if (xIsNan<IssmDouble>(data_value)){
 						if(num_default_values==1) data_value=default_values[0];
 						else data_value=default_values[j];
@@ -125,7 +98,6 @@
 		}
 	}
-	if (debug && my_thread==0) printf("\b\b\b\b\b\b\b%5.2lf %%\n",100.0);
-	
+	if(debug && my_thread==0)
+	 _printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
 	return NULL;
-
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 12878)
@@ -30,5 +30,5 @@
 	/*some checks*/
 	if (nels<1 || nods<3 || nlines<1 || ncols<1 || xposting==0 || yposting==0){
-		_error_("nothing to be done according to the mesh given in input");
+		_error2_("nothing to be done according to the mesh given in input");
 	}
 
@@ -41,11 +41,11 @@
 	}
 	else{
-		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
+		_error2_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
 	}
 
 	/*First, allocate pointers: */
-	griddata=(double*)xcalloc(nlines*ncols,sizeof(double));
-	x_grid=(double*)xcalloc(ncols,sizeof(double));
-	y_grid=(double*)xcalloc(nlines,sizeof(double));
+	griddata=xNewZeroInit<double>(nlines*ncols);
+	x_grid=xNewZeroInit<double>(ncols);
+	y_grid=xNewZeroInit<double>(nlines);
 
 	/*Set debug to 1 if there are lots of elements*/
@@ -85,9 +85,9 @@
 
 	/*Loop over the elements*/
-	if (debug) printf("      interpolation progress:   %5.2lf %%",0.0);
 	for (n=0;n<nels;n++){
 
 		/*display current iteration*/
-		if (debug && fmod((double)n,(double)100)==0) printf("\b\b\b\b\b\b\b%5.2lf %%",(double)n/nels*100);
+		if (debug && fmod((double)n,(double)100)==0)
+		 _printString_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(n)/double(nels)*100<<"%");
 
 		/*Get extrema coordinates of current elements*/
@@ -160,5 +160,5 @@
 						data_value=data_mesh[n];
 					}
-					if (isnan(data_value)) data_value=default_value;
+					if (xIsNan<IssmDouble>(data_value)) data_value=default_value;
 
 					/*insert value and go to the next point*/
@@ -168,5 +168,6 @@
 		}
 	}
-	if (debug) printf("\b\b\b\b\b\b\b%5.2lf %%\n",100.0);
+	if (debug)
+	 _printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
 
 	/*Assign output pointers:*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../modules.h"
 
@@ -13,6 +13,6 @@
 using namespace std;
 
-int InterpFromMeshToMesh2dx(double** pdata_interp,double* index_data,double* x_data,double* y_data,int nods_data,int nels_data,
-			double* data,int data_rows,int data_cols,double* x_interp,double* y_interp,int nods_interp,double* default_values,int num_default_values, DataSet* contours){
+int InterpFromMeshToMesh2dx(double** pdata_interp,int* index_data,double* x_data,double* y_data,int nods_data,int nels_data,
+			double* data,int M_data,int N_data,double* x_interp,double* y_interp,int N_interp,Options* options){
 	
 	/*Output*/
@@ -20,4 +20,7 @@
 
 	/*Intermediary*/
+	double xmin,xmax,ymin,ymax;
+	bool   isdefault;
+	double defaultvalue;
 	R2     r;
 	I2     I;
@@ -29,76 +32,85 @@
 	double data_value;
 	Icoor2 dete[3];
-	int verbose=0;
-
-	/*default values: */
-	Vector*    vec_incontour=NULL;
-	double*    incontour=NULL;
-	bool   skip_bamg=false;
 
 	/*Checks*/
-	if (data_cols<=0){
-		_error_("data provided has a negative number of columns");
+	if (M_data!=nods_data && M_data!=nels_data){
+		_error2_("data provided should have either " << nods_data << " or " << nels_data << " lines (not " << M_data << ")");
 	}
-	if (data_rows!=nods_data && data_rows!=nels_data){
-		_error_("data provided should have either %i or %i lines (not %i)",nods_data,nels_data,data_rows);
+
+	/*Get default*/
+	if(options->GetOption("default")){
+		isdefault=true;
+		options->Get(&defaultvalue,"default");
 	}
-	if((num_default_values) && (data_cols>1)){
-		_error_("data provided can only have 1 column if a default value is provided");
-	}
-	
-	/*If default values supplied, figure out which nodes are inside the contour, including the border of the contour: */
-	if(num_default_values){
-		ContourToNodesx( &vec_incontour,x_interp,y_interp,nods_interp,contours,1);
-		incontour=vec_incontour->ToMPISerial();
+	else{
+		isdefault=false;
 	}
 
 	/*Initialize output*/
-	if (verbose) printf("Initializing output vector\n");
-	data_interp=(double*)xmalloc(nods_interp*data_cols*sizeof(double));
+	data_interp=xNew<double>(N_interp*N_data);
 
-	// read background mesh 
-	if (verbose) printf("Reading mesh\n");
+	/*read background mesh*/
 	Mesh Th(index_data,x_data,y_data,nods_data,nels_data); 
+
+	/*Get reference number (for subdomains)*/
+	long* reft = xNew<long>(Th.nbt);
+	Th.TriangleReferenceList(reft);
 	Th.CreateSingleVertexToTriangleConnectivity();
 
-	//Loop over output nodes
-	if (verbose) printf("Loop over the nodes\n");
-	for(i=0;i<nods_interp;i++){
-		
-		/*reset skip_bamg: */
-		skip_bamg=false;
+	/*Get domain boundaries*/
+	xmin=x_data[0]; ymin=y_data[0];
+	xmax=x_data[0]; ymax=y_data[0];
+	for(i=1;i<nods_data;i++){
+		if(x_data[i]<xmin) xmin=x_data[i];
+		if(x_data[i]>xmax) xmax=x_data[i];
+		if(y_data[i]<ymin) ymin=y_data[i];
+		if(y_data[i]>ymax) ymax=y_data[i];
+	}
 
-		/*figure out if we should skip bamg logic: */
-		if(num_default_values){
-			if(!incontour[i]){
-				/*This node is not inside the contour. Skip Bamg logic and apply default value.: */
-				skip_bamg=true;
+	/*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(isdefault){
+			if(x_interp[i]<xmin || x_interp[i]>xmax || y_interp[i]<ymin || y_interp[i]>ymax){
+				for(j=0;j<N_data;j++) data_interp[i*N_data+j]=defaultvalue;
+				continue;
 			}
 		}
 
-		if(skip_bamg==false){
+		/*Get current point coordinates*/
+		r.x=x_interp[i]; r.y=y_interp[i];
+		I2 I=Th.R2ToI2(r);
 
-			//Get current point coordinates
-			r.x=x_interp[i]; r.y=y_interp[i];
-			I2 I=Th.R2ToI2(r);
+		/*Find triangle holding r/I*/
+		Triangle &tb=*Th.TriangleFindFromCoord(I,dete);
 
-			//Find triangle holding r/I
-			Triangle &tb=*Th.TriangleFindFromCoord(I,dete);
+		/*point inside convex*/
+		if (tb.det>0){ 
 
-			// internal point 
-			if (tb.det>0){ 
-				//Area coordinate
-				areacoord[0]= (double) dete[0]/tb.det;
-				areacoord[1]= (double) dete[1]/tb.det;
-				areacoord[2]= (double) dete[2]/tb.det;
-				//3 vertices of the triangle
-				i0=Th.GetId(tb[0]);
-				i1=Th.GetId(tb[1]);
-				i2=Th.GetId(tb[2]);
-				//triangle number
-				it=Th.GetId(tb);
+			/*Area coordinates*/
+			areacoord[0]= (double) dete[0]/tb.det;
+			areacoord[1]= (double) dete[1]/tb.det;
+			areacoord[2]= (double) dete[2]/tb.det;
+			/*3 vertices of the triangle*/
+			i0=Th.GetId(tb[0]);
+			i1=Th.GetId(tb[1]);
+			i2=Th.GetId(tb[2]);
+			/*triangle number*/
+			it=Th.GetId(tb);
+
+			/*Inside convex but outside mesh*/
+			if (reft[it]<0 & isdefault){
+				for(j=0;j<N_data;j++) data_interp[i*N_data+j]=defaultvalue;
+				continue;
 			}
-			//external point
-			else {
+		}
+		//external point
+		else{
+			if(isdefault){
+				for(j=0;j<N_data;j++) data_interp[i*N_data+j]=defaultvalue;
+				continue;
+			}
+			else{
 				//Get closest adjacent triangle (inside the mesh)
 				AdjacentTriangle ta=CloseBoundaryEdge(I,&tb,aa,bb).Adj();
@@ -116,30 +128,25 @@
 				it=Th.GetId(tc);
 			}
-			
-			if (data_rows==nods_data){
-				for (j=0;j<data_cols;j++){
-					data_interp[i*data_cols+j]=areacoord[0]*data[data_cols*i0+j]+areacoord[1]*data[data_cols*i1+j]+areacoord[2]*data[data_cols*i2+j];
-				}
-			}
-			else{
-				for (j=0;j<data_cols;j++){
-					if (it<0 || it>=nels_data){
-						_error_("Triangle number %i not in [0 %i], because not correctly implemented yet... interpolate on grid first",it,nels_data);
-					}
-					data_interp[i*data_cols+j]=data[data_cols*it+j];
-				}
+		}
+
+		if (M_data==nods_data){
+			for (j=0;j<N_data;j++){
+				data_interp[i*N_data+j]=areacoord[0]*data[N_data*i0+j]+areacoord[1]*data[N_data*i1+j]+areacoord[2]*data[N_data*i2+j];
 			}
 		}
 		else{
-			if(num_default_values==1) data_interp[i]=default_values[0];
-			else data_interp[i]=default_values[i];
+			for (j=0;j<N_data;j++){
+				if (it<0 || it>=nels_data){
+					_error2_("Triangle number " << it << " not in [0 " << nels_data << "], report bug to developers");
+				}
+				data_interp[i*N_data+j]=data[N_data*it+j];
+			}
 		}
 	}
+	//if(N_interp>=100) _printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
 
-	/*Assign output pointers:*/
-	if (verbose) printf("Assigning output\n");
+	/*clean-up and return*/
+	xDelete<long>(reft);
 	*pdata_interp=data_interp;
-
-	/*No error return*/
 	return 1;
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h	(revision 12878)
@@ -6,9 +6,8 @@
 #define _INTERPFROMMESHTOMESH2DX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/classes.h"
 
-/* local prototypes: */
-int InterpFromMeshToMesh2dx(double** pdata_interp,double* index_data,double* x_data,double* y_data,int nods_data,int nels_data,
-			double* data,int data_rows,int data_cols,double* x_interp,double* y_interp,int nods_interp,double* default_values,int num_default_values,DataSet* contours);
+int InterpFromMeshToMesh2dx(double** pdata_interp,int* index_data,double* x_data,double* y_data,int nods_data,int nels_data,
+			double* data,int M_data,int N_data,double* x_interp,double* y_interp,int N_interp,Options* options);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 12878)
@@ -27,5 +27,5 @@
 	/*some checks*/
 	if (nels_data<1 || nods_data<6 || nods_prime==0){
-		_error_("nothing to be done according to the mesh given in input");
+		_error2_("nothing to be done according to the mesh given in input");
 	}
 
@@ -41,5 +41,5 @@
 	}
 	else{
-		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
+		_error2_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
 	}
 
@@ -58,9 +58,9 @@
 
 	/*Loop over the elements*/
-	if (debug) printf("      interpolation progress:   %5.2lf %%",0.0);
 	for (i=0;i<nels_data;i++){
 
 		/*display current iteration*/
-		if (debug && fmod((double)i,(double)100)==0) printf("\b\b\b\b\b\b\b%5.2lf %%",(double)i/nels_data*100);
+		if (debug && fmod((double)i,(double)100)==0)
+		 _printString_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i)/double(nels_data)*100<<"%");
 
 		/*Get extrema coordinates of current elements*/
@@ -124,5 +124,5 @@
 						data_value=data[i];
 					}
-					if (isnan(data_value)) data_value=default_value;
+					if (xIsNan<IssmDouble>(data_value)) data_value=default_value;
 
 					/*insert value and go to the next point*/
@@ -132,5 +132,6 @@
 		}
 	}
-	if (debug) printf("\b\b\b\b\b\b\b%5.2lf %%\n",100.0);
+	if (debug)
+	 _printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
 
 	/*Assign output pointers:*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../toolkits/toolkits.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 int InterpFromMeshToMesh3dx( Vector** 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);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 12878)
@@ -22,6 +22,6 @@
 	int     counter;
 	int     nods;
-	double* times=NULL;
-	double* values=NULL;
+	IssmDouble* times=NULL;
+	IssmDouble* values=NULL;
 	bool    spcpresent=false;
 	int     count=0;
@@ -29,5 +29,5 @@
 
 	/*variables being fetched: */
-	double *doublevector  = NULL;
+	IssmDouble *IssmDoublevector  = NULL;
 	int     M,N;
 
@@ -38,9 +38,9 @@
 	fid=iomodel->SetFilePointerToData(&code, &vector_layout,vector_enum);
 
-	if(code!=7)_error_("%s%s"," expecting a double vector for constraints with enum ",EnumToStringx(vector_enum));
-	if(vector_layout!=1)_error_("%s%s"," expecting a nodal vector for constraints with enum ",EnumToStringx(vector_enum));
+	if(code!=7)_error2_("expecting a IssmDouble vector for constraints with enum " << EnumToStringx(vector_enum));
+	if(vector_layout!=1)_error2_("expecting a nodal vector for constraints with enum " << EnumToStringx(vector_enum));
 
 	/*Fetch vector:*/
-	iomodel->FetchData(&doublevector,&M,&N,vector_enum);
+	iomodel->FetchData(&IssmDoublevector,&M,&N,vector_enum);
 
 	/*Transient or static?:*/
@@ -55,7 +55,7 @@
 			if((iomodel->my_vertices[i])){
 
-				if (!isnan(doublevector[i])){
+				if (!xIsNan<IssmDouble>(IssmDoublevector[i])){
 
-					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,doublevector[i],analysis_type));
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,IssmDoublevector[i],analysis_type));
 					count++;
 				}
@@ -69,7 +69,7 @@
 
 		/*figure out times: */
-		times=(double*)xmalloc(N*sizeof(double));
+		times=xNew<IssmDouble>(N);
 		for(j=0;j<N;j++){
-			times[j]=doublevector[(M-1)*N+j];
+			times[j]=IssmDoublevector[(M-1)*N+j];
 		}
 		/*unit conversion: */
@@ -83,9 +83,9 @@
 
 				/*figure out times and values: */
-				values=(double*)xmalloc(N*sizeof(double));
+				values=xNew<IssmDouble>(N);
 				spcpresent=false;
 				for(j=0;j<N;j++){
-					values[j]=doublevector[i*N+j];
-					if(!isnan(values[j]))spcpresent=true; //NaN means no spc by default
+					values[j]=IssmDoublevector[i*N+j];
+					if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
 				}
 
@@ -94,15 +94,15 @@
 					count++;
 				}
-				xfree((void**)&values);
+				xDelete<IssmDouble>(values);
 			}
 		}
 	}
 	else{
-		_error_("Size of field %s not supported",EnumToStringx(vector_enum));
+		_error2_("Size of field " << EnumToStringx(vector_enum) << " not supported");
 	}
 
 	/*Free ressources:*/
-	xfree((void**)&doublevector);
-	xfree((void**)&times);
-	xfree((void**)&values);
+	xDelete<IssmDouble>(IssmDoublevector);
+	xDelete<IssmDouble>(times);
+	xDelete<IssmDouble>(values);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h	(revision 12878)
@@ -6,5 +6,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/KMLFileReadx/KMLFileReadx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/KMLFileReadx/KMLFileReadx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/KMLFileReadx/KMLFileReadx.cpp	(revision 12878)
@@ -21,5 +21,5 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_printf_(true,"\nKMLFileReadx Module -- %s",ctime(&time0));
+	_pprintString_("\nKMLFileReadx Module -- " << ctime(&time0));
 
 /*  read kml file  */
@@ -43,15 +43,15 @@
 		}
 
-//		_printf_(true,"%s\n",kstr);
-		xfree((void**)&kstr);
+//		_pprintLine_(kstr);
+		xDelete<char>(kstr);
 	}
 
 	if (kxml) {
-		_printf_(true,"XML declaration:\n");
+		_pprintLine_("XML declaration:");
 		kxml->DeepEcho("  ");
 		delete kxml;
 	}
 	if (kdtd) {
-		_printf_(true,"DTD declaration (not yet implemented):\n");
+		_pprintLine_("DTD declaration (not yet implemented):");
 		kdtd->DeepEcho("  ");
 		delete kdtd;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/KMLFileReadx/KMLFileReadx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/KMLFileReadx/KMLFileReadx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/KMLFileReadx/KMLFileReadx.h	(revision 12878)
@@ -8,5 +8,5 @@
 #include <float.h>    /*  DBL_MAX  */
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 12878)
@@ -9,28 +9,18 @@
 #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){
-
-	int     i,j,k,ipt=0,jpt=0,nnodes;
-	int     mxepg=25;
-	int     lwidth=1;
-	double  popac=0.50;
-	char    indent[81]="  ";
-	char    cstr[81];
-	double* edata=NULL;
-	bool    ncfree=false,
-			edfree=false;
-	KML_Document*  kdoc=NULL;
-	KML_Style*     kstyle;
-	KML_LineStyle* klsty;
-	KML_PolyStyle* kpsty;
+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){
+
+	int                 i,j,k,ipt=0,jpt=0,nnodes;
+	int                 mxepg      = 25;
+	int                 lwidth     = 1;
+	double              popac      = 0.50;
+	char                indent[81] = " ";
+	char                cstr[81];
+	double             *edata = NULL;
+	bool ncfree=false, edfree=false;
+	KML_Document       *kdoc = NULL;
+	KML_Style          *kstyle;
+	KML_LineStyle      *klsty;
+	KML_PolyStyle      *kpsty;
 
 	clock_t clock0,clock1,clock0a,clock0b,clock0c;
@@ -39,5 +29,5 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_printf_(true,"\nKMLMeshWritex Module -- %s",ctime(&time0));
+	_pprintString_("\nKMLMeshWritex Module -- " << ctime(&time0));
 
 /*  construct kml document  */
@@ -93,5 +83,5 @@
 
 	if (cmap) {
-		_printf_(true,"Writing %d Matlab colors as KML style templates.\n",mcmap);
+		_pprintLine_("Writing " << mcmap << " Matlab colors as KML style templates.");
 		ipt=0;
 		for (i=0; i<mcmap; i++) {
@@ -128,7 +118,7 @@
 
 	if (!nodecon) {
-		_printf_(true,"Creating the node connectivity table.\n");
+		_pprintLine_("Creating the node connectivity table.");
 		nncon=mxepg+1;
-		nodecon=(int *) xcalloc(mncon*nncon,sizeof(int));
+		nodecon=xNewZeroInit<int>(mncon*nncon);
 		ncfree=true;
 
@@ -143,5 +133,5 @@
 					}
 					else
-						_error_("Nodal connectivity table needs more than specified %d columns.\n",mxepg);
+						_error2_("Nodal connectivity table needs more than specified " << mxepg << " columns.\n");
 				}
 				jpt++;
@@ -159,6 +149,6 @@
 
 		else if (mdata == mncon) {
-			_printf_(true,"Averaging nodal data to element data.\n");
-			edata=(double *) xcalloc(melem*ndata,sizeof(double));
+			_pprintLine_("Averaging nodal data to element data.");
+			edata=xNewZeroInit<double>(melem*ndata);
 			edfree=true;
 
@@ -183,5 +173,5 @@
 
 		else
-			_error_("Data matrix has incorrect number of %d rows.\n",mdata);
+			_error2_("Data matrix has incorrect number of " << mdata << " rows.\n");
 	}
 
@@ -194,6 +184,6 @@
 														cmap,mcmap,ncmap));
 
-	if (edfree) xfree((void**)&edata);
-	if (ncfree) xfree((void**)&nodecon);
+	if(edfree) xDelete<double>(edata);
+	if(ncfree) xDelete<int>(nodecon);
 	clock0a=clock();
 	time0a =time(NULL);
@@ -203,5 +193,5 @@
 /*  write kml file  */
 
-	_printf_(true,"Writing kml document to file.\n");
+	_pprintLine_("Writing kml document to file.");
 	fprintf(fid,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
 	fprintf(fid,"<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n");
@@ -213,5 +203,5 @@
 			 ((double)(clock0b-clock0a))/CLOCKS_PER_SEC,difftime(time0b,time0a));
 
-	_printf_(true,"Deleting kml document.\n");
+	_pprintLine_("Deleting kml document.");
 	delete kdoc;
 	clock0c=clock();
@@ -314,5 +304,5 @@
 /*  write each element as a polygon placemark  */
 
-	_printf_(true,"Writing %d tria elements as KML polygons.\n",melem);
+	_pprintLine_("Writing " << melem << " tria elements as KML polygons.");
 
 	for (i=0; i<melem; i++) {
@@ -344,29 +334,29 @@
 		kring=new KML_LinearRing();
 		kring->ncoord    =nelem+1;
-		kring->coords    =(double (*)[3]) xmalloc((nelem+1)*3*sizeof(double));
+		kring->coords =xNew<double>((nelem+1)*3);
 
 /*  write the nodal coordinates as a linear ring  */
 
 		for (j=0; j<nelem; j++) {
-			kring->coords[j][0]=lng[elem[ipt]-1];
-			kring->coords[j][1]=lat[elem[ipt]-1];
-			kring->coords[j][2]=alt;
+			kring->coords[3*j+0]=lng[elem[ipt]-1];
+			kring->coords[3*j+1]=lat[elem[ipt]-1];
+			kring->coords[3*j+2]=alt;
 			ipt++;
 		}
-		kring->coords[nelem][0]=kring->coords[0][0];
-		kring->coords[nelem][1]=kring->coords[0][1];
-		kring->coords[nelem][2]=kring->coords[0][2];
+		kring->coords[3*nelem+0]=kring->coords[3*0+0];
+		kring->coords[3*nelem+1]=kring->coords[3*0+1];
+		kring->coords[3*nelem+2]=kring->coords[3*0+2];
 //		kring->DeepEcho();
 
 /*  assemble the linear ring into polygon into placemark into folder  */
 
-		(kpoly ->outer     )->AddObject((Object*)kring);
-		(kplace->geometry  )->AddObject((Object*)kpoly);
-		(kfold ->feature   )->AddObject((Object*)kplace);
+		(kpoly ->outer   )->AddObject((Object*)kring);
+		(kplace->geometry)->AddObject((Object*)kpoly);
+		(kfold ->feature )->AddObject((Object*)kplace);
 
 //		if (!(int)fmod((double)(i+1),1000))
-//			_printf_(true,"  %d tria elements written.\n",(i+1));
+//			_pprintLine_("  " << (i+1) << " tria elements written.");
 	}
-	_printf_(true,"  %d tria elements written.\n",melem);
+	_pprintLine_("  " << melem << " tria elements written.");
 
 	return(kfold);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/KMLMeshWritex/KMLMeshWritex.h	(revision 12878)
@@ -8,5 +8,5 @@
 #include <float.h>    /*  DBL_MAX  */
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/KMLOverlayx/KMLOverlayx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/KMLOverlayx/KMLOverlayx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/KMLOverlayx/KMLOverlayx.cpp	(revision 12878)
@@ -28,5 +28,5 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_printf_(true,"\nKMLOverlayx Module -- %s",ctime(&time0));
+	_pprintString_("\nKMLOverlayx Module -- " << ctime(&time0));
 
 /*  construct kml file  */
@@ -82,5 +82,5 @@
 /*  write kml file  */
 
-	_printf_(true,"Writing kml document to file.\n");
+	_pprintLine_("Writing kml document to file.");
 	fprintf(fid,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
 	kfile->Write(fid,indent);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/KMLOverlayx/KMLOverlayx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/KMLOverlayx/KMLOverlayx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/KMLOverlayx/KMLOverlayx.h	(revision 12878)
@@ -8,5 +8,5 @@
 #include <float.h>    /*  DBL_MAX  */
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 12878)
@@ -38,5 +38,5 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_printf_(true,"\nKml2Expx Module -- %s",ctime(&time0));
+	_pprintString_("\nKml2Expx Module -- " << ctime(&time0));
 
 /*  read kml file  */
@@ -44,10 +44,10 @@
 	fidi=fopen(filkml,"r");
 	if (!(kobj=KMLFileReadx(fidi)))
-		_error_("Error reading kml file.");
+		_error2_("Error reading kml file.");
 	fclose(fidi);
 
 /*  open exp file  */
 
-	_printf_(true,"Writing exp profiles to file.\n");
+	_pprintLine_("Writing exp profiles to file.");
 	fido=fopen(filexp,"w");
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Kml2Expx/Kml2Expx.h	(revision 12878)
@@ -8,5 +8,5 @@
 #include <float.h>    /*  DBL_MAX  */
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/Krigingx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/Krigingx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/Krigingx.cpp	(revision 12878)
@@ -7,13 +7,10 @@
 #include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Observations.h"
 #include "../modules.h"
-
 #ifdef _HAVE_GSL_
 #include <gsl/gsl_linalg.h>
 #endif
-
-#include "../../objects/Kriging/GaussianVariogram.h"
 /*FUNCTION Krigingx{{{*/
 int Krigingx(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){
@@ -24,5 +21,6 @@
 
 	/*Intermediaries*/
-	double        range;
+	int           mindata,maxdata;
+	double        radius;
 	char         *output       = NULL;
 	Variogram    *variogram    = NULL;
@@ -38,5 +36,7 @@
 	/*Get Variogram from Options*/
 	ProcessVariogram(&variogram,options);
-	options->Get(&range,"searchrange",0.);
+	options->Get(&radius,"searchradius",0.);
+	options->Get(&mindata,"mindata",1);
+	options->Get(&maxdata,"maxdata",50);
 
 	/*Process observation dataset*/
@@ -44,6 +44,6 @@
 
 	/*Allocate output*/
-	predictions =(double*)xcalloc(n_interp,sizeof(double));
-	error       =(double*)xcalloc(n_interp,sizeof(double));
+	predictions =xNewZeroInit<double>(n_interp);
+	error       =xNewZeroInit<double>(n_interp);
 
 	/*Get output*/
@@ -56,24 +56,87 @@
 		observations->Variomap(predictions,x_interp,n_interp);
 	}
-	else if(strcmp(output,"prediction")==0){
-
+	else if(strcmp(output,"delaunay")==0){
+		int nobs,nel;
+		double *x     = NULL;
+		double *y     = NULL;
+		double *data  = NULL;
+		int    *index = NULL;
+
+		observations->ObservationList(&x,&y,&data,&nobs);
+
+		_printLine_("Generation Delaunay Triangulation");
+		BamgTriangulatex(&index,&nel,x,y,nobs);
+
+		_printLine_("Interpolating");
+		xDelete<double>(predictions);
+		InterpFromMeshToMesh2dx(&predictions,index,x,y,nobs,nel,data,nobs,1,x_interp,y_interp,n_interp,options);
+		xDelete<double>(x);
+		xDelete<double>(y);
+		xDelete<double>(data);
+		xDelete<int>(index);
+	}
+	else if(strcmp(output,"nearestneighbor")==0){
 		/*initialize thread parameters: */
 		gate.n_interp     = n_interp;
 		gate.x_interp     = x_interp;
 		gate.y_interp     = y_interp;
-		gate.range        = range;
+		gate.radius       = radius;
+		gate.mindata      = mindata;
+		gate.maxdata      = maxdata;
 		gate.variogram    = variogram;
 		gate.observations = observations;
 		gate.predictions  = predictions;
 		gate.error        = error;
-		gate.percent      = (double*)xcalloc(num,sizeof(double));
+		gate.percent      = xNewZeroInit<double>(num);
+
+		/*launch the thread manager with Krigingxt as a core: */
+		LaunchThread(NearestNeighbort,(void*)&gate,num);
+		_printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+		xDelete<double>(gate.percent);
+	}
+	else if(strcmp(output,"idw")==0){ //Inverse distance weighting
+		double power;
+		options->Get(&power,"power",2.);
+		/*initialize thread parameters: */
+		gate.n_interp     = n_interp;
+		gate.x_interp     = x_interp;
+		gate.y_interp     = y_interp;
+		gate.radius       = radius;
+		gate.mindata      = mindata;
+		gate.maxdata      = maxdata;
+		gate.variogram    = variogram;
+		gate.observations = observations;
+		gate.predictions  = predictions;
+		gate.error        = error;
+		gate.percent      = xNewZeroInit<double>(num);
+		gate.power        = power;
+
+		/*launch the thread manager with Krigingxt as a core: */
+		LaunchThread(idwt,(void*)&gate,num);
+		_printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+		xDelete<double>(gate.percent);
+	}
+	else if(strcmp(output,"prediction")==0){
+
+		/*initialize thread parameters: */
+		gate.n_interp     = n_interp;
+		gate.x_interp     = x_interp;
+		gate.y_interp     = y_interp;
+		gate.radius       = radius;
+		gate.mindata      = mindata;
+		gate.maxdata      = maxdata;
+		gate.variogram    = variogram;
+		gate.observations = observations;
+		gate.predictions  = predictions;
+		gate.error        = error;
+		gate.percent      = xNewZeroInit<double>(num);
 
 		/*launch the thread manager with Krigingxt as a core: */
 		LaunchThread(Krigingxt,(void*)&gate,num);
-		printf("\r      interpolation progress:  100.00%%\n");
-		xfree((void**)&gate.percent);
+		_printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+		xDelete<double>(gate.percent);
 	}
 	else{
-		_error_("output '%s' not supported yet",output);
+		_error2_("output '" << output << "' not supported yet");
 	}
 
@@ -81,5 +144,5 @@
 	delete variogram;
 	delete observations;
-	xfree((void**)&output);
+	xDelete<char>(output);
 	*ppredictions = predictions;
 	*perror       = error;
@@ -106,5 +169,7 @@
 	double       *x_interp     = gate->x_interp;
 	double       *y_interp     = gate->y_interp;
-	double        range        = gate->range;
+	double        radius       = gate->radius;
+	int           mindata      = gate->mindata;
+	int           maxdata      = gate->maxdata;
 	Variogram    *variogram    = gate->variogram;
 	Observations *observations = gate->observations;
@@ -114,15 +179,54 @@
 
 	/*Intermediaries*/
-	int           i,j,n_obs;
-	double        numerator,denominator,ratio,localpercent;
-	double       *x            = NULL;
-	double       *y            = NULL;
-	double       *obs          = NULL;
-	double       *Gamma        = NULL;
-	double       *GinvG0       = NULL;
-	double       *Ginv1        = NULL;
-	double       *GinvZ        = NULL;
-	double       *gamma0       = NULL;
-	double       *ones         = NULL;
+	double        localpercent;
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,n_interp,num_threads,my_thread);
+	for(int idx=i0;idx<i1;idx++){
+
+		/*Print info*/
+		percent[my_thread]=double(idx-i0)/double(i1-i0)*100.;
+		localpercent=percent[0];
+		for(int i=1;i<num_threads;i++) localpercent=min(localpercent,percent[i]);
+		if(my_thread==0) _printString_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<localpercent<<"%");
+
+		/*Kriging interpolation*/
+		observations->InterpolationKriging(&predictions[idx],&error[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata,variogram);
+	}
+
+	return NULL;
+}/*}}}*/
+/*FUNCTION NearestNeighbort{{{*/
+void* NearestNeighbort(void* vpthread_handle){
+
+	/*gate variables :*/
+	KrigingxThreadStruct *gate        = NULL;
+	pthread_handle       *handle      = NULL;
+	int my_thread;
+	int num_threads;
+	int i0,i1;
+
+	/*recover handle and gate: */
+	handle      = (pthread_handle*)vpthread_handle;
+	gate        = (KrigingxThreadStruct*)handle->gate;
+	my_thread   = handle->id;
+	num_threads = handle->num;
+
+	/*recover parameters :*/
+	int           n_interp     = gate->n_interp;
+	double       *x_interp     = gate->x_interp;
+	double       *y_interp     = gate->y_interp;
+	double        radius       = gate->radius;
+	int           mindata      = gate->mindata;
+	int           maxdata      = gate->maxdata;
+	Variogram    *variogram    = gate->variogram;
+	Observations *observations = gate->observations;
+	double       *predictions  = gate->predictions;
+	double       *error        = gate->error;
+	double       *percent      = gate->percent;
+
+	/*Intermediaries*/
+	int           i;
+	double        localpercent;
 
 	/*partition loop across threads: */
@@ -134,54 +238,56 @@
 		localpercent=percent[0];
 		for(i=1;i<num_threads;i++) localpercent=min(localpercent,percent[i]);
-		printf("\r      interpolation progress: %5.2lf%%",localpercent);
-
-		/*Get list of observations for current point*/
-		observations->ObservationList(&x,&y,&obs,&n_obs,x_interp[idx],y_interp[idx],range);
-
-		/*Allocate intermediary matrix and vectors*/
-		Gamma  = (double*)xmalloc(n_obs*n_obs*sizeof(double));
-		gamma0 = (double*)xmalloc(n_obs*sizeof(double));
-		ones   = (double*)xmalloc(n_obs*sizeof(double));
-
-		/*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[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[idx],y[i]-y_interp[idx]);
-
-		/*Solve the three linear systems*/
-		GslSolve(&GinvG0,Gamma,gamma0,n_obs); // Gamma^-1 gamma0
-		GslSolve(&Ginv1, Gamma,ones,n_obs);   // Gamma^-1 ones
-		GslSolve(&GinvZ, Gamma,obs,n_obs);    // Gamma^-1 Z
-
-		/*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;
-
-		predictions[idx] = 0.;
-		error[idx]       = - numerator*numerator/denominator;
-		for(i=0;i<n_obs;i++) predictions[idx] += (gamma0[i]-ratio)*GinvZ[i];
-		for(i=0;i<n_obs;i++) error[idx] += gamma0[i]*GinvG0[i];
-
-		/*clean-up*/
-		xfree((void**)&x);
-		xfree((void**)&y);
-		xfree((void**)&obs);
-		xfree((void**)&Gamma);
-		xfree((void**)&gamma0);
-		xfree((void**)&ones);
-		xfree((void**)&GinvG0);
-		xfree((void**)&Ginv1);
-		xfree((void**)&GinvZ);
-	}
-
+		if(my_thread==0) _printString_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<localpercent<<"%");
+
+		observations->InterpolationNearestNeighbor(&predictions[idx],x_interp[idx],y_interp[idx],radius);
+	}
+
+	return NULL;
+}/*}}}*/
+/*FUNCTION idwt{{{*/
+void* idwt(void* vpthread_handle){
+
+	/*gate variables :*/
+	KrigingxThreadStruct *gate        = NULL;
+	pthread_handle       *handle      = NULL;
+	int my_thread;
+	int num_threads;
+	int i0,i1;
+
+	/*recover handle and gate: */
+	handle      = (pthread_handle*)vpthread_handle;
+	gate        = (KrigingxThreadStruct*)handle->gate;
+	my_thread   = handle->id;
+	num_threads = handle->num;
+
+	/*recover parameters :*/
+	int           n_interp     = gate->n_interp;
+	double       *x_interp     = gate->x_interp;
+	double       *y_interp     = gate->y_interp;
+	double        radius       = gate->radius;
+	int           mindata      = gate->mindata;
+	int           maxdata      = gate->maxdata;
+	Variogram    *variogram    = gate->variogram;
+	Observations *observations = gate->observations;
+	double       *predictions  = gate->predictions;
+	double       *error        = gate->error;
+	double       *percent      = gate->percent;
+	double        power        = gate->power;
+
+	/*Intermediaries*/
+	double localpercent;
+
+	/*partition loop across threads: */
+	PartitionRange(&i0,&i1,n_interp,num_threads,my_thread);
+	for(int idx=i0;idx<i1;idx++){
+
+		/*Print info*/
+		percent[my_thread]=double(idx-i0)/double(i1-i0)*100.;
+		localpercent=percent[0];
+		for(int i=1;i<num_threads;i++) localpercent=min(localpercent,percent[i]);
+		if(my_thread==0) _printString_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<localpercent<<"%");
+
+		observations->InterpolationIDW(&predictions[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata,power);
+	}
 	return NULL;
 }/*}}}*/
@@ -199,50 +305,10 @@
 		else if(strcmp(model,"spherical")==0)   variogram = new SphericalVariogram(options);
 		else if(strcmp(model,"power")==0)       variogram = new PowerVariogram(options);
-		else _error_("variogram %s not supported yet (list of supported variogram: gaussian, exponential, spherical and power)",model);
+		else _error2_("variogram " << model << " not supported yet (list of supported variogram: gaussian, exponential, spherical and power)");
 	}
 	else variogram = new GaussianVariogram(options);
 
 	/*Assign output pointer*/
-	xfree((void**)&model);
+	xDelete<char>(model);
 	*pvariogram = variogram;
 }/*}}}*/
-void GslSolve(double** pX,double* A,double* B,int n){/*{{{*/
-#ifdef _HAVE_GSL_
-
-		/*GSL Matrices and vectors: */
-		int              s;
-		gsl_matrix_view  a;
-		gsl_vector_view  b;
-		gsl_vector      *x = NULL;
-		gsl_permutation *p = NULL;
-
-		/*A will be modified by LU decomposition. Use copy*/
-		double* Acopy = (double*)xmalloc(n*n*sizeof(double));
-		memcpy(Acopy,A,n*n*sizeof(double));
-
-		/*Initialize gsl matrices and vectors: */
-		a = gsl_matrix_view_array (Acopy,n,n);
-		b = gsl_vector_view_array (B,n);
-		x = gsl_vector_alloc (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);
-
-		//printf ("x = \n");
-		//gsl_vector_fprintf (stdout, x, "%g");
-
-		/*Copy result*/
-		double* X = (double*)xmalloc(n*sizeof(double));
-		memcpy(X,gsl_vector_ptr(x,0),n*sizeof(double));
-
-		/*Clean up and assign output pointer*/
-		xfree((void**)&Acopy);
-		gsl_permutation_free(p);
-		gsl_vector_free(x);
-		*pX=X;
-#else
-		_error_("GSL support required");
-#endif
-	}/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/Krigingx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/Krigingx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/Krigingx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _KRIGINGX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../toolkits/toolkits.h"
 
@@ -13,6 +13,6 @@
 
 int  Krigingx(double** ppredictions,double **perror,double* x, double* y, double* observations, int n_obs,double* x_interp,double* y_interp,int n_interp,Options* options);
+int  pKrigingx(double** ppredictions,double **perror,double* x, double* y, double* observations, int n_obs,double* x_interp,double* y_interp,int n_interp,Options* options);
 void ProcessVariogram(Variogram **pvariogram,Options* options);
-void GslSolve(double** pX,double* A,double* B,int n);
 
 /*threading: */
@@ -21,5 +21,7 @@
 	double       *x_interp;
 	double       *y_interp;
-	double        range;
+	double        radius;
+	int           mindata;
+	int           maxdata;
 	Variogram    *variogram;
 	Observations *observations;
@@ -27,6 +29,9 @@
 	double       *error;
 	double       *percent;
+	double        power;//for idw
 }KrigingxThreadStruct;
 
 void* Krigingxt(void*);
+void* NearestNeighbort(void*);
+void* idwt(void*);
 #endif /* _KRIGINGX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/pKrigingx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/pKrigingx.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Krigingx/pKrigingx.cpp	(revision 12878)
@@ -0,0 +1,135 @@
+/*!\file:  Kriging.cpp
+ * \brief  "c" core code for Kriging
+ */ 
+
+#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"
+
+/*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){
+
+	extern int num_procs;
+	extern int my_rank;
+
+	/*output*/
+	double *predictions = NULL;
+	double *error       = NULL;
+
+	/*Intermediaries*/
+	int           mindata,maxdata;
+	double        radius;
+	char         *output       = NULL;
+	Variogram    *variogram    = NULL;
+	Observations *observations = NULL;
+
+	/*Get some Options*/
+	options->Get(&radius,"searchradius",0.);
+	options->Get(&mindata,"mindata",1);
+	options->Get(&maxdata,"maxdata",50);
+
+	/*Process observation dataset*/
+	observations=new Observations(obs_list,obs_x,obs_y,obs_length,options);
+
+	/*Allocate output*/
+	predictions =xNewZeroInit<double>(n_interp);
+	error       =xNewZeroInit<double>(n_interp);
+
+	/*Get output*/
+	options->Get(&output,"output","prediction");
+
+	if(strcmp(output,"quadtree")==0){
+		observations->QuadtreeColoring(predictions,x_interp,y_interp,n_interp);
+	}
+	else if(strcmp(output,"variomap")==0){
+		observations->Variomap(predictions,x_interp,n_interp);
+	}
+	else if(strcmp(output,"prediction")==0){
+
+		/*Process Variogram*/
+		ProcessVariogram(&variogram,options);
+
+		/*partition loop across threads: */
+		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
+			_pprintString_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(idx)/double(n_interp)*100<<"%");
+			observations->InterpolationKriging(&predictions[idx],&error[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata,variogram);
+		}
+		_pprintLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+
+#ifdef _HAVE_MPI_
+		double *sumpredictions =xNew<double>(n_interp);
+		double *sumerror       =xNew<double>(n_interp);
+		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+		MPI_Allreduce(error,sumerror,n_interp,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+		xDelete<double>(error); error=sumerror;
+		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){
+			_pprintString_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(idx)/double(n_interp)*100<<"%");
+			observations->InterpolationNearestNeighbor(&predictions[idx],x_interp[idx],y_interp[idx],radius);
+		}
+		_pprintLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+
+#ifdef _HAVE_MPI_
+		double *sumpredictions =xNew<double>(n_interp);
+		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+		xDelete<double>(predictions); predictions=sumpredictions;
+#endif
+	}
+	else if(strcmp(output,"idw")==0){
+		double power;
+		options->Get(&power,"power",2.);
+
+		/*partition loop across threads: */
+		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
+			_pprintString_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(idx)/double(n_interp)*100<<"%");
+			observations->InterpolationIDW(&predictions[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata,power);
+		}
+		_pprintLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
+
+#ifdef _HAVE_MPI_
+		double *sumpredictions =xNew<double>(n_interp);
+		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+		xDelete<double>(predictions); predictions=sumpredictions;
+#endif
+	}
+	else{
+		_error2_("output '" << output << "' not supported yet");
+	}
+
+	/*clean-up and Assign output pointer*/
+	delete variogram;
+	delete observations;
+	xDelete<char>(output);
+	*ppredictions = predictions;
+	*perror       = error;
+	return 1;
+}/*}}}*/
+void ProcessVariogram(Variogram **pvariogram,Options* options){/*{{{*/
+
+	/*Intermediaries*/
+	Variogram* variogram = NULL;
+	char      *model     = NULL;
+
+	if(options->GetOption("model")){
+		options->Get(&model,"model");
+		if     (strcmp(model,"gaussian")==0)    variogram = new GaussianVariogram(options);
+		else if(strcmp(model,"exponential")==0) variogram = new ExponentialVariogram(options);
+		else if(strcmp(model,"spherical")==0)   variogram = new SphericalVariogram(options);
+		else if(strcmp(model,"power")==0)       variogram = new PowerVariogram(options);
+		else _error2_("variogram " << model << " not supported yet (list of supported variogram: gaussian, exponential, spherical and power)");
+	}
+	else variogram = new GaussianVariogram(options);
+
+	/*Assign output pointer*/
+	xDelete<char>(model);
+	*pvariogram = variogram;
+}/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Ll2xyx/Ll2xyx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Ll2xyx/Ll2xyx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Ll2xyx/Ll2xyx.cpp	(revision 12878)
@@ -52,5 +52,5 @@
 	double  T,rho,sl,tc,mc;
 
-	if((sgn!=1) && (sgn!=-1)) _error_("Sign should be either +1 or -1.\n");
+	if((sgn!=1) && (sgn!=-1)) _error2_("Sign should be either +1 or -1.\n");
 
 	delta = central_meridian;
@@ -116,12 +116,12 @@
 		*pdelta= 45;
 		*pslat = 70;
-		_printf_(flag,"Info: creating coordinates in polar stereographic (Std Latitude: 70N Meridian: 45).\n");
+		if(flag) _pprintLine_("Info: creating coordinates in polar stereographic (Std Latitude: 70N Meridian: 45).");
 	}
 	else if (sgn == -1) {
 		*pdelta= 0;
 		*pslat = 71;
-		_printf_(flag,"Info: creating coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).\n");
+		if(flag) _pprintLine_("Info: creating coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).");
 	}
-	else _error_("Sign should be either +1 or -1.\n");
+	else _error2_("Sign should be either +1 or -1.\n");
 
 	return;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.cpp	(revision 12878)
@@ -67,9 +67,9 @@
 	for(j=0;j<M;j++){
 		double* matrix=array[j];
-		xfree((void**)&matrix);
+		xDelete<double>(matrix);
 	}
-	xfree((void**)&mdims_array);
-	xfree((void**)&ndims_array);
-	xfree((void**)&array);
+	xDelete<int>(mdims_array);
+	xDelete<int>(ndims_array);
+	xDelete<double*>(array);
 	
 	/*Assign output pointers: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MassFluxx/MassFluxx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVxx/MaxAbsVxx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVyx/MaxAbsVyx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxAbsVzx/MaxAbsVzx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxVelx/MaxVelx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxVxx/MaxVxx.h	(revision 12878)
@@ -6,5 +6,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxVyx/MaxVyx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MaxVzx/MaxVzx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp	(revision 12878)
@@ -17,5 +17,5 @@
 
 	/*Display message*/
-	_printf_(VerboseModule(),"   Merging solution vector from fset to gset\n");
+	if(VerboseModule()) _pprintLine_("   Merging solution vector from fset to gset");
 
 	/*first, get gsize, fsize and ssize: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _MERGESOLUTIONFROMFTOGX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.cpp	(revision 12878)
@@ -9,6 +9,6 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-int MeshPartitionx(int** pepart, int** pnpart, int numberofelements,int numberofnodes,double* elements,
-		int numberofelements2d,int numberofnodes2d,double* elements2d,int numlayers,int elements_width, int dim,int num_procs){
+int MeshPartitionx(int** pepart, int** pnpart, int numberofelements,int numberofnodes,IssmDouble* elements,
+		int numberofelements2d,int numberofnodes2d,IssmDouble* elements2d,int numlayers,int elements_width, int dim,int num_procs){
 
 	int noerr=1;
@@ -31,10 +31,10 @@
 
 	if(dim==2){
-		epart=(int*)xmalloc(numberofelements*sizeof(int));
-		npart=(int*)xmalloc(numberofnodes*sizeof(int));
-		index=(int*)xmalloc(elements_width*numberofelements*sizeof(int));
+		epart=xNew<int>(numberofelements);
+		npart=xNew<int>(numberofnodes);
+		index=xNew<int>(elements_width*numberofelements);
 		for (i=0;i<numberofelements;i++){
 			for (j=0;j<elements_width;j++){
-				*(index+elements_width*i+j)=(int)*(elements+elements_width*i+j)-1; //-1 for C indexing in Metis
+				*(index+elements_width*i+j)=reCast<int>(*(elements+elements_width*i+j))-1; //-1 for C indexing in Metis
 			}
 		}
@@ -51,5 +51,5 @@
 			for (i=0;i<numberofnodes;i++)    npart[i]=0;
 		}
-		else _error_("At least one processor is required");
+		else _error2_("At least one processor is required");
 	}
 	else{
@@ -57,11 +57,11 @@
 
 		/*First build concatenated 2d mesh  from 2d_coll and 2d_noncoll: */
-		epart2d=(int*)xmalloc(numberofelements2d*sizeof(int));
-		npart2d=(int*)xmalloc(numberofnodes2d*sizeof(int)); 
-		index2d=(int*)xmalloc(3*numberofelements2d*sizeof(int));
+		epart2d=xNew<int>(numberofelements2d);
+		npart2d=xNew<int>(numberofnodes2d); 
+		index2d=xNew<int>(3*numberofelements2d);
 
 		for (i=0;i<numberofelements2d;i++){
 			for (j=0;j<3;j++){
-				*(index2d+3*i+j)=(int)*(elements2d+3*i+j)-1; //-1 for C indexing in Metis
+				*(index2d+3*i+j)=reCast<int>(*(elements2d+3*i+j))-1; //-1 for C indexing in Metis
 			}
 		}
@@ -78,8 +78,8 @@
 			for (i=0;i<numberofnodes2d;i++)    npart2d[i]=0;
 		}
-		else _error_("At least one processor is required");
+		else _error2_("At least one processor is required");
 
 		/*Extrude epart2d to epart, using numlayers: */
-		epart=(int*)xmalloc(numberofelements*sizeof(int));
+		epart=xNew<int>(numberofelements);
 		
 		count=0;
@@ -92,5 +92,5 @@
 
 		/*Extrude npart2d to npart, using numlayers: */
-		npart=(int*)xmalloc(numberofnodes*sizeof(int));
+		npart=xNew<int>(numberofnodes);
 		
 		count=0;
@@ -108,10 +108,8 @@
 
 	/*Free ressources: */
-	xfree((void**)&index);
-	xfree((void**)&epart2d);
-	xfree((void**)&npart2d);
-	xfree((void**)&index2d);
-
+	xDelete<int>(index);
+	xDelete<int>(epart2d);
+	xDelete<int>(npart2d);
+	xDelete<int>(index2d);
 	return noerr;
-
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 12878)
@@ -6,7 +6,9 @@
 #define _MESHPARTITIONX_H
 
+#include "../../include/include.h"
+
 /* local prototypes: */
-int MeshPartitionx(int** pepart, int** pnpart, int numberofelements,int numberofnodes,double* elements,
-		int numberofelements2d,int numberofnodes2d,double* elements2d,int numlayers,int elements_width, int dim,int numareas);
+int MeshPartitionx(int** pepart, int** pnpart, int numberofelements,int numberofnodes,IssmDouble* elements,
+		int numberofelements2d,int numberofnodes2d,IssmDouble* elements2d,int numlayers,int elements_width, int dim,int numareas);
 	
 #endif /* _MESHPARTITIONX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp	(revision 12878)
@@ -38,5 +38,5 @@
 	if(    (edge1==IntersectEnum) && (edge2==IntersectEnum) && (edge3==IntersectEnum)   ){
 		/*This case is impossible: */
-		_error_(" error: a line cannot go through 3 different vertices!");
+		_error2_("error: a line cannot go through 3 different vertices!");
 	}
 	else if(    ((edge1==IntersectEnum) && (edge2==IntersectEnum)) || ((edge2==IntersectEnum) && (edge3==IntersectEnum)) || ((edge3==IntersectEnum) && (edge1==IntersectEnum))   ){
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 12878)
@@ -5,5 +5,4 @@
 
 void MeshProfileIntersectionx( double** psegments, int* pnumsegs, int* index, double* x, double* y, int nel, int nods,  Contour** contours,int numcontours){
-
 
 	int i,j,k;
@@ -28,6 +27,6 @@
 
 	/*Allocate: */
-	allsegments=(double**)xmalloc(numcontours*sizeof(double*));
-	allnumsegs=(int*)xmalloc(numcontours*sizeof(int));
+	allsegments=xNew<double*>(numcontours);
+	allnumsegs=xNew<int>(numcontours);
 
 	/*Loop through all contours: */
@@ -53,5 +52,5 @@
 
 	/*Out of all segments, create one common array of segments: */
-	segments=(double*)xmalloc(5*numsegs*sizeof(double));
+	segments=xNew<double>(5*numsegs);
 	count=0;
 	for(i=0;i<numcontours;i++){
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 12878)
@@ -8,5 +8,5 @@
 
 #include "../../shared/shared.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp	(revision 12878)
@@ -32,5 +32,5 @@
 	/*Using the segments_dataset dataset, create segments: */
 	numsegs=segments_dataset->Size();
-	segments=(double*)xmalloc(5*numsegs*sizeof(double));
+	segments=xNew<double>(5*numsegs);
 	for(i=0;i<numsegs;i++){
 		Segment* segment=(Segment*)segments_dataset->GetObjectByOffset(i);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MinVelx/MinVelx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MinVxx/MinVxx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MinVyx/MinVyx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/MinVzx/MinVzx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 #include "../../../toolkits/toolkits.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
@@ -46,5 +46,5 @@
 
 	/*Check in 3d*/
-	if(stabilization==3 && dim==3) _error_("DG 3d not implemented yet");
+	if(stabilization==3 && dim==3) _error2_("DG 3d not implemented yet");
 
 	/*First fetch data: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../toolkits/toolkits.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../toolkits/toolkits.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../toolkits/toolkits.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
@@ -63,9 +63,9 @@
 		parameters->AddObject(new DoubleVecParam(InversionMaxiterPerStepEnum,maxiter,nsteps));
 
-		xfree((void**)&control_type);
-		xfree((void**)&cm_responses);
-		xfree((void**)&cm_jump);
-		xfree((void**)&optscal);
-		xfree((void**)&maxiter);
+		xDelete<int>(control_type);
+		xDelete<double>(cm_responses);
+		xDelete<double>(cm_jump);
+		xDelete<double>(optscal);
+		xDelete<double>(maxiter);
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateDataSets.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 12878)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../../include/include.h"
@@ -124,5 +124,5 @@
 
 		default:
-			_error_("%s%s%s"," analysis_type: ",EnumToStringx(analysis_type)," not supported yet!");
+			_error2_("analysis_type: " << EnumToStringx(analysis_type) << " not supported yet!");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../io/io.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 12878)
@@ -23,5 +23,5 @@
 	int    numberofelements;
 	int    numberofvertices;
-	double* elements=NULL;
+	IssmDouble* elements=NULL;
 
 	/*output*/
@@ -43,5 +43,5 @@
 
 	/*Allocate ouput*/
-	connectivity=(int*)xcalloc(numberofvertices,sizeof(int));
+	connectivity=xNewZeroInit<int>(numberofvertices);
 
 	/*Get element width (3 or 6)*/
@@ -56,5 +56,5 @@
 	for (i=0;i<numberofelements;i++){
 		for (j=0;j<elementswidth;j++){
-			vertexid=(int)elements[elementswidth*i+j];
+			vertexid=reCast<int>(elements[elementswidth*i+j]);
 			_assert_(vertexid>0 && vertexid-1<numberofvertices);
 			connectivity[vertexid-1]+=1;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 12878)
@@ -13,5 +13,5 @@
 #include "../../toolkits/toolkits.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../MeshPartitionx/MeshPartitionx.h"
@@ -24,6 +24,7 @@
 	int         numoutputs;
 	Parameters *parameters       = NULL;
-	double     *requestedoutputs = NULL;
-	
+	IssmDouble *requestedoutputs = NULL;
+	bool        isdelta18o;
+
 	if(*pparameters)return; //do not create parameters twice!
 
@@ -57,5 +58,5 @@
 	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyFactorEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsLowmemEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(DebugPetscProfilingEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(DebugProfilingEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(MeshAverageVertexConnectivityEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(ConstantsReferencetemperatureEnum));
@@ -89,4 +90,26 @@
 	parameters->AddObject(iomodel->CopyConstantObject(InversionIscontrolEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(InversionTaoEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsIspddEnum));
+	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));
+		xDelete<IssmDouble>(temp);
+
+		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));
+		xDelete<IssmDouble>(temp);
+	}
 
 	/*some parameters that did not come with the iomodel: */
@@ -104,13 +127,13 @@
 	parameters->AddObject(new IntParam(DiagnosticNumRequestedOutputsEnum,numoutputs));
 	if(numoutputs)parameters->AddObject(new IntVecParam(DiagnosticRequestedOutputsEnum,requestedoutputs,numoutputs));
-	xfree((void**)&requestedoutputs);
+	xDelete<IssmDouble>(requestedoutputs);
 	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,TransientRequestedOutputsEnum);
 	parameters->AddObject(new IntParam(TransientNumRequestedOutputsEnum,numoutputs));
 	if(numoutputs)parameters->AddObject(new IntVecParam(TransientRequestedOutputsEnum,requestedoutputs,numoutputs));
-	xfree((void**)&requestedoutputs);
+	xDelete<IssmDouble>(requestedoutputs);
 	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,SteadystateRequestedOutputsEnum);
 	parameters->AddObject(new IntParam(SteadystateNumRequestedOutputsEnum,numoutputs));
 	if(numoutputs)parameters->AddObject(new IntVecParam(SteadystateRequestedOutputsEnum,requestedoutputs,numoutputs));
-	xfree((void**)&requestedoutputs);
+	xDelete<IssmDouble>(requestedoutputs);
 	
 	/*Before returning, create parameters in case we are running Qmu or control types runs: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp	(revision 12878)
@@ -23,5 +23,5 @@
 	int    numberofelements;
 	int    numberofvertices;
-	double* elements=NULL;
+	IssmDouble* elements=NULL;
 
 	/*output*/
@@ -44,5 +44,5 @@
 
 	/*Allocate ouput*/
-	connectivity=(int*)xcalloc(numberofvertices,sizeof(int));
+	connectivity=xNewZeroInit<int>(numberofvertices);
 
 	/*Get element width (3 or 6)*/
@@ -59,5 +59,5 @@
 		if(iomodel->my_elements[i]){
 			for (j=0;j<elementswidth;j++){
-				vertexid=(int)elements[elementswidth*i+j];
+				vertexid=reCast<int>(elements[elementswidth*i+j]);
 				_assert_(vertexid>0 && vertexid-1<numberofvertices);
 				connectivity[vertexid-1]=i+1;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../toolkits/toolkits.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../io/io.h"
@@ -15,5 +15,5 @@
 void CreateParametersDakota(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
 
-	/*variable declarations: {{{1*/
+	/*variable declarations: {{{*/
 	int i,j,k;
 	
@@ -73,18 +73,18 @@
 		iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 
-		/*name of qmu input, error and output files:{{{1*/
-		qmuinname=(char*)xmalloc((strlen(name)+strlen(".qmu.in")+1)*sizeof(char));
+		/*name of qmu input, error and output files:{{{*/
+		qmuinname=xNew<char>((strlen(name)+strlen(".qmu.in")+1));
 		sprintf(qmuinname,"%s%s",name,".qmu.in");
 		parameters->AddObject(new   StringParam(QmuInNameEnum,qmuinname));
 
-		qmuoutname=(char*)xmalloc((strlen(name)+strlen(".qmu.out")+1)*sizeof(char));
+		qmuoutname=xNew<char>((strlen(name)+strlen(".qmu.out")+1));
 		sprintf(qmuoutname,"%s%s",name,".qmu.out");
 		parameters->AddObject(new   StringParam(QmuOutNameEnum,qmuoutname));
 
-		qmuerrname=(char*)xmalloc((strlen(name)+strlen(".qmu.err")+1)*sizeof(char));
+		qmuerrname=xNew<char>((strlen(name)+strlen(".qmu.err")+1));
 		sprintf(qmuerrname,"%s%s",name,".qmu.err");
 		parameters->AddObject(new   StringParam(QmuErrNameEnum,qmuerrname));
 		/*}}}*/
-		/*Fetch variable descriptors: {{{1*/
+		/*Fetch variable descriptors: {{{*/
 		iomodel->FetchData(&variabledescriptors,&numvariabledescriptors,QmuVariabledescriptorsEnum);
 
@@ -93,5 +93,5 @@
 
 		/*}}}*/
-		/*Fetch response descriptors: {{{1*/
+		/*Fetch response descriptors: {{{*/
 		iomodel->FetchData(&responsedescriptors,&numresponsedescriptors,QmuResponsedescriptorsEnum);
 
@@ -100,5 +100,5 @@
 		parameters->AddObject(new    IntParam(QmuNumberofresponsesEnum,numberofresponses));
 		/*}}}*/
-		/*Deal with partitioning: {{{1*/
+		/*Deal with partitioning: {{{*/
 		/*partition vertices in iomodel->qmu_npart parts, unless a partition is already present: */
 		
@@ -111,10 +111,10 @@
 			ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
 
-			dpart=(double*)xmalloc(numberofvertices*sizeof(double));
+			dpart=xNew<double>(numberofvertices);
 			for(i=0;i<numberofvertices;i++)dpart[i]=iomodel->my_vertices[i];
 		}
 		parameters->AddObject(new DoubleVecParam(QmuPartitionEnum,dpart,numberofvertices));
 		/*}}}*/
-		/*Deal with data needed because of qmu variables: {{{1*/
+		/*Deal with data needed because of qmu variables: {{{*/
 		
 		for(i=0;i<numvariabledescriptors;i++){
@@ -136,9 +136,9 @@
 				
 				/*Free ressources:*/
-				xfree((void**)&dakota_parameter);
-			}
-		}
-		/*}}}*/
-		/*Deal with data needed to compute qmu responses: {{{1*/
+				xDelete<double>(dakota_parameter);
+			}
+		}
+		/*}}}*/
+		/*Deal with data needed to compute qmu responses: {{{*/
 		for(i=0;i<numresponsedescriptors;i++){
 			
@@ -153,5 +153,5 @@
 			/*Fetch the mass flux segments necessary to compute the mass fluxes.  Build a DoubleMatArrayParam object out of them: */ 
 			iomodel->FetchData(&array,&mdims_array,&ndims_array,&qmu_mass_flux_num_profiles,QmuMassFluxSegmentsEnum);
-			if(qmu_mass_flux_num_profiles==0)_error_(" qmu_mass_flux_num_profiles is 0, when MassFlux computations were requested!");
+			if(qmu_mass_flux_num_profiles==0)_error2_("qmu_mass_flux_num_profiles is 0, when MassFlux computations were requested!");
 
 			/*Go through segments, and extract those that belong to this cpu: */
@@ -166,5 +166,5 @@
 				}
 				if(m){
-					matrix=(double*)xcalloc(5*m,sizeof(double));
+					matrix=xNewZeroInit<double>(5*m);
 					count=0;
 					for(j=0;j<temp_m;j++){
@@ -185,5 +185,5 @@
 
 				/*Free temporary matrix: */
-				xfree((void**)&temp_matrix);
+				xDelete<double>(temp_matrix);
 			}
 
@@ -194,33 +194,33 @@
 			for(i=0;i<qmu_mass_flux_num_profiles;i++){
 				double* matrix=array[i];
-				xfree((void**)&matrix);
-			}
-			xfree((void**)&mdims_array); 
-			xfree((void**)&ndims_array);
-			xfree((void**)&array);
-		}
-		/*}}}*/
-		/*Free data: {{{1*/
+				xDelete<double>(matrix);
+			}
+			xDelete<int>(mdims_array); 
+			xDelete<int>(ndims_array);
+			xDelete<double*>(array);
+		}
+		/*}}}*/
+		/*Free data: {{{*/
 		for(i=0;i<numresponsedescriptors;i++){
 			descriptor=responsedescriptors[i];
-			xfree((void**)&descriptor);
-		}
-		xfree((void**)&responsedescriptors);
+			xDelete<char>(descriptor);
+		}
+		xDelete<char*>(responsedescriptors);
 
 		for(i=0;i<numvariabledescriptors;i++){
 			descriptor=variabledescriptors[i];
-			xfree((void**)&descriptor);
-		}
-		xfree((void**)&variabledescriptors);
-		xfree((void**)&part);
-		xfree((void**)&dpart);
-		xfree((void**)&qmuinname);
-		xfree((void**)&qmuerrname);
-		xfree((void**)&qmuoutname);
+			xDelete<char>(descriptor);
+		}
+		xDelete<char*>(variabledescriptors);
+		xDelete<int>(part);
+		xDelete<double>(dpart);
+		xDelete<char>(qmuinname);
+		xDelete<char>(qmuerrname);
+		xDelete<char>(qmuoutname);
 		/*}}}*/
 	} //if(dakota_analysis)
 
 	/*Free data*/
-	xfree((void**)&name);
+	xDelete<char>(name);
 
 	/*Assign output pointer: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
@@ -87,5 +87,5 @@
 
 	/*figure out times: */
-	timesx=(double*)xmalloc(Nx*sizeof(double));
+	timesx=xNew<double>(Nx);
 	for(j=0;j<Nx;j++){
 		timesx[j]=spcvx[(Mx-1)*Nx+j];
@@ -94,5 +94,5 @@
 	UnitConversion(timesx,Nx,ExtToIuEnum,TimeEnum);
 	/*figure out times: */
-	timesy=(double*)xmalloc(Ny*sizeof(double));
+	timesy=xNew<double>(Ny);
 	for(j=0;j<Ny;j++){
 		timesy[j]=spcvy[(My-1)*Ny+j];
@@ -101,5 +101,5 @@
 	UnitConversion(timesy,Ny,ExtToIuEnum,TimeEnum);
 	/*figure out times: */
-	timesz=(double*)xmalloc(Nz*sizeof(double));
+	timesz=xNew<double>(Nz);
 	for(j=0;j<Nz;j++){
 		timesz[j]=spcvz[(Mz-1)*Nz+j];
@@ -107,5 +107,4 @@
 	/*unit conversion: */
 	UnitConversion(timesz,Nz,ExtToIuEnum,TimeEnum);
-
 
 	/*Create spcs from x,y,z, as well as the spc values on those spcs: */
@@ -121,9 +120,9 @@
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
-						if (!isnan(spcvx[i])){
+						if (!xIsNan<IssmDouble>(spcvx[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
 						}
-						if (!isnan(spcvy[i])){
+						if (!xIsNan<IssmDouble>(spcvy[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
@@ -136,9 +135,9 @@
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
-						if (!isnan(spcvx[i])){
+						if (!xIsNan<IssmDouble>(spcvx[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
 						}
-						if (!isnan(spcvy[i])){
+						if (!xIsNan<IssmDouble>(spcvy[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
@@ -146,5 +145,5 @@
 
 					}
-					else _error_("if vertices_type is MacAyealPattyn, you shoud have nodeonpattyn or nodeonmacayeal");
+					else _error2_("if vertices_type is MacAyealPattyn, you shoud have nodeonpattyn or nodeonmacayeal");
 			}
 			/*Also add spcs of coupling: zero at the border pattyn/stokes for the appropriate dofs*/
@@ -158,9 +157,9 @@
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
-						if (!isnan(spcvx[i])){
+						if (!xIsNan<IssmDouble>(spcvx[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
 						}
-						if (!isnan(spcvy[i])){
+						if (!xIsNan<IssmDouble>(spcvy[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
@@ -173,18 +172,18 @@
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
-						if (!isnan(spcvx[i])){
+						if (!xIsNan<IssmDouble>(spcvx[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
 						}
-						if (!isnan(spcvy[i])){
+						if (!xIsNan<IssmDouble>(spcvy[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
 						}
-						if (!isnan(spcvz[i])){
+						if (!xIsNan<IssmDouble>(spcvz[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,spcvz[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
 						}
 					}
-					else _error_("if vertices_type is PattynStokes, you shoud have nodeonpattyn or nodeonstokes");
+					else _error2_("if vertices_type is PattynStokes, you shoud have nodeonpattyn or nodeonstokes");
 			}
 			/*Also add spcs of coupling: zero at the border pattyn/stokes for the appropriate dofs*/
@@ -198,9 +197,9 @@
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
-						if (!isnan(spcvx[i])){
+						if (!xIsNan<IssmDouble>(spcvx[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
 						}
-						if (!isnan(spcvy[i])){
+						if (!xIsNan<IssmDouble>(spcvy[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
@@ -213,22 +212,22 @@
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
-						if (!isnan(spcvx[i])){
+						if (!xIsNan<IssmDouble>(spcvx[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
 						}
-						if (!isnan(spcvy[i])){
+						if (!xIsNan<IssmDouble>(spcvy[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
 						}
-						if (!isnan(spcvz[i])){
+						if (!xIsNan<IssmDouble>(spcvz[i])){
 							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,spcvz[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 							count++;
 						}
 					}
-					else _error_("if vertices_type is MacAyealStokes, you shoud have nodeonmacayeal or nodeonstokes");
+					else _error2_("if vertices_type is MacAyealStokes, you shoud have nodeonmacayeal or nodeonstokes");
 			}
 			/*Now add the regular spcs*/
 			else{
-				if (Mx==numberofvertices && !isnan(spcvx[i])){
+				if (Mx==numberofvertices && !xIsNan<IssmDouble>(spcvx[i])){
 					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvx[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 					count++;
@@ -236,9 +235,9 @@
 				else if (Mx==numberofvertices+1) {
 					/*figure out times and values: */
-					values=(double*)xmalloc(Nx*sizeof(double));
+					values=xNew<double>(Nx);
 					spcpresent=false;
 					for(j=0;j<Nx;j++){
 						values[j]=spcvx[i*Nx+j]/yts;
-						if(!isnan(values[j]))spcpresent=true; //NaN means no spc by default
+						if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
 					}
 
@@ -247,5 +246,5 @@
 						count++;
 					}
-					xfree((void**)&values);
+					xDelete<double>(values);
 				}
 				else if (vertices_type[i]==HutterApproximationEnum){
@@ -254,5 +253,5 @@
 				}
 
-				if (My==numberofvertices && !isnan(spcvy[i])){
+				if (My==numberofvertices && !xIsNan<IssmDouble>(spcvy[i])){
 					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvy[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vy.
 					count++;
@@ -260,9 +259,9 @@
 				else if (My==numberofvertices+1){
 					/*figure out times and values: */
-					values=(double*)xmalloc(Ny*sizeof(double));
+					values=xNew<double>(Ny);
 					spcpresent=false;
 					for(j=0;j<Ny;j++){
 						values[j]=spcvy[i*Ny+j]/yts;
-						if(!isnan(values[j]))spcpresent=true; //NaN means no spc by default
+						if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
 					}
 					if(spcpresent){
@@ -270,5 +269,5 @@
 						count++;
 					}
-					xfree((void**)&values);
+					xDelete<double>(values);
 				}
 				else if (vertices_type[i]==HutterApproximationEnum){
@@ -278,5 +277,5 @@
 
 				if ((int)vertices_type[i]==StokesApproximationEnum ||  ((int)vertices_type[i]==NoneApproximationEnum)){
-					if (Mz==numberofvertices && !isnan(spcvz[i])){
+					if (Mz==numberofvertices && !xIsNan<IssmDouble>(spcvz[i])){
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvz[i]/yts,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
 						count++;
@@ -284,9 +283,9 @@
 					else if (Mz==numberofvertices+1){
 						/*figure out times and values: */
-						values=(double*)xmalloc(Nz*sizeof(double));
+						values=xNew<double>(Nz);
 						spcpresent=false;
 						for(j=0;j<Nz;j++){
 							values[j]=spcvz[i*Nz+j]/yts;
-							if(!isnan(values[j]))spcpresent=true; //NaN means no spc by default
+							if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
 						}
 						if(spcpresent){
@@ -294,5 +293,5 @@
 							count++;
 						}
-						xfree((void**)&values);
+						xDelete<double>(values);
 					}
 
@@ -319,5 +318,5 @@
 						count++;
 						break;
-					default: _error_("Vertex approximation %s not supported",EnumToStringx((int)vertices_type[i]));
+					default: _error2_("Vertex approximation " << EnumToStringx((int)vertices_type[i]) << " not supported");
 				}
 			}
@@ -326,21 +325,21 @@
 	  
 	/*Free data: */
-	xfree((void**)&spcvx);
-	xfree((void**)&spcvy);
-	xfree((void**)&spcvz);
-	xfree((void**)&nodeonmacayeal);
-	xfree((void**)&nodeonpattyn);
-	xfree((void**)&nodeonstokes);
-	xfree((void**)&nodeonicesheet);
-	xfree((void**)&nodeonbed);
-	xfree((void**)&vertices_type);
-	xfree((void**)&surface);
-	xfree((void**)&z);
+	xDelete<double>(spcvx);
+	xDelete<double>(spcvy);
+	xDelete<double>(spcvz);
+	xDelete<double>(nodeonmacayeal);
+	xDelete<double>(nodeonpattyn);
+	xDelete<double>(nodeonstokes);
+	xDelete<double>(nodeonicesheet);
+	xDelete<double>(nodeonbed);
+	xDelete<double>(vertices_type);
+	xDelete<double>(surface);
+	xDelete<double>(z);
 
 	/*Free resources:*/
-	xfree((void**)&timesx);
-	xfree((void**)&timesy);
-	xfree((void**)&timesz);
-	xfree((void**)&values);
+	xDelete<double>(timesx);
+	xDelete<double>(timesy);
+	xDelete<double>(timesz);
+	xDelete<double>(values);
 
 	/*Assign output pointer: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
@@ -120,6 +120,6 @@
 	/*Free data: */
 	iomodel->DeleteData(3,DiagnosticIcefrontEnum,ThicknessEnum,BedEnum);
-	xfree((void**)&elements_type);
-	xfree((void**)&pressureload);
+	xDelete<double>(elements_type);
+	xDelete<double>(pressureload);
 
 	/*Create Penpair for penalties: */
@@ -144,5 +144,5 @@
 
 	/*free ressources: */
-	xfree((void**)&penalties);
+	xDelete<double>(penalties);
 
 	/*Create Riffront loads for rifts: */
@@ -157,5 +157,5 @@
 		}
 		iomodel->DeleteData(5,RiftsRiftstructEnum,ThicknessEnum,BedEnum,SurfaceEnum,MaskVertexonfloatingiceEnum);
-		xfree((void**)&riftfront);
+		xDelete<Riftfront>(riftfront);
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
@@ -60,10 +60,10 @@
 			}
 			else{
-				if (!isnan(iomodel->Data(DiagnosticSpcvxEnum)[i])){
+				if (!xIsNan<IssmDouble>(iomodel->Data(DiagnosticSpcvxEnum)[i])){
 					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,iomodel->Data(DiagnosticSpcvxEnum)[i]/yts,DiagnosticHutterAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 					count++;
 				}
 
-				if (!isnan(iomodel->Data(DiagnosticSpcvyEnum)[i])){
+				if (!xIsNan<IssmDouble>(iomodel->Data(DiagnosticSpcvyEnum)[i])){
 					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,iomodel->Data(DiagnosticSpcvyEnum)[i]/yts,DiagnosticHutterAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
 					count++;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../modules/modules.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
@@ -56,5 +56,5 @@
 				count++;
 			}
-			else if (!isnan(iomodel->Data(DiagnosticSpcvzEnum)[i])){
+			else if (!xIsNan<IssmDouble>(iomodel->Data(DiagnosticSpcvzEnum)[i])){
 				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,
 								iomodel->Data(DiagnosticSpcvzEnum)[i]/yts,DiagnosticVertAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../modules/modules.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 	
-void DistributeNumDofs(DofIndexing* index,int analysis_type,double* vertices_type){
+void DistributeNumDofs(DofIndexing* index,int analysis_type,IssmDouble* vertices_type){
 
 	/*For now, we distribute by analysis_type, later, we will distribute using the analysis_type,
@@ -35,5 +35,5 @@
 		else if (vertices_type[0]==MacAyealPattynApproximationEnum){
 			numdofs=4;
-			doftype=(int*)xmalloc(numdofs*sizeof(int));
+			doftype=xNew<int>(numdofs);
 			doftype[0]=MacAyealApproximationEnum;
 			doftype[1]=MacAyealApproximationEnum;
@@ -43,5 +43,5 @@
 		else if (vertices_type[0]==PattynStokesApproximationEnum){
 			numdofs=6;
-			doftype=(int*)xmalloc(numdofs*sizeof(int));
+			doftype=xNew<int>(numdofs);
 			doftype[0]=PattynApproximationEnum;
 			doftype[1]=PattynApproximationEnum;
@@ -53,5 +53,5 @@
 		else if (vertices_type[0]==MacAyealStokesApproximationEnum){
 			numdofs=6;
-			doftype=(int*)xmalloc(numdofs*sizeof(int));
+			doftype=xNew<int>(numdofs);
 			doftype[0]=MacAyealApproximationEnum;
 			doftype[1]=MacAyealApproximationEnum;
@@ -61,5 +61,5 @@
 			doftype[5]=StokesApproximationEnum;
 		}
-		else _error_("Approximationtype %i (%s) not implemented yet for DiagnosticHoriz",(int)*vertices_type,EnumToStringx((int)*vertices_type));
+		else _error2_("Approximationtype " << reCast<int>(*vertices_type) << " (" << EnumToStringx(reCast<int>(*vertices_type)) << ") not implemented yet for DiagnosticHoriz");
 	}
 	else if (analysis_type==DiagnosticVertAnalysisEnum){
@@ -90,5 +90,5 @@
 		numdofs=1;
 	}
-	else _error_("analysis type: %i (%s) not implemented yet",analysis_type,EnumToStringx(analysis_type));
+	else _error2_("analysis type: " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not implemented yet");
 
 	/*Now initialize the index*/
@@ -96,4 +96,4 @@
 
 	/*Clean up*/
-	 xfree((void**)&doftype);
+	 xDelete<int>(doftype);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 12878)
@@ -10,5 +10,5 @@
 
 #include <string.h>
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
@@ -42,8 +42,8 @@
 	int  el1,el2;
 	int    dim;
-	double* elements=NULL;
-	double* elements2d=NULL;
-	double* riftinfo=NULL;
-	double* vertex_pairing=NULL;
+	IssmDouble* elements=NULL;
+	IssmDouble* elements2d=NULL;
+	IssmDouble* riftinfo=NULL;
+	IssmDouble* vertex_pairing=NULL;
 
 	/*Fetch parameters: */
@@ -76,6 +76,6 @@
 
 	/*Free elements and elements2d: */
-	xfree((void**)&elements);
-	xfree((void**)&elements2d);
+	xDelete<IssmDouble>(elements);
+	xDelete<IssmDouble>(elements2d);
 
 	/*Deal with rifts, they have to be included into one partition only, not several: */
@@ -83,14 +83,14 @@
 		iomodel->FetchData(&riftinfo,&numrifts,NULL,RiftsRiftstructEnum);
 		for(i=0;i<numrifts;i++){
-			el1=(int)*(riftinfo+RIFTINFOSIZE*i+2)-1; //matlab indexing to c indexing
-			el2=(int)*(riftinfo+RIFTINFOSIZE*i+3)-1; //matlab indexing to c indexing
+			el1=reCast<int>(*(riftinfo+RIFTINFOSIZE*i+2))-1; //matlab indexing to c indexing
+			el2=reCast<int>(*(riftinfo+RIFTINFOSIZE*i+3))-1; //matlab indexing to c indexing
 			epart[el2]=epart[el1]; //ensures that this pair of elements will be in the same partition, as well as the corresponding vertices;
 		}
-		xfree((void**)&riftinfo); 
+		xDelete<IssmDouble>(riftinfo); 
 	}
 
 	/*Used later on: */
-	my_vertices=(int*)xcalloc(numberofvertices,sizeof(int));
-	my_elements=(bool*)xcalloc(numberofelements,sizeof(bool));
+	my_vertices=xNewZeroInit<int>(numberofvertices);
+	my_elements=xNewZeroInit<bool>(numberofelements);
 
 	/*Start figuring out, out of the partition, which elements belong to this cpu: */
@@ -107,17 +107,17 @@
 			 into the vertices coordinates. If we start plugging 1 into my_vertices for each index[n][i] (i=0:2), then my_vertices 
 			 will hold which vertices belong to this partition*/
-			my_vertices[(int)*(elements+elements_width*i+0)-1]=1;
-			my_vertices[(int)*(elements+elements_width*i+1)-1]=1;
-			my_vertices[(int)*(elements+elements_width*i+2)-1]=1;
+			my_vertices[reCast<int>(*(elements+elements_width*i+0))-1]=1;
+			my_vertices[reCast<int>(*(elements+elements_width*i+1))-1]=1;
+			my_vertices[reCast<int>(*(elements+elements_width*i+2))-1]=1;
 			
 			if(elements_width==6){
-				my_vertices[(int)*(elements+elements_width*i+3)-1]=1;
-				my_vertices[(int)*(elements+elements_width*i+4)-1]=1;
-				my_vertices[(int)*(elements+elements_width*i+5)-1]=1;
+				my_vertices[reCast<int>(*(elements+elements_width*i+3))-1]=1;
+				my_vertices[reCast<int>(*(elements+elements_width*i+4))-1]=1;
+				my_vertices[reCast<int>(*(elements+elements_width*i+5))-1]=1;
 			}
 		}
 	}//for (i=0;i<numberofelements;i++)
 	/*Free data : */
-	xfree((void**)&elements);
+	xDelete<IssmDouble>(elements);
 
 	/*We might have vertex_pairing in which case, some vertices have to be cloned:
@@ -126,20 +126,20 @@
 	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,DiagnosticVertexPairingEnum);
 	for(i=0;i<numvertex_pairing;i++){
-		if(my_vertices[(int)vertex_pairing[2*i+0]-1] && !my_vertices[(int)vertex_pairing[2*i+1]-1]){
-			my_vertices[(int)vertex_pairing[2*i+1]-1]=2; //to know that these elements are not on the partition
+		if(my_vertices[reCast<int>(vertex_pairing[2*i+0])-1] && !my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]){
+			my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]=2; //to know that these elements are not on the partition
 		}
 	}
-	xfree((void**)&vertex_pairing);
+	xDelete<IssmDouble>(vertex_pairing);
 	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,PrognosticVertexPairingEnum);
 	for(i=0;i<numvertex_pairing;i++){
-		if(my_vertices[(int)vertex_pairing[2*i+0]-1] && !my_vertices[(int)vertex_pairing[2*i+1]-1]){
-			my_vertices[(int)vertex_pairing[2*i+1]-1]=2; //to know that these elements are not on the partition
+		if(my_vertices[reCast<int>(vertex_pairing[2*i+0])-1] && !my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]){
+			my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]=2; //to know that these elements are not on the partition
 		}
 	}
-	xfree((void**)&vertex_pairing);
+	xDelete<IssmDouble>(vertex_pairing);
 
 	/*Free ressources:*/
-	xfree((void**)&npart);
-	xfree((void**)&epart);
+	xDelete<int>(npart);
+	xDelete<int>(epart);
 
 	/*Assign output pointers:*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 12878)
@@ -7,6 +7,7 @@
 #include "../../../toolkits/toolkits.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
+#include "../../../include/include.h"
 #include "../ModelProcessorx.h"
 
@@ -14,14 +15,18 @@
 
 	/*Intermediary*/
-	int i;
-	int count;
+	int    i,j;
+	int    count;
 	int    dim;
+	int    M,N;
 	int    numberofvertices;
+	bool   spcpresent=false;
 	double heatcapacity;
 	double referencetemperature;
 	
 	/*Output*/
+	IssmDouble *spcvector  = NULL;
+	IssmDouble* times=NULL;
+	IssmDouble* values=NULL;
 	Constraints* constraints = NULL;
-	SpcStatic*    spcstatic  = NULL;
 
 	/*Fetch parameters: */
@@ -44,27 +49,69 @@
 
 	/*Fetch data: */
-	double *spctemperature=NULL;
-	iomodel->FetchData(&spctemperature,NULL,NULL,ThermalSpctemperatureEnum);
+	iomodel->FetchData(&spcvector,&M,&N,ThermalSpctemperatureEnum);
 
-	/*Initialize counter*/
-	count=0;
+	//FIX ME: SHOULD USE IOMODELCREATECONSTRAINTS 
+	/*Transient or static?:*/
+	if(M==numberofvertices){
+		/*static: just create Constraints objects*/
+		count=0;
 
-	/*Create constraints from x,y,z: */
-	for (i=0;i<numberofvertices;i++){
-		/*keep only this partition's nodes:*/
-		if((iomodel->my_vertices[i])){
+		for (i=0;i<numberofvertices;i++){
+			/*keep only this partition's nodes:*/
+			if((iomodel->my_vertices[i])){
 
-			if (!isnan(spctemperature[i])){
+				if (!xIsNan<IssmDouble>(spcvector[i])){
 
-				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,heatcapacity*(spctemperature[i]-referencetemperature),EnthalpyAnalysisEnum));
-				count++;
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,heatcapacity*(spcvector[i]-referencetemperature),EnthalpyAnalysisEnum));
+					count++;
 
+				}
 			}
 		}
 	}
+	else if (M==(numberofvertices+1)){
+		/*transient: create transient SpcTransient objects. Same logic, except we need to retrieve 
+		 * various times and values to initialize an SpcTransient object: */
+		count=0;
 
-	/*Free data: */
-	xfree((void**)&spctemperature);
-	
+		/*figure out times: */
+		times=xNew<IssmDouble>(N);
+		for(j=0;j<N;j++){
+			times[j]=spcvector[(M-1)*N+j];
+		}
+		/*unit conversion: */
+		UnitConversion(times,N,ExtToIuEnum,TimeEnum);
+
+		/*Create constraints from x,y,z: */
+		for (i=0;i<numberofvertices;i++){
+			
+			/*keep only this partition's nodes:*/
+			if((iomodel->my_vertices[i])){
+
+				/*figure out times and values: */
+				values=xNew<IssmDouble>(N);
+				spcpresent=false;
+				for(j=0;j<N;j++){
+					values[j]=heatcapacity*(spcvector[i*N+j]-referencetemperature);
+					if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+				}
+
+				if(spcpresent){
+					constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,N,times,values,EnthalpyAnalysisEnum));
+					count++;
+				}
+				xDelete<IssmDouble>(values);
+			}
+		}
+	}
+	else{
+		_error2_("Size of field " << EnumToStringx(ThermalSpctemperatureEnum) << " not supported");
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(spcvector);
+	xDelete<IssmDouble>(times);
+	xDelete<IssmDouble>(values);
+
 	/*Assign output pointer: */
 	*pconstraints=constraints;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../include/include.h"
 #include "../../../shared/shared.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../EnumDefinitions/EnumDefinitions.h"
 #include "../../../modules/modules.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../EnumDefinitions/EnumDefinitions.h"
 #include "../../../io/io.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../include/include.h"
 #include "../../../shared/shared.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../modules/modules.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../toolkits/toolkits.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
@@ -26,5 +26,5 @@
 
 	/*if 2d: Error*/
-	if (dim==2) _error_("2d meshes not supported yet");
+	if (dim==2) _error2_("2d meshes not supported yet");
 
 	/*Recover pointer: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../EnumDefinitions/EnumDefinitions.h"
 #include "../../../include/include.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/ModelProcessorx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 12878)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../../io/io.h"
@@ -68,5 +68,5 @@
 		if(solution_type==SteadystateSolutionEnum && analysis_type==EnthalpyAnalysisEnum && isenthalpy==false) continue;
 	
-		_printf_(VerboseMProcessor(),"   creating datasets for analysis %s\n",EnumToStringx(analysis_type));
+		if(VerboseMProcessor()) _pprintLine_("   creating datasets for analysis " << EnumToStringx(analysis_type));
 		CreateDataSets(&elements,&nodes,&vertices,&materials,&constraints,&loads,&parameters,iomodel,solution_type,analysis_type,nummodels,i);
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/ModelProcessorx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 12878)
@@ -108,5 +108,5 @@
 
 /*Distribution of dofs: */
-void DistributeNumDofs(DofIndexing* index,int analysis_type,double* vertices_type);
+void DistributeNumDofs(DofIndexing* index,int analysis_type,IssmDouble* vertices_type);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/NodesPartitioning.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 12878)
@@ -10,5 +10,5 @@
 
 #include <string.h>
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
@@ -24,5 +24,5 @@
 	
 	/*First thing, this is a new partition for a new analysis_type, therefore, to avoid a leak, erase the nodes partition that might come through pmy_nodes: */
-	xfree((void**)pmy_nodes);
+	xDelete<bool>(*pmy_nodes);
 
 	/*Now, depending on whether we are running galerkin discontinous or continuous elements, carry out a different partition of the nodes: */
@@ -44,6 +44,6 @@
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 
-	my_nodes=(bool*)xmalloc(numberofvertices*sizeof(bool));
-	memcpy(my_nodes,my_vertices,numberofvertices*sizeof(bool));
+	my_nodes=xNew<bool>(numberofvertices);
+	for(int i=0;i<numberofvertices;i++) my_nodes[i]=(bool)my_vertices[i];
 
 	/*Assign output pointers:*/
@@ -69,11 +69,11 @@
 	bool*   my_nodes=NULL;
 
-	int     i1,i2;
-	int     cols;
-	double  e1,e2;
-	int     pos;
-	int     numberofedges;
-	double* edges=NULL;
-	double* elements=NULL;
+	int  i1,i2;
+	int  cols;
+	int  e1,e2;
+	int  pos;
+	int  numberofedges;
+	int *edges         = NULL;
+	int *elements      = NULL;
 
 	/*Fetch parameters: */
@@ -90,5 +90,5 @@
 
 	/*Allocate*/
-	my_nodes=(bool*)xcalloc(3*numberofelements,sizeof(int));
+	my_nodes=xNewZeroInit<bool>(3*numberofelements);
 
 	/*First: add all the nodes of all the elements belonging to this cpu*/
@@ -96,12 +96,12 @@
 		for (i=0;i<numberofelements;i++){
 			if (my_elements[i]){
-				my_nodes[3*i+0]=1;
-				my_nodes[3*i+1]=1;
-				my_nodes[3*i+2]=1;
+				my_nodes[3*i+0]=true;
+				my_nodes[3*i+1]=true;
+				my_nodes[3*i+2]=true;
 			}
 		}
 	}
 	else{
-		_error_("not implemented yet");
+		_error2_("not implemented yet");
 	}
 
@@ -111,5 +111,5 @@
 	iomodel->FetchData(&edges,&numberofedges,&cols,MeshEdgesEnum);
 	iomodel->FetchData(&elements,NULL,NULL,MeshElementsEnum);
-	if (cols!=4) _error_("field edges should have 4 columns");
+	if (cols!=4) _error2_("field edges should have 4 columns");
 
 	/*!All elements have been partitioned above, only create elements for this CPU: */
@@ -125,14 +125,14 @@
 		 * we must clone the nodes on this partition so that the loads (Numericalflux)
 		 * will have access to their properties (dofs,...)*/
-		if(my_elements[(int)e1] && !isnan(e2) && !my_elements[(int)e2]){ 
+		if(my_elements[e1] && e2!=-2 && !my_elements[e2]){
 
 			/*1: Get vertices ids*/
-			i1=(int)edges[4*i+0];
-			i2=(int)edges[4*i+1];
+			i1=edges[4*i+0];
+			i2=edges[4*i+1];
 
 			/*2: Get the column where these ids are located in the index*/
 			pos=UNDEF;
 			for(j=0;j<3;j++){
-				if ((int)elements[3*(int)e2+j]==i1) pos=j;
+				if (elements[3*e2+j]==i1) pos=j;
 			}
 
@@ -140,17 +140,17 @@
 			 * we can now create the corresponding nodes:*/
 			if (pos==0){
-				my_nodes[(int)e2*3+0]=1;
-				my_nodes[(int)e2*3+2]=1;
+				my_nodes[e2*3+0]=true;
+				my_nodes[e2*3+2]=true;
 			}
 			else if(pos==1){
-				my_nodes[(int)e2*3+1]=1;
-				my_nodes[(int)e2*3+0]=1;
+				my_nodes[e2*3+1]=true;
+				my_nodes[e2*3+0]=true;
 			}
 			else if (pos==2){
-				my_nodes[(int)e2*3+2]=1;
-				my_nodes[(int)e2*3+1]=1;
+				my_nodes[e2*3+2]=true;
+				my_nodes[e2*3+1]=true;
 			}
 			else{
-				_error_("Problem in edges creation");
+				_error2_("Problem in edges creation");
 			}
 		}
@@ -158,6 +158,6 @@
 
 	/*Free data: */
-	xfree((void**)&elements);
-	xfree((void**)&edges);
+	xDelete<int>(elements);
+	xDelete<int>(edges);
 
 	/*Assign output pointers:*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 #include "../../../EnumDefinitions/EnumDefinitions.h"
 #include "../../../io/io.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
@@ -47,5 +47,5 @@
 
 			/*Get left and right elements*/
-			element=(int)(iomodel->Data(MeshEdgesEnum)[4*i+2])-1; //edges are [node1 node2 elem1 elem2]
+			element=reCast<int>(iomodel->Data(MeshEdgesEnum)[4*i+2])-1; //edges are [node1 node2 elem1 elem2]
 
 			/*Now, if this element is not in the partition, pass: */
@@ -61,6 +61,6 @@
 
 	/*Create Penpair for vertex_pairing: */
-	double *vertex_pairing=NULL;
-	double *nodeonbed=NULL;
+	IssmDouble *vertex_pairing=NULL;
+	IssmDouble *nodeonbed=NULL;
 	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,PrognosticVertexPairingEnum);
 	iomodel->FetchData(&nodeonbed,NULL,NULL,MeshVertexonbedEnum);
@@ -68,15 +68,15 @@
 	for(i=0;i<numvertex_pairing;i++){
 
-		if(iomodel->my_vertices[(int)vertex_pairing[2*i+0]-1]){
+		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
 
 			/*In debugging mode, check that the second node is in the same cpu*/
-			_assert_(iomodel->my_vertices[(int)vertex_pairing[2*i+1]-1]);
+			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
 
 			/*Skip if one of the two is not on the bed*/
-			if(!nodeonbed[(int)vertex_pairing[2*i+0]-1] || !nodeonbed[(int)vertex_pairing[2*i+1]-1]) continue;
+			if(!(reCast<bool>(nodeonbed[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonbed[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
 
 			/*Get node ids*/
-			penpair_ids[0]=iomodel->nodecounter+(int)vertex_pairing[2*i+0];
-			penpair_ids[1]=iomodel->nodecounter+(int)vertex_pairing[2*i+1];
+			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
 
 			/*Create Load*/
@@ -90,7 +90,6 @@
 
 	/*free ressources: */
-	xfree((void**)&vertex_pairing);
-	xfree((void**)&nodeonbed);
-
+	xDelete<IssmDouble>(vertex_pairing);
+	xDelete<IssmDouble>(nodeonbed);
 
 	/*Assign output pointer: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../toolkits/toolkits.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../io/io.h"
@@ -46,5 +46,5 @@
 
 	/*Check in 3d*/
-	if(stabilization==3 && dim==3) _error_("DG 3d not implemented yet");
+	if(stabilization==3 && dim==3) _error2_("DG 3d not implemented yet");
 
 	/*First fetch data: */
@@ -72,5 +72,5 @@
 
 					//Get index of the vertex on which the current node is located
-					vertex_id=(int)*(iomodel->Data(MeshElementsEnum)+3*i+j); //(Matlab indexing)
+					vertex_id=reCast<int>(*(iomodel->Data(MeshElementsEnum)+3*i+j)); //(Matlab indexing)
 					io_index=vertex_id-1;                      //(C indexing)
 					_assert_(vertex_id>0 && vertex_id<=numberofvertices);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
@@ -20,4 +20,8 @@
 	int    stabilization;
 	bool   dakota_analysis;
+	bool   issmbgradients;
+	bool   ispdd;
+	bool   isdelta18o;
+	IssmDouble *size, Delta18oTimeSerie,Delta18oSurfaceTimeSerie ;
 
 	/*Fetch data needed: */
@@ -26,4 +30,7 @@
 	iomodel->Constant(&stabilization,PrognosticStabilizationEnum);
 	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&ispdd,SurfaceforcingsIspddEnum);
+	iomodel->Constant(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+	iomodel->Constant(&issmbgradients,SurfaceforcingsIssmbgradientsEnum);
 	iomodel->FetchData(1,MeshElementsEnum);
 
@@ -44,5 +51,4 @@
 	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
 	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
-	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
 	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateCorrectionEnum);
@@ -66,4 +72,28 @@
 		iomodel->FetchDataToInput(elements,TemperatureEnum);
 	}
+	if(issmbgradients){
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsHcEnum);
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsSmbPosMaxEnum);
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsSmbPosMinEnum);
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsAPosEnum);
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsBPosEnum);
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsANegEnum);
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsBNegEnum);
+	}
+	if(ispdd){
+		iomodel->FetchDataToInput(elements,ThermalSpctemperatureEnum);
+		if(isdelta18o){
+			iomodel->FetchDataToInput(elements,SurfaceforcingsTemperaturesLgmEnum);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsTemperaturesPresentdayEnum);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationsPresentdayEnum);
+		}
+		else{
+			iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationEnum);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsMonthlytemperaturesEnum);
+		}
+	}
+	if(~ispdd & ~issmbgradients){
+		iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	}
 
 	/*Free data: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SortDataSets.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 12878)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../../include/include.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../toolkits/toolkits.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../toolkits/toolkits.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../toolkits/toolkits.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../toolkits/toolkits.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../ModelProcessorx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
@@ -33,5 +33,5 @@
 
 	/*return if 2d mesh*/
-	if (dim==2) _error_("2d meshes not supported yet");
+	if (dim==2) _error2_("2d meshes not supported yet");
 
 	//create penalties for nodes: no node can have a temperature over the melting point
@@ -43,5 +43,5 @@
 		/*keep only this partition's nodes:*/
 		if((iomodel->my_vertices[i]==1)){
-			if (isnan(iomodel->Data(ThermalSpctemperatureEnum)[i])){ //No penalty applied on spc nodes!
+			if (xIsNan<IssmDouble>(iomodel->Data(ThermalSpctemperatureEnum)[i])){ //No penalty applied on spc nodes!
 				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,ThermalAnalysisEnum));
 			}
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../include/include.h"
 #include "../../../shared/shared.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #include "../../../modules/modules.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../objects/objects.h"
+#include "../../../classes/objects/objects.h"
 #include "../../../shared/shared.h"
 #include "../../MeshPartitionx/MeshPartitionx.h"
@@ -15,6 +15,3 @@
 
 void	UpdateElementsTransient(Elements* elements, Parameters* parameters,IoModel* iomodel,int analysis_counter,int analysis_type){
-
-	/*nothing for now: */
-
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/UpdateCounters.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/UpdateCounters.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ModelProcessorx/UpdateCounters.cpp	(revision 12878)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../../include/include.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 12878)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void NodalValuex( double* 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,bool process_units){
 
 	extern int my_rank;
@@ -16,5 +16,5 @@
 	int index;
 	Element* element=NULL;
-	double value;
+	IssmDouble value;
 	int found;
 	int sumfound;
@@ -38,5 +38,5 @@
 	#ifdef _HAVE_MPI_
 	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
-	if(!sumfound)_error_("%s%i%s%s","could not find element with vertex with id",index," to compute nodal value ",EnumToStringx(natureofdataenum));
+	if(!sumfound)_error2_("could not find element with vertex with id" << index << " to compute nodal value " << EnumToStringx(natureofdataenum));
 	#endif
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/NodalValuex/NodalValuex.h	(revision 12878)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void NodalValuex( double* 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,bool process_units);
 
 #endif  /* _NODALVALUEX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 12878)
@@ -37,5 +37,5 @@
 
 	/*Allocate connectivity: */
-	connectivity=(double*)xcalloc(nods*width,sizeof(double));
+	connectivity=xNewZeroInit<double>(nods*width);
 
 	/*Go through all elements, and for each elements, plug into the connectivity, all the nodes. 
@@ -71,5 +71,5 @@
 	 * warn the user to increase the connectivity width: */
 	for(i=0;i<nods;i++){
-		if (*(connectivity+width*i+maxels)>maxels)_error_("%s%g%s"," max connectivity width reached (",*(connectivity+width*i+maxels),")! increase width of connectivity table");
+		if (*(connectivity+width*i+maxels)>maxels)_error2_("max connectivity width reached (" << *(connectivity+width*i+maxels) << ")! increase width of connectivity table");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/NodesDofx/NodesDofx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/NodesDofx/NodesDofx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/NodesDofx/NodesDofx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Orthx/Orthx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Orthx/Orthx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Orthx/Orthx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _ORTHX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../include/include.h"
 #include "../../shared/shared.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/OutputResultsx/OutputResultsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 12878)
@@ -14,7 +14,7 @@
 #include "../../Container/Container.h"
 #include "../../io/io.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 		
-void OutputResultsx(                    Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Results* results){
+void OutputResultsx(Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Results* results){
 
 	extern int  my_rank;
@@ -46,5 +46,5 @@
 		EnumToStringx(&solutiontypestring,solutiontype);
 		results->AddObject(new StringExternalResult(results->Size()+1,SolutionTypeEnum,solutiontypestring,1,0));
-		xfree((void**)&solutiontypestring);
+		xDelete<char>(solutiontypestring);
 	}
 
@@ -68,5 +68,5 @@
 			fid=pfopen(cpu_outputfilename ,"wb");
 		}
-		xfree((void**)&outputfilename);
+		xDelete<char>(outputfilename);
 		
 		/*Add file pointer in parameters for further calls to OutputResultsx: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp	(revision 12878)
@@ -10,4 +10,6 @@
 #error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif
+
+#include <cstring>
 
 #include "./ParsePetscOptionsx.h"
@@ -25,5 +27,5 @@
 
 	/*intermediary: */
-	double* analyses=NULL;
+	IssmDouble* analyses=NULL;
 	char** strings=NULL;
 	int numanalyses;
@@ -46,6 +48,6 @@
 
 		/*Now, allocate analyses and strings: */
-		analyses=(double*)xmalloc(numanalyses*sizeof(double));
-		strings=(char**)xmalloc(numanalyses*sizeof(char*));
+		analyses=xNew<IssmDouble>(numanalyses);
+		strings=xNew<char*>(numanalyses);
 		for(i=0;i<numanalyses;i++)strings[i]=NULL; 
 
@@ -68,6 +70,6 @@
 			to the already existing options*/
 				if(strings[numanalyses-1]==NULL){
-					string=(char*)xmalloc((strlen(line)+1)*sizeof(char)); 
-					memcpy(string,line,(strlen(line)+1)*sizeof(char));
+					string=xNew<char>((strlen(line)+1)); 
+					xMemCpy<char>(string,line,(strlen(line)+1));
 
 					strings[numanalyses-1]=string;
@@ -75,16 +77,16 @@
 				else{
 					string=strings[numanalyses-1];
-					newstring=(char*)xmalloc((strlen(line)+1)*sizeof(char));
-					memcpy(newstring,line,(strlen(line)+1)*sizeof(char));
+					newstring=xNew<char>((strlen(line)+1));
+					xMemCpy<char>(newstring,line,(strlen(line)+1));
 
 					/*concatenate:*/
-					catstring=(char*)xmalloc((strlen(string)+1+strlen(newstring)+1+1)*sizeof(char)); //fit in a space " "
-					memcpy(catstring,string,(strlen(string)+1)*sizeof(char));
+					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;
-					xfree((void**)&newstring);
-					xfree((void**)&string);
+					xDelete<char>(newstring);
+					xDelete<char>(string);
 				}
 			}
@@ -96,6 +98,6 @@
 	MPI_Bcast(&numanalyses,1,MPI_INT,0,MPI_COMM_WORLD);
 	if(my_rank!=0){
-		analyses=(double*)xmalloc(numanalyses*sizeof(double));
-		strings=(char**)xmalloc(numanalyses*sizeof(char*));
+		analyses=xNew<IssmPDouble>(numanalyses);
+		strings=xNew<char*>(numanalyses);
 	}
 	MPI_Bcast(analyses,numanalyses,MPI_DOUBLE,0,MPI_COMM_WORLD);
@@ -104,10 +106,10 @@
 		char* string=strings[i];
 		if(my_rank==0){
-			if(string==NULL) _error_("PETSc options for analysis %s have been declared but were not found",EnumToStringx((int)analyses[i]));
+			if(string==NULL) _error2_("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,MPI_COMM_WORLD);
-		if(my_rank!=0)string=(char*)xmalloc(stringlength);
+		if(my_rank!=0)string=xNew<char>(stringlength);
 		MPI_Bcast(string,stringlength,MPI_CHAR,0,MPI_COMM_WORLD);
 		if(my_rank!=0)strings[i]=string;
@@ -120,8 +122,7 @@
 
 	/*Clean up and return*/
-	for(i=0;i<numanalyses;i++) xfree((void**)&strings[i]);
-	xfree((void**)&strings);
-	xfree((void**)&analyses);
+	for(i=0;i<numanalyses;i++) xDelete<char>(strings[i]);
+	xDelete<char*>(strings);
+	xDelete<IssmDouble>(analyses);
 	return;
 }
-
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h	(revision 12878)
@@ -8,5 +8,5 @@
 
 #include "../../shared/shared.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 12878)
@@ -39,5 +39,5 @@
 
 	/*allocate: */
-	already=(bool*)xcalloc(nods,sizeof(bool));
+	already=xNewZeroInit<bool>(nods);
 
 	/*partition loop across threads: */
@@ -45,10 +45,9 @@
 
 	/*Loop over the nodes*/
-	if (my_thread==0) printf("      loop progress:   %5.2lf %%",0.0);
-
 	for (i=i0;i<i1;i++){
 
 		/*display current iteration*/
-		if (my_thread==0 && fmod((double)i,(double)100)==0) printf("\b\b\b\b\b\b\b%5.2lf %%",(double)i/nods*100*num_threads);
+		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<<"%");
 
 		distance=mindistance+100; //make sure initialization respects min distance criterion.
@@ -70,8 +69,9 @@
 		}
 	}
-	if (my_thread==0) printf("\b\b\b\b\b\b\b%5.2lf %%\n",100.0);
+	if (my_thread==0)
+	 _printLine_("\r      loop progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
 
 	/*Free ressources:*/
-	xfree((void**)&already);
+	xDelete<bool>(already);
 	
 	return NULL;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp	(revision 12878)
@@ -23,27 +23,23 @@
 
   int    i, it, jj, itm;
-  double DT = 0.02, sigfac, snormfac;
-  double signorm = 5.5;      // signorm : sigma of the temperature distribution for a normal day 
-  double siglim;       // sigma limit for the integration which is equal to 2.5 sigmanorm
-  double signormc;     // sigma of the temperature distribution for cloudy day
-  double siglimc=0, siglim0, siglim0c;
-  double tstep, tsint, tint, tstepc;
+  IssmDouble DT = 0.02, sigfac, snormfac;
+  IssmDouble signorm = 5.5;      // signorm : sigma of the temperature distribution for a normal day 
+  IssmDouble siglim;       // sigma limit for the integration which is equal to 2.5 sigmanorm
+  IssmDouble signormc = signorm - 0.5;     // sigma of the temperature distribution for cloudy day
+  IssmDouble siglimc, siglim0, siglim0c;
+  IssmDouble tstep, tsint, tint, tstepc;
   int    NPDMAX = 1504, NPDCMAX = 1454;
-  //double pdds[NPDMAX]={0}; 
-  //double pds[NPDCMAX]={0};
-  double pddt, pd ; // pd : snow/precip fraction, precipitation falling as snow
-  double PDup, PDCUT = 2.0;    // PDcut: rain/snow cutoff temperature (C)
-  double tstar; // monthly mean surface temp
+  //IssmDouble pdds[NPDMAX]={0}; 
+  //IssmDouble pds[NPDCMAX]={0};
+  IssmDouble pddt, pd ; // pd : snow/precip fraction, precipitation falling as snow
+  IssmDouble PDup, PDCUT = 2.0;    // PDcut: rain/snow cutoff temperature (C)
+  IssmDouble tstar; // monthly mean surface temp
   
-  double* pdds=NULL; 
-  double* pds=NULL; 
+  IssmDouble* pdds=NULL; 
+  IssmDouble* pds=NULL; 
   Element* element = NULL;
   
-  pdds=(double*)xmalloc(NPDMAX*sizeof(double)+1); 
-  pds=(double*)xmalloc(NPDCMAX*sizeof(double)+1); 
-  
-  
-  // PDD constant
-  siglim = 2.5*signorm; 
+  pdds=xNew<IssmDouble>(NPDMAX+1); 
+  pds=xNew<IssmDouble>(NPDCMAX+1); 
   
   // initialize PDD (creation of a lookup table)
@@ -53,8 +49,13 @@
   snormfac = 1.0/(signorm*sqrt(2.0*acos(-1.0)));
   siglim = 2.5*signorm;
-  itm = (int)(2*siglim/DT + 1.5);
+  siglimc = 2.5*signormc;
+  siglim0 =  siglim/DT + 0.5;
+  siglim0c =  siglimc/DT + 0.5;
+  PDup = siglimc+PDCUT;
+
+  itm = reCast<int,IssmDouble>((2*siglim/DT + 1.5));
   
   if (itm >= NPDMAX){
-    printf("increase NPDMAX in massBalance.cpp\n");
+    _printLine_("increase NPDMAX in massBalance.cpp");
     exit (1);
       }
@@ -63,5 +64,5 @@
     tstar = it*DT-siglim;
     tint = tsint;
-    pddt = 0;
+    pddt = 0.;
     for ( jj = 0; jj < 600; jj++){
       if (tint > (tstar+siglim)){break;}
@@ -80,7 +81,7 @@
   snormfac = 1.0/(signormc*sqrt(2.0*acos(-1.0)));
   siglimc = 2.5*signormc ;
-  itm = (int)((PDCUT+2.*siglimc)/DT + 1.5);
+  itm = reCast<int,IssmDouble>((PDCUT+2.*siglimc)/DT + 1.5);
   if (itm >= NPDCMAX){
-    printf("'increase NPDCMAX in p35com'\n");
+    _printLine_("'increase NPDCMAX in p35com'");
     exit (1);
       }
@@ -89,5 +90,5 @@
     //    tstar = REAL(it)*DT-siglimc;
     tint = tsint;          // start against upper bound
-    pd = 0;
+    pd = 0.;
     for (jj = 0; jj < 600; jj++){
       if (tint<(tstar-siglimc)) {break;}
@@ -97,5 +98,5 @@
     pds[it] = pd*snormfac;  // gaussian integral lookup table for snow fraction
   }
-  pds[itm+1] = 0;
+  pds[itm+1] = 0.;
   //     *******END initialize PDD
   
@@ -105,6 +106,6 @@
   }
   /*free ressouces: */
-  xfree((void**)&pdds);
-  xfree((void**)&pds);
+  xDelete<IssmDouble>(pdds);
+  xDelete<IssmDouble>(pds);
   
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Reduceloadx/Reduceloadx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 12878)
@@ -22,5 +22,5 @@
 	int         verbose;
 
-	_printf_(VerboseModule(),"   Dirichlet lifting applied to load vector\n");
+	if(VerboseModule()) _pprintLine_("   Dirichlet lifting applied to load vector");
 
 	Kfs->GetSize(&global_m,&global_n);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Reduceloadx/Reduceloadx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Reduceloadx/Reduceloadx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Reduceloadx/Reduceloadx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _REDUCELOADX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 12878)
@@ -15,5 +15,5 @@
 	int configuration_type;
 	int fsize;
-	double* ug_serial=NULL;
+	IssmDouble* ug_serial=NULL;
 
 	/*first figure out fsize: */
@@ -51,5 +51,5 @@
 
 	/*Free ressources:*/
-	xfree((void**)&ug_serial);
+	xDelete<IssmDouble>(ug_serial);
 
 	/*Assign output pointers:*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h	(revision 12878)
@@ -7,5 +7,5 @@
 #define _REDUCEVECTORGTOFX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp	(revision 12878)
@@ -51,5 +51,5 @@
 
 	/*Free ressources:*/
-	xfree((void**)&yg_serial);
+	xDelete<double>(yg_serial);
 
 	/*Assign output pointers:*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h	(revision 12878)
@@ -7,5 +7,5 @@
 #define _REDUCEVECTORGTOSX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/RequestedOutputsx/RequestedOutputsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/RequestedOutputsx/RequestedOutputsx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/RequestedOutputsx/RequestedOutputsx.cpp	(revision 12878)
@@ -13,6 +13,6 @@
 	int      output_enum;
 	int      step;
-	double   time;
-	double   output_value;
+	IssmDouble   time;
+	IssmDouble   output_value;
 	Element *element      = NULL;
 
@@ -32,4 +32,8 @@
 					results->AddObject(new DoubleExternalResult(results->Size()+1,IceVolumeEnum,output_value,step,time));
 					break;
+				case TotalSmbEnum:
+					Responsex(&output_value,elements,nodes,vertices,loads,materials,parameters,"TotalSmb",false,0);
+					results->AddObject(new DoubleExternalResult(results->Size()+1,TotalSmbEnum,output_value,step,time));
+					break;
 				default:
 					/*create this output in the element inputs, and then transfer to results:*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 12878)
@@ -22,5 +22,5 @@
 
 	/*Display message*/
-	_printf_(VerboseModule(),"   Resetting penalties\n");
+	if(VerboseModule()) _pprintLine_("   Resetting penalties");
 
 	/*recover parameters: */
@@ -30,5 +30,5 @@
 	 * management routine, otherwise, skip : */
 	if (RiftIsPresent(loads,analysis_type)){
-		_error_("rift constraints reset not supported yet!");
+		_error2_("rift constraints reset not supported yet!");
 	}
 	else if(ThermalIsPresent(loads,analysis_type)){
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Responsex/Responsex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Responsex/Responsex.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Responsex/Responsex.cpp	(revision 12878)
@@ -16,5 +16,5 @@
 #include "../modules.h"
 
-void Responsex(double* responses,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,const char* response_descriptor,bool process_units,int weight_index){
+void Responsex(IssmDouble* responses,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,const char* response_descriptor,bool process_units,int weight_index){
 
 	switch (StringToEnumx(response_descriptor)){
@@ -41,4 +41,5 @@
 		case ThicknessAbsMisfitEnum:     ThicknessAbsMisfitx(      responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
 		case ThicknessAbsGradientEnum:   ThicknessAbsGradientx(    responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case TotalSmbEnum:					TotalSmbx(                responses, elements,nodes, vertices, loads, materials, parameters,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;
@@ -46,7 +47,7 @@
 		case VelEnum:ElementResponsex(responses, elements,nodes, vertices, loads, materials, parameters,VelEnum,process_units); break;
 		case FrictionCoefficientEnum:NodalValuex(responses, FrictionCoefficientEnum,elements,nodes, vertices, loads, materials, parameters,process_units); break;
-		default: _error_(" response descriptor \"%s\" not supported yet!",response_descriptor); break;
+		default: _error2_("response descriptor \"" << response_descriptor << "\" not supported yet!"); break;
 		#else
-		default: _error_(" ISSM was not compiled with responses capabilities, exiting!");
+		default: _error2_("ISSM was not compiled with responses capabilities, exiting!");
 		#endif
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Responsex/Responsex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Responsex/Responsex.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Responsex/Responsex.h	(revision 12878)
@@ -6,8 +6,8 @@
 #define _RESPONSESX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
-void Responsex(double* presponse,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,const char* response_descriptor,bool process_units,int weight_index);
+void Responsex(IssmDouble* presponse,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,const char* response_descriptor,bool process_units,int weight_index);
 
 #endif  /* _RESPONSESXX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Scotchx/Scotchx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Scotchx/Scotchx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Scotchx/Scotchx.h	(revision 12878)
@@ -20,5 +20,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 #ifdef _HAVE_SCOTCH_ //only works if scotch library has been compiled in.
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 12878)
@@ -25,5 +25,5 @@
 	}
 
-	xfree((void**)&control_type);
+	xDelete<int>(control_type);
 }
 
@@ -37,4 +37,4 @@
 
 	/*Free ressources:*/
-	xfree((void**)&serial_vector);
+	xDelete<double>(serial_vector);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h	(revision 12878)
@@ -5,5 +5,5 @@
 #define _SETCONTROLINPUTSXFROMVECTOR_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 12878)
@@ -39,7 +39,7 @@
 	int     nshape,ncoord;
 	double  cpsum;
-	int     *pstype=NULL,*pnpart=NULL,**ppstrt=NULL,**pptype=NULL,*pnvert=NULL;
-	double  **pshapx=NULL,**pshapy=NULL,**pshapz=NULL,**pshapm=NULL;
-	double  *lat=NULL,*lon=NULL;
+	int     *pstype = NULL, *pnpart=NULL,**ppstrt=NULL,**pptype=NULL,*pnvert=NULL;
+	double **pshapx = NULL,**pshapy=NULL,**pshapz=NULL,**pshapm=NULL;
+	double  *lat    = NULL, *lon=NULL;
 
 	SHPHandle   hSHP;
@@ -49,18 +49,17 @@
 
 	char    indent[81]="";
-	KML_File*             kfile =NULL;
-	KML_Document*         kdoc  =NULL;
-	KML_Style*            kstyle=NULL;
-	KML_LineStyle*        klsty =NULL;
-	KML_PolyStyle*        kpsty =NULL;
-	KML_Folder*           kfold =NULL;
-	KML_Placemark*        kplace=NULL;
-	KML_MultiGeometry*    kmulti=NULL;
-	KML_Polygon*          kpoly =NULL;
-	KML_LinearRing*       kring =NULL;
-	KML_LineString*       kline =NULL;
-	KML_Point*            kpoint=NULL;
-
-	FILE*   fid=NULL;
+	KML_File          *kfile  = NULL;
+	KML_Document      *kdoc   = NULL;
+	KML_Style         *kstyle = NULL;
+	KML_LineStyle     *klsty  = NULL;
+	KML_PolyStyle     *kpsty  = NULL;
+	KML_Folder        *kfold  = NULL;
+	KML_Placemark     *kplace = NULL;
+	KML_MultiGeometry *kmulti = NULL;
+	KML_Polygon       *kpoly  = NULL;
+	KML_LinearRing    *kring  = NULL;
+	KML_LineString    *kline  = NULL;
+	KML_Point         *kpoint = NULL;
+	FILE              *fid    = NULL;
 
 	clock_t clock0,clock1;
@@ -69,5 +68,5 @@
 	clock0=clock();
 	time0 =time(NULL);
-	_printf_(true,"\nShp2Kmlx Module -- %s",ctime(&time0));
+	_pprintString_("\nShp2Kmlx Module -- " << ctime(&time0));
 
 /*  note that much of the following code is taken from shpdump.c in shapelib.  */
@@ -76,5 +75,5 @@
 
 	hSHP = SHPOpen( filshp, "rb" );
-	if (!hSHP) _error_("Error opening shp/shx files.");
+	if (!hSHP) _error2_("Error opening shp/shx files.");
 
 /*  read header and print out file bounds  */
@@ -97,13 +96,13 @@
 
 	nshape=nEntities;
-	pstype=(int *) xmalloc(nshape*sizeof(int));
-	pnpart=(int *) xmalloc(nshape*sizeof(int));
-	ppstrt=(int **) xmalloc(nshape*sizeof(int *));
-	pptype=(int **) xmalloc(nshape*sizeof(int *));
-	pnvert=(int *) xmalloc(nshape*sizeof(int));
-	pshapx=(double **) xmalloc(nshape*sizeof(double *));
-	pshapy=(double **) xmalloc(nshape*sizeof(double *));
-	pshapz=(double **) xmalloc(nshape*sizeof(double *));
-	pshapm=(double **) xmalloc(nshape*sizeof(double *));
+	pstype=xNew<int>(nshape);
+	pnpart=xNew<int>(nshape);
+	ppstrt=xNew<int*>(nshape);
+	pptype=xNew<int*>(nshape);
+	pnvert=xNew<int>(nshape);
+	pshapx=xNew<double*>(nshape);
+	pshapy=xNew<double*>(nshape);
+	pshapz=xNew<double*>(nshape);
+	pshapm=xNew<double*>(nshape);
 
 /*  loop over the list of shapes  */
@@ -129,6 +128,6 @@
 	pnpart[i]=psShape->nParts;
 	if (pnpart[i]) {
-		ppstrt[i]=(int *) xmalloc(pnpart[i]*sizeof(int));
-		pptype[i]=(int *) xmalloc(pnpart[i]*sizeof(int));
+		ppstrt[i]=xNew<int>(pnpart[i]);
+		pptype[i]=xNew<int>(pnpart[i]);
 	}
 	else {
@@ -138,8 +137,8 @@
 	pnvert[i]=psShape->nVertices;
 	if (pnvert[i]) {
-		pshapx[i]=(double *) xmalloc(pnvert[i]*sizeof(double));
-		pshapy[i]=(double *) xmalloc(pnvert[i]*sizeof(double));
-		pshapz[i]=(double *) xmalloc(pnvert[i]*sizeof(double));
-		pshapm[i]=(double *) xmalloc(pnvert[i]*sizeof(double));
+		pshapx[i]=xNew<double>(pnvert[i]);
+		pshapy[i]=xNew<double>(pnvert[i]);
+		pshapz[i]=xNew<double>(pnvert[i]);
+		pshapm[i]=xNew<double>(pnvert[i]);
 	}
 	else {
@@ -296,6 +295,6 @@
 			kpoint=new KML_Point();
 
-			lat=(double *) xmalloc(pnvert[i]*sizeof(double));
-			lon=(double *) xmalloc(pnvert[i]*sizeof(double));
+			lat=xNew<double>(pnvert[i]);
+			lon=xNew<double>(pnvert[i]);
 			if (sgn) {
 				Xy2llx(lat,lon,pshapx[i],pshapy[i],pnvert[i],sgn,cm,sp);
@@ -310,6 +309,6 @@
 			kpoint->coords[2]=pshapz[i][0];
 
-			xfree((void**)&lon);
-			xfree((void**)&lat);
+			xDelete<double>(lon);
+			xDelete<double>(lat);
 
 			(kplace->geometry  )->AddObject((Object*)kpoint);
@@ -337,6 +336,6 @@
 /*  convert to lat/lon, if necessary  */
 
-			lat=(double *) xmalloc(pnvert[i]*sizeof(double));
-			lon=(double *) xmalloc(pnvert[i]*sizeof(double));
+			lat=xNew<double>(pnvert[i]);
+			lon=xNew<double>(pnvert[i]);
 			if (sgn) {
 				Xy2llx(lat,lon,pshapx[i],pshapy[i],pnvert[i],sgn,cm,sp);
@@ -353,21 +352,20 @@
 
 				kline->ncoord    =(j<pnpart[i]-1 ? ppstrt[i][j+1]-ppstrt[i][j] : pnvert[i]-ppstrt[i][j]);
-				kline->coords    =(double (*)[3]) xmalloc(kline->ncoord*3*sizeof(double));
+				kline->coords    =xNew<double>(kline->ncoord*3);
 				for (k=0; k<kline->ncoord; k++) {
-					kline->coords[k][0]=lon      [ppstrt[i][j]+k];
-					kline->coords[k][1]=lat      [ppstrt[i][j]+k];
-					kline->coords[k][2]=pshapz[i][ppstrt[i][j]+k];
+					kline->coords[3*k+0]=lon      [ppstrt[i][j]+k];
+					kline->coords[3*k+1]=lat      [ppstrt[i][j]+k];
+					kline->coords[3*k+2]=pshapz[i][ppstrt[i][j]+k];
 				}
-
 				(kmulti->geometry  )->AddObject((Object*)kline);
-				kline =NULL;
-			}
-
-			xfree((void**)&lon);
-			xfree((void**)&lat);
-
-			(kplace->geometry  )->AddObject((Object*)kmulti);
+				kline = NULL;
+			}
+
+			xDelete<double>(lon);
+			xDelete<double>(lat);
+
+			(kplace->geometry)->AddObject((Object*)kmulti);
 			kmulti=NULL;
-			(kfold ->feature   )->AddObject((Object*)kplace);
+			(kfold ->feature )->AddObject((Object*)kplace);
 			kplace=NULL;
 		}
@@ -401,6 +399,6 @@
 /*  convert to lat/lon, if necessary  */
 
-			lat=(double *) xmalloc(pnvert[i]*sizeof(double));
-			lon=(double *) xmalloc(pnvert[i]*sizeof(double));
+			lat=xNew<double>(pnvert[i]);
+			lon=xNew<double>(pnvert[i]);
 			if (sgn) {
 				Xy2llx(lat,lon,pshapx[i],pshapy[i],pnvert[i],sgn,cm,sp);
@@ -438,16 +436,16 @@
 
 					kring->ncoord    =(j<pnpart[i]-1 ? ppstrt[i][j+1]-ppstrt[i][j] : pnvert[i]-ppstrt[i][j]);
-					kring->coords    =(double (*)[3]) xmalloc(kring->ncoord*3*sizeof(double));
+					kring->coords    =xNew<double>(kring->ncoord*3);
 					if (cpsum < 0)
 						for (k=0; k<kring->ncoord; k++) {
-							kring->coords[kring->ncoord-1-k][0]=lon      [ppstrt[i][j]+k];
-							kring->coords[kring->ncoord-1-k][1]=lat      [ppstrt[i][j]+k];
-							kring->coords[kring->ncoord-1-k][2]=pshapz[i][ppstrt[i][j]+k];
+							kring->coords[3*(kring->ncoord-1-k)+0]=lon      [ppstrt[i][j]+k];
+							kring->coords[3*(kring->ncoord-1-k)+1]=lat      [ppstrt[i][j]+k];
+							kring->coords[3*(kring->ncoord-1-k)+2]=pshapz[i][ppstrt[i][j]+k];
 						}
 					else
 						for (k=0; k<kring->ncoord; k++) {
-							kring->coords[k                ][0]=lon      [ppstrt[i][j]+k];
-							kring->coords[k                ][1]=lat      [ppstrt[i][j]+k];
-							kring->coords[k                ][2]=pshapz[i][ppstrt[i][j]+k];
+							kring->coords[3*k+0]=lon      [ppstrt[i][j]+k];
+							kring->coords[3*k+1]=lat      [ppstrt[i][j]+k];
+							kring->coords[3*k+2]=pshapz[i][ppstrt[i][j]+k];
 						}
 
@@ -470,9 +468,9 @@
 
 					kring->ncoord    =(j<pnpart[i]-1 ? ppstrt[i][j+1]-ppstrt[i][j] : pnvert[i]-ppstrt[i][j]);
-					kring->coords    =(double (*)[3]) xmalloc(kring->ncoord*3*sizeof(double));
+					kring->coords    =xNew<double>(kring->ncoord*3);
 					for (k=0; k<kring->ncoord; k++) {
-						kring->coords[k][0]=lon      [ppstrt[i][j]+k];
-						kring->coords[k][1]=lat      [ppstrt[i][j]+k];
-						kring->coords[k][2]=pshapz[i][ppstrt[i][j]+k];
+						kring->coords[3*k+0]=lon      [ppstrt[i][j]+k];
+						kring->coords[3*k+1]=lat      [ppstrt[i][j]+k];
+						kring->coords[3*k+2]=pshapz[i][ppstrt[i][j]+k];
 					}
 
@@ -487,6 +485,6 @@
 			}
 
-			xfree((void**)&lon);
-			xfree((void**)&lat);
+			xDelete<double>(lon);
+			xDelete<double>(lat);
 
 			(kplace->geometry  )->AddObject((Object*)kmulti);
@@ -518,6 +516,6 @@
 /*  convert to lat/lon, if necessary  */
 
-			lat=(double *) xmalloc(pnvert[i]*sizeof(double));
-			lon=(double *) xmalloc(pnvert[i]*sizeof(double));
+			lat=xNew<double>(pnvert[i]);
+			lon=xNew<double>(pnvert[i]);
 			if (sgn) {
 				Xy2llx(lat,lon,pshapx[i],pshapy[i],pnvert[i],sgn,cm,sp);
@@ -541,6 +539,6 @@
 			}
 
-			xfree((void**)&lon);
-			xfree((void**)&lat);
+			xDelete<double>(lon);
+			xDelete<double>(lat);
 
 			(kplace->geometry  )->AddObject((Object*)kmulti);
@@ -575,5 +573,5 @@
 /*  write kml file  */
 
-	_printf_(true,"Writing kml document to file.\n");
+	_pprintLine_("Writing kml document to file.");
 	fid=fopen(filkml,"w");
 	fprintf(fid,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
@@ -583,22 +581,22 @@
 	delete kfile;
 	for (i=nshape-1; i>=0; i--) {
-		xfree((void**)&(pshapm[i]));
-		xfree((void**)&(pshapz[i]));
-		xfree((void**)&(pshapy[i]));
-		xfree((void**)&(pshapx[i]));
-	}
-	xfree((void**)&pshapm);
-	xfree((void**)&pshapz);
-	xfree((void**)&pshapy);
-	xfree((void**)&pshapx);
-	xfree((void**)&pnvert);
+		xDelete<double>((pshapm[i]));
+		xDelete<double>((pshapz[i]));
+		xDelete<double>((pshapy[i]));
+		xDelete<double>((pshapx[i]));
+	}
+	xDelete<double*>(pshapm);
+	xDelete<double*>(pshapz);
+	xDelete<double*>(pshapy);
+	xDelete<double*>(pshapx);
+	xDelete<int>(pnvert);
 	for (i=nshape-1; i>=0; i--) {
-		xfree((void**)&(pptype[i]));
-		xfree((void**)&(ppstrt[i]));
-	}
-	xfree((void**)&pptype);
-	xfree((void**)&ppstrt);
-	xfree((void**)&pnpart);
-	xfree((void**)&pstype);
+		xDelete<int>((pptype[i]));
+		xDelete<int>((ppstrt[i]));
+	}
+	xDelete<int*>(pptype);
+	xDelete<int*>(ppstrt);
+	xDelete<int>(pnpart);
+	xDelete<int>(pstype);
 
 	clock1=clock();
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Shp2Kmlx/Shp2Kmlx.h	(revision 12878)
@@ -19,5 +19,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SmbGradientsx/SmbGradientsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SmbGradientsx/SmbGradientsx.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SmbGradientsx/SmbGradientsx.cpp	(revision 12878)
@@ -0,0 +1,27 @@
+/*!\file SmbGradientsx
+ * \brief: calculates SMB as function of local elevation 
+ */
+
+#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){
+
+// void SmbGradientsx(hd,agd,ni){
+//    INPUT parameters: ni: working size of arrays
+//    INPUT: surface elevation (m): hd(NA)
+//    OUTPUT: mass-balance (m/yr ice): agd(NA)
+
+  int    i;
+  
+  Element* element = NULL;
+  
+  for(i=0;i<elements->Size();i++){
+    element=(Element*)elements->GetObjectByOffset(i);
+    element->SmbGradients();
+  }
+}
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SmbGradientsx/SmbGradientsx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SmbGradientsx/SmbGradientsx.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SmbGradientsx/SmbGradientsx.h	(revision 12878)
@@ -0,0 +1,14 @@
+/*!\file:  SmbGradientsx.h
+ * \brief header file for degree of freedoms distribution routines.
+ */ 
+
+#ifndef _SMBGRADIENTSX_H
+#define _SMBGRADIENTSX_H
+
+#include "../../Container/Container.h"
+#include "../../classes/objects/objects.h"
+
+/* local prototypes: */
+void SmbGradientsx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters);
+
+#endif  /* _SMBGRADIENTSX_H*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SmearFunctionx/SmearFunctionx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SmearFunctionx/SmearFunctionx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SmearFunctionx/SmearFunctionx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/DofTypesToIndexSet.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/DofTypesToIndexSet.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/DofTypesToIndexSet.cpp	(revision 12878)
@@ -20,5 +20,5 @@
 
 	int         start,end;
-	double*     df_local=NULL;
+	IssmDouble*     df_local=NULL;
 	int         df_local_size;
 	int         i;
@@ -46,6 +46,6 @@
 
 		/*Allocate indices: */
-		if(pressure_num)pressure_indices=(int*)xmalloc(pressure_num*sizeof(int));
-		if(velocity_num)velocity_indices=(int*)xmalloc(velocity_num*sizeof(int));
+		if(pressure_num)pressure_indices=xNew<int>(pressure_num);
+		if(velocity_num)velocity_indices=xNew<int>(velocity_num);
 
 		pressure_count=0;
@@ -74,6 +74,6 @@
 
 	/*Free ressources:*/
-	xfree((void**)&pressure_indices);
-	xfree((void**)&velocity_indices);
+	xDelete<int>(pressure_indices);
+	xDelete<int>(velocity_indices);
 
 	/*Assign output pointers:*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/Solverx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/Solverx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/Solverx.cpp	(revision 12878)
@@ -26,36 +26,20 @@
 	_assert_(pf);
 
-	#ifdef _HAVE_PETSC_
-		Vec uf0_vector = NULL;
-		Vec df_vector  = NULL;
-		Vec uf_vector  = NULL;
-		if(uf0) uf0_vector = uf0->vector;
-		if(df)  df_vector  = df->vector;
+	/*Initialize vector: */
+	uf=new Vector();
 
-		/*In serial mode, the Petsc Options database has not been initialized properly: */
+	/*According to matrix type, use specific solvers: */
+	if(Kff->type==PetscMatType){
+		PetscVec* uf0_vector = NULL;
+		PetscVec* df_vector  = NULL;
+		if(uf0) uf0_vector = uf0->pvector;
+		if(df)  df_vector  = df->pvector;
 
-		SolverxPetsc(&uf_vector,Kff->matrix,pf->vector,uf0_vector,df_vector,parameters);
-
-		/*Create vector out of petsc vector: */
-		uf=new Vector(uf_vector);
-
-		/*Free ressources: */
-		VecFree(&uf_vector);
-	#else
-		#ifdef _HAVE_GSL_
-		SeqVec* uf_vector=NULL;
-
-		SolverxGsl(&uf_vector,Kff->matrix,pf->vector);
-
-		/*Create vector out of SeqVec vector: */
-		uf=new Vector(uf_vector);
-
-		/*Free ressources: */
-		delete uf_vector;
-
-		#else
-			_error_("GSL support not compiled in!");
-		#endif
-	#endif
+		SolverxPetsc(&uf->pvector,Kff->pmatrix,pf->pvector,uf0_vector,df_vector,parameters);
+	}
+	else if(Kff->type==SeqMatType){
+		SolverxSeq(&uf->svector,Kff->smatrix,pf->svector);
+	}
+	else _error2_("Matrix type: " << Kff->type << " not supported yet!");
 
 	/*Assign output pointers:*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/Solverx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/Solverx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/Solverx.h	(revision 12878)
@@ -12,5 +12,5 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
@@ -18,11 +18,11 @@
 
 #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);
+void  DofTypesToIndexSet(IS* pisv, IS* pisp, Vec df,int typeenum);
 #endif
 
-#ifdef _HAVE_GSL_
-void	SolverxGsl(SeqVec** puf,SeqMat* Kff, SeqVec* pf);
-#endif
+void SolverxSeq(SeqVec** puf,SeqMat* Kff, SeqVec* pf);
+void SolverxSeq(IssmDouble** pX,IssmDouble* A,IssmDouble* B,int n);
 
 #endif  /* _SOLVERX_H */
Index: sm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxGsl.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxGsl.cpp	(revision 12877)
+++ 	(revision )
@@ -1,71 +1,0 @@
-/*!\file SolverxGsl
- * \brief Gsl 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
- 
-#include <gsl/gsl_linalg.h>
-
-void	SolverxGsl(SeqVec** puf,SeqMat* Kff, SeqVec* pf){
-
-	/*intermediary: */
-	SeqMat* KffCopy=NULL;
-
-	/*Output: */
-	SeqVec*        uf               = NULL;
-
-	
-	/*GSL Matrices and vectors: */
-	gsl_matrix_view m;
-	gsl_vector_view b;
-	gsl_vector* x=NULL;
-	gsl_permutation* p=NULL;
-	
-	/*We are going to do an in place LU decomp, so we need to save the matrix with its original structure: */
-	KffCopy=Kff->Duplicate();
-
-
-	/*Intermediary: */
-	int M,N,N2,s;
-
-	Kff->GetSize(&M,&N);
-	pf->GetSize(&N2);
-
-	if(N!=N2)_error_("Right hand side vector of size %i, when matrix is of size %i-%i !",N2,M,N);
-	if(M!=N)_error_("Stiffness matrix should be square!");
-
-	/*Initialize gsl matrices and vectors: */
-	m = gsl_matrix_view_array (KffCopy->matrix, M, N);
-	b = gsl_vector_view_array (pf->vector, N);
-	x = gsl_vector_alloc (N);
-
-	/*Run LU and solve: */
-	p = gsl_permutation_alloc (N);
-	gsl_linalg_LU_decomp (&m.matrix, p, &s);
-	gsl_linalg_LU_solve (&m.matrix, p, &b.vector, x);
-
-	//printf ("x = \n");
-	//gsl_vector_fprintf (stdout, x, "%g");
-
-	/*Get uf initialized with the results: */
-	uf=new SeqVec(gsl_vector_ptr(x,0),M);
-
-	/*Free resources:*/
-	gsl_permutation_free (p);
-	gsl_vector_free (x);
-
-	delete KffCopy;
-
-
-	/*Assign output pointers:*/
-	*puf=uf;
-}
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxPetsc.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxPetsc.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxPetsc.cpp	(revision 12878)
@@ -14,4 +14,19 @@
 #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){
 
@@ -44,5 +59,5 @@
 
 	/*Display message*/
-	_printf_(VerboseModule(),"   Solving\n");
+	if(VerboseModule()) _pprintLine_("   Solving");
 	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
 	if(VerboseSolver())PetscOptionsPrint(stdout);
@@ -55,5 +70,5 @@
 	MatGetSize(Kff,&global_m,&global_n); _assert_(global_m==global_m);
 	if(!global_n){
-		*puf=NULL; return;
+		*puf=NewVec(0); return;
 	}
 
@@ -81,5 +96,5 @@
 		#if _PETSC_MAJOR_ >=3
 			#ifndef _HAVE_MUMPS_
-			_error_("requested MUMPS solver, which was not compiled into ISSM!\n");
+			_error2_("requested MUMPS solver, which was not compiled into ISSM!\n");
 			#endif
 		#endif
@@ -105,5 +120,5 @@
 	if (solver_type==StokesSolverEnum){
 		/*Make indices out of doftypes: */
-		if(!df)_error_("need doftypes for Stokes solver!\n");
+		if(!df)_error2_("need doftypes for Stokes solver!\n");
 		DofTypesToIndexSet(&isv,&isp,df,StokesSolverEnum);
 
@@ -136,5 +151,5 @@
 	/*Check convergence*/
 	KSPGetIterationNumber(ksp,&iteration_number);
-	if (iteration_number<0) _error_("%s%i"," Solver diverged at iteration number: ",-iteration_number);
+	if (iteration_number<0) _error2_("Solver diverged at iteration number: " << -iteration_number);
 
 	/*Free resources:*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxSeq.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxSeq.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Solverx/SolverxSeq.cpp	(revision 12878)
@@ -0,0 +1,89 @@
+/*!\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 "../../include/include.h"
+#include "../../io/io.h"
+
+#ifdef _HAVE_GSL_
+#include <gsl/gsl_linalg.h>
+#endif
+
+void SolverxSeq(SeqVec** puf,SeqMat* Kff, SeqVec* pf){/*{{{*/
+
+	#ifdef _HAVE_GSL_
+	/*Intermediary: */
+	int M,N,N2,s;
+	SeqVec *uf = NULL;
+	IssmDouble *x  = NULL;
+
+	Kff->GetSize(&M,&N);
+	pf->GetSize(&N2);
+
+	if(N!=N2)_error2_("Right hand side vector of size " << N2 << ", when matrix is of size " << M << "-" << N << " !");
+	if(M!=N)_error2_("Stiffness matrix should be square!");
+
+	SolverxSeq(&x,Kff->matrix,pf->vector,N);
+	uf=new SeqVec(x,N);
+
+	/*Assign output pointers:*/
+	*puf=uf;
+
+	#else
+		_error2_("GSL support not compiled in!");
+	#endif
+
+}/*}}}*/
+void SolverxSeq(IssmDouble** pX,IssmDouble* A,IssmDouble* B,int n){/*{{{*/
+
+	#ifdef _HAVE_GSL_
+		/*GSL Matrices and vectors: */
+		int              s;
+		gsl_matrix_view  a;
+		gsl_vector_view  b;
+		gsl_vector      *x = NULL;
+		gsl_permutation *p = NULL;
+		#ifdef _HAVE_ADOLC_
+			// if we use Adol-C then the IssmDouble will be an adouble
+			// and the calls to gsl_... will not work
+			// and we should call  a suitable wrapped solve instead
+			_error2_("SolverxSeq: should not be here with Adol-C");
+		#else
+			/*A will be modified by LU decomposition. Use copy*/
+			IssmDouble* Acopy = xNew<IssmDouble>(n*n);
+			xMemCpy<IssmDouble>(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_alloc (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);
+
+			//printf ("x = \n");
+			//gsl_vector_fprintf (stdout, x, "%g");
+
+			/*Copy result*/
+			IssmDouble* X = xNew<IssmDouble>(n);
+			memcpy(X,gsl_vector_ptr(x,0),n*sizeof(IssmDouble));
+
+			/*Clean up and assign output pointer*/
+			xDelete<IssmDouble>(Acopy);
+			gsl_permutation_free(p);
+			gsl_vector_free(x);
+			*pX=X;
+		#endif
+	#endif
+}/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SpcNodesx/SpcNodesx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SpcNodesx/SpcNodesx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SpcNodesx/SpcNodesx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _SPCNODESX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 #include "../../toolkits/toolkits.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/StringToEnumx/StringToEnumx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/StringToEnumx/StringToEnumx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/StringToEnumx/StringToEnumx.cpp	(revision 12878)
@@ -8,4 +8,5 @@
 */
 
+#include <cstring>
 #include "../../shared/shared.h"
 #include "../../include/include.h"
@@ -110,4 +111,5 @@
 	      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;
@@ -136,9 +138,9 @@
 	      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 stage=2;
    }
    if(stage==2){
-	      if (strcmp(name,"PrognosticPenaltyFactor")==0) return PrognosticPenaltyFactorEnum;
+	      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;
@@ -158,8 +160,14 @@
 	      else if (strcmp(name,"SettingsResultsAsPatches")==0) return SettingsResultsAsPatchesEnum;
 	      else if (strcmp(name,"SettingsWaitonlock")==0) return SettingsWaitonlockEnum;
-	      else if (strcmp(name,"DebugPetscProfiling")==0) return DebugPetscProfilingEnum;
-	      else if (strcmp(name,"PetscProfilingCurrentMem")==0) return PetscProfilingCurrentMemEnum;
-	      else if (strcmp(name,"PetscProfilingCurrentFlops")==0) return PetscProfilingCurrentFlopsEnum;
-	      else if (strcmp(name,"PetscProfilingSolutionTime")==0) return PetscProfilingSolutionTimeEnum;
+	      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;
@@ -170,4 +178,14 @@
 	      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,"SurfaceforcingsIssmbgradients")==0) return SurfaceforcingsIssmbgradientsEnum;
+	      else if (strcmp(name,"SurfaceforcingsMonthlytemperatures")==0) return SurfaceforcingsMonthlytemperaturesEnum;
+	      else if (strcmp(name,"SurfaceforcingsHc")==0) return SurfaceforcingsHcEnum;
+	      else if (strcmp(name,"SurfaceforcingsSmbPosMax")==0) return SurfaceforcingsSmbPosMaxEnum;
+	      else if (strcmp(name,"SurfaceforcingsSmbPosMin")==0) return SurfaceforcingsSmbPosMinEnum;
+	      else if (strcmp(name,"SurfaceforcingsAPos")==0) return SurfaceforcingsAPosEnum;
+	      else if (strcmp(name,"SurfaceforcingsBPos")==0) return SurfaceforcingsBPosEnum;
+	      else if (strcmp(name,"SurfaceforcingsANeg")==0) return SurfaceforcingsANegEnum;
+	      else if (strcmp(name,"SurfaceforcingsBNeg")==0) return SurfaceforcingsBNegEnum;
 	      else if (strcmp(name,"ThermalMaxiter")==0) return ThermalMaxiterEnum;
 	      else if (strcmp(name,"ThermalPenaltyFactor")==0) return ThermalPenaltyFactorEnum;
@@ -243,5 +261,8 @@
 	      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 stage=3;
+   }
+   if(stage==3){
+	      if (strcmp(name,"ControlInput")==0) return ControlInputEnum;
 	      else if (strcmp(name,"DatasetInput")==0) return DatasetInputEnum;
 	      else if (strcmp(name,"DofIndexing")==0) return DofIndexingEnum;
@@ -260,8 +281,6 @@
 	      else if (strcmp(name,"IntInput")==0) return IntInputEnum;
 	      else if (strcmp(name,"IntParam")==0) return IntParamEnum;
-         else stage=3;
-   }
-   if(stage==3){
-	      if (strcmp(name,"IntVecParam")==0) return IntVecParamEnum;
+	      else if (strcmp(name,"IntVecParam")==0) return IntVecParamEnum;
+	      else if (strcmp(name,"TransientParam")==0) return TransientParamEnum;
 	      else if (strcmp(name,"MacAyeal2dIceFront")==0) return MacAyeal2dIceFrontEnum;
 	      else if (strcmp(name,"MacAyeal3dIceFront")==0) return MacAyeal3dIceFrontEnum;
@@ -365,5 +384,8 @@
 	      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 stage=4;
+   }
+   if(stage==4){
+	      if (strcmp(name,"DragCoefficientAbsGradient")==0) return DragCoefficientAbsGradientEnum;
 	      else if (strcmp(name,"TransientInput")==0) return TransientInputEnum;
 	      else if (strcmp(name,"Outputfilename")==0) return OutputfilenameEnum;
@@ -383,8 +405,6 @@
 	      else if (strcmp(name,"StressTensorzz")==0) return StressTensorzzEnum;
 	      else if (strcmp(name,"IceVolume")==0) return IceVolumeEnum;
-         else stage=4;
-   }
-   if(stage==4){
-	      if (strcmp(name,"P0")==0) return P0Enum;
+	      else if (strcmp(name,"TotalSmb")==0) return TotalSmbEnum;
+	      else if (strcmp(name,"P0")==0) return P0Enum;
 	      else if (strcmp(name,"P1")==0) return P1Enum;
 	      else if (strcmp(name,"P1DG")==0) return P1DGEnum;
@@ -468,4 +488,4 @@
    }
 	/*If we reach this point, the string provided has not been found*/
-   _error_("Enum %s not found",name);
+	_error2_("Enum " << name << " not found");
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAreax/SurfaceAreax.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 12878)
@@ -11,5 +11,5 @@
 #include "../InputUpdateFromConstantx/InputUpdateFromConstantx.h"
 
-void SurfaceAreax( double* pS, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+void SurfaceAreax( IssmDouble* pS, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
 	
 	/*Intermediary*/
@@ -18,6 +18,6 @@
 
 	/*output: */
-	double S=0;
-	double S_sum;
+	IssmDouble S=0;
+	IssmDouble S_sum;
 	
 	/*Compute gradients: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAreax/SurfaceAreax.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 12878)
@@ -6,9 +6,9 @@
 #define _SURFACEAREAX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 /* local prototypes: */
-void SurfaceAreax( double* pS, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+void SurfaceAreax( IssmDouble* pS, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif  /* _SURFACEAREAX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SystemMatricesx/SystemMatricesx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SystemMatricesx/SystemMatricesx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SystemMatricesx/SystemMatricesx.cpp	(revision 12878)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SystemMatricesx(Matrix** pKff, Matrix** pKfs, Vector** ppf, Vector** pdf, double* pkmax,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool kflag,bool pflag,bool penalty_kflag,bool penalty_pflag){
+void SystemMatricesx(Matrix** pKff, Matrix** pKfs, Vector** ppf, Vector** pdf, IssmDouble* pkmax,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool kflag,bool pflag,bool penalty_kflag,bool penalty_pflag){
 	
 	/*intermediary: */
@@ -25,8 +25,8 @@
 	Vector*    pf   = NULL;
 	Vector*    df=NULL;
-	double kmax = 0;
+	IssmDouble kmax = 0;
 
 	/*Display message*/
-	_printf_(VerboseModule(),"   Generating matrices\n");
+	if(VerboseModule()) _pprintLine_("   Generating matrices");
 
 	/*retrive parameters: */
@@ -41,5 +41,5 @@
 	numberofdofspernode=nodes->MaxNumDofs(configuration_type,GsetEnum);
 
-	/*Checks in debugging mode {{{1*/
+	/*Checks in debugging mode {{{*/
 	if(penalty_kflag)_assert_(kflag);
 	if(penalty_pflag)_assert_(pflag);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/SystemMatricesx/SystemMatricesx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/SystemMatricesx/SystemMatricesx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/SystemMatricesx/SystemMatricesx.h	(revision 12878)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void SystemMatricesx(Matrix** pKff, Matrix** pKfs, Vector** ppf, Vector** pdf, double* pkmax,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,
+void SystemMatricesx(Matrix** pKff, Matrix** pKfs, Vector** ppf, Vector** pdf, IssmDouble* pkmax,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,
 			bool kflag=true,bool pflag=true,bool penalty_kflag=true,bool penalty_pflag=true);
 
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/TimeAdaptx/TimeAdaptx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/TimeAdaptx/TimeAdaptx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/TimeAdaptx/TimeAdaptx.cpp	(revision 12878)
@@ -10,15 +10,15 @@
 #include "../../Container/Container.h"
 
-void TimeAdaptx(double* pdt, Elements* elements, Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials, Parameters* parameters){
+void TimeAdaptx(IssmDouble* pdt, Elements* elements, Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials, Parameters* parameters){
 
 	int      i;
 
 	/*output: */
-	double   dt;
+	IssmDouble   dt;
 
 	/*intermediary: */
 	Element *element     = NULL;
-	double   min_dt      = 0;
-	double   node_min_dt = 0;
+	IssmDouble   min_dt      = 0;
+	IssmDouble   node_min_dt = 0;
 
 	/*Go through elements, and figure out the minimum of the time steps for each element (using CFL criterion): */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/TimeAdaptx/TimeAdaptx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/TimeAdaptx/TimeAdaptx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/TimeAdaptx/TimeAdaptx.h	(revision 12878)
@@ -6,8 +6,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void TimeAdaptx(double* pdt, Elements* elements, Nodes* nodes,Vertices* vertices,Loads* loads, Materials* materials, Parameters* parameters);
+void TimeAdaptx(IssmDouble* pdt, Elements* elements, Nodes* nodes,Vertices* vertices,Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif  /* _TIMEADAPTX_H */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/TotalSmbx/TotalSmbx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/TotalSmbx/TotalSmbx.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/TotalSmbx/TotalSmbx.cpp	(revision 12878)
@@ -0,0 +1,30 @@
+/*!\file TotalSmbx
+ * \brief: compute total ice sheet surface mass balance 
+ */
+
+#include "./TotalSmbx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void TotalSmbx(double* pSmb, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+
+	double local_smb = 0;
+	double total_smb;
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=(Element*)elements->GetObjectByOffset(i);
+		local_smb+=element->TotalSmb();
+	}
+	#ifdef _HAVE_MPI_
+	MPI_Reduce(&local_smb,&total_smb,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&total_smb,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	#else
+	total_smb=local_smb;
+	#endif
+
+	/*Assign output pointers: */
+	*pSmb=total_smb;
+}
Index: /issm/branches/trunk-jpl-damage/src/c/modules/TotalSmbx/TotalSmbx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/TotalSmbx/TotalSmbx.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/TotalSmbx/TotalSmbx.h	(revision 12878)
@@ -0,0 +1,14 @@
+/*!\file:  TotalSmbx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _TOTALSMBX_H
+#define _TOTALSMBX_H
+
+#include "../../Container/Container.h"
+#include "../../classes/objects/objects.h"
+
+/* local prototypes: */
+void TotalSmbx(double* pSmb, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/TriMeshx/TriMeshx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/TriMeshx/TriMeshx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/TriMeshx/TriMeshx.cpp	(revision 12878)
@@ -57,5 +57,5 @@
 
 	/*fill in the point list: */
-	in.pointlist = (REAL *) xmalloc(in.numberofpoints * 2 * sizeof(REAL));
+	in.pointlist = xNew<REAL>(in.numberofpoints*2);
 
 	counter=0;
@@ -78,9 +78,9 @@
 	
 	/*fill in the point attribute list: */
-	in.pointattributelist = (REAL*)xmalloc(in.numberofpoints*in.numberofpointattributes*sizeof(REAL));
+	in.pointattributelist = xNew<REAL>(in.numberofpoints*in.numberofpointattributes);
 	for (i=0;i<in.numberofpoints;i++) in.pointattributelist[i] = 0.0;
 	
 	/*fill in the point marker list: */
-	in.pointmarkerlist = (int *) xmalloc(in.numberofpoints * sizeof(int));
+	in.pointmarkerlist = xNew<int>(in.numberofpoints);
 	for(i=0;i<in.numberofpoints;i++) in.pointmarkerlist[i] = 0;
 
@@ -97,6 +97,6 @@
 	}
 	
-	in.segmentlist = (int *) xmalloc(in.numberofsegments * 2 * sizeof(int));
-	in.segmentmarkerlist = (int *) xcalloc(in.numberofsegments,sizeof(int));
+	in.segmentlist = xNew<int>(in.numberofsegments*2);
+	in.segmentmarkerlist = xNewZeroInit<int>(in.numberofsegments);
 	counter=0;
 	backcounter=0;
@@ -135,5 +135,5 @@
 	in.numberofholes = domain->Size()-1; /*everything is a hole, but for the first profile.*/
 	if(in.numberofholes){
-		in.holelist = (REAL *) xmalloc(in.numberofholes * 2 * sizeof(REAL));
+		in.holelist = xNew<REAL>(in.numberofholes*2);
 		for (i=0;i<domain->Size()-1;i++){
 			contour=(Contour*)domain->GetObjectByOffset(i+1);
@@ -164,9 +164,9 @@
 
 	/*Allocate index, x and y: */
-	index=(double*)xmalloc(3*out.numberoftriangles*sizeof(double));
-	x=(double*)xmalloc(out.numberofpoints*sizeof(double));
-	y=(double*)xmalloc(out.numberofpoints*sizeof(double));
-	segments=(double*)xmalloc(3*out.numberofsegments*sizeof(double));
-	segmentmarkerlist=(double*)xmalloc(out.numberofsegments*sizeof(double));
+	index=xNew<double>(3*out.numberoftriangles);
+	x=xNew<double>(out.numberofpoints);
+	y=xNew<double>(out.numberofpoints);
+	segments=xNew<double>(3*out.numberofsegments);
+	segmentmarkerlist=xNew<double>(out.numberofsegments);
 
 	for (i = 0; i< out.numberoftriangles; i++) {
@@ -192,13 +192,12 @@
 
 	/*Output : */
-	index_matrix=new Matrix(index,out.numberoftriangles,3,1); 
-	index_matrix->Convert(DENSE_SEQUENTIAL);
+	index_matrix=new Matrix(index,out.numberoftriangles,3,1,SeqMatType);
 	*pindex=index_matrix;
 	
-	segments_matrix=new Matrix(segments,out.numberofsegments,3,1); segments_matrix->Convert(DENSE_SEQUENTIAL);
+	segments_matrix=new Matrix(segments,out.numberofsegments,3,1,SeqMatType);
 	*psegments=segments_matrix;
 
-	*px=new Vector(x,out.numberofpoints);
-	*py=new Vector(y,out.numberofpoints);
-	*psegmentmarkerlist=new Vector(segmentmarkerlist,out.numberofsegments);
+	*px=new Vector(x,out.numberofpoints,SeqMatType);
+	*py=new Vector(y,out.numberofpoints,SeqMatType);
+	*psegmentmarkerlist=new Vector(segmentmarkerlist,out.numberofsegments,SeqMatType);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/TriMeshx/TriMeshx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/TriMeshx/TriMeshx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/TriMeshx/TriMeshx.h	(revision 12878)
@@ -8,5 +8,5 @@
 #include "string.h"
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/TriaSearchx/TriaSearchx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/TriaSearchx/TriaSearchx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/TriaSearchx/TriaSearchx.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../modules.h"
 
@@ -13,5 +13,5 @@
 using namespace std;
 
-void TriaSearchx(double** ptria,double* index,int nel, double* x, double* y, int nods,double* x0, double* y0,int numberofnodes){
+void TriaSearchx(double** ptria,int* index,int nel, double* x, double* y, int nods,double* x0, double* y0,int numberofnodes){
 
 	/*Output*/
@@ -19,5 +19,5 @@
 
 	/*allocate: */
-	tria=(double*)xmalloc(numberofnodes*sizeof(double));
+	tria=xNew<double>(numberofnodes);
 
 	/*Intermediary*/
@@ -52,5 +52,4 @@
 	}
 
-
 	/*Assign output pointers:*/
 	*ptria=tria;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/TriaSearchx/TriaSearchx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/TriaSearchx/TriaSearchx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/TriaSearchx/TriaSearchx.h	(revision 12878)
@@ -6,8 +6,8 @@
 #define _TRIASEARCHX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void TriaSearchx(double** ptria,double* index,int nel, double* x, double* y, int nods,double* x0, double* y0,int numberofnodes);
+void TriaSearchx(double** ptria,int* index,int nel, double* x, double* y, int nods,double* x0, double* y0,int numberofnodes);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.cpp	(revision 12878)
@@ -14,5 +14,5 @@
 void UpdateConstraintsx(Nodes* nodes,Constraints* constraints,Parameters* parameters){
 
-	double time;
+	IssmDouble time;
 	int    analysis_type;
 
@@ -22,5 +22,5 @@
 
 	/*start module: */
-	_printf_(VerboseModule(),"%s%g\n","   Updating constraints for time: ",time);
+	if(VerboseModule()) _pprintLine_("   Updating constraints for time: " << time);
 	
 	/*First, update dof constraints in nodes, using constraints: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _UPDATECONSTRAINTSX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 #include "../../toolkits/toolkits.h"
Index: /issm/branches/trunk-jpl-damage/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 12878)
@@ -13,5 +13,5 @@
 	
 	int configuration_type;
-	double* yg_serial=NULL;
+	IssmDouble* yg_serial=NULL;
 
 	/*Get current configuration*/
@@ -34,4 +34,4 @@
 
 	/*Free ressources:*/
-	xfree((void**)&yg_serial);
+	xDelete<IssmDouble>(yg_serial);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vector* yg);
Index: /issm/branches/trunk-jpl-damage/src/c/modules/UpdateVertexPositionsx/UpdateVertexPositionsx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/UpdateVertexPositionsx/UpdateVertexPositionsx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/UpdateVertexPositionsx/UpdateVertexPositionsx.cpp	(revision 12878)
@@ -15,6 +15,6 @@
 	Vector*     vz        = NULL;
 	Vertex *vertex    = NULL;
-	double *thickness = NULL;
-	double *bed       = NULL;
+	IssmDouble *thickness = NULL;
+	IssmDouble *bed       = NULL;
 
 	/*get vertex vectors for bed and thickness: */
@@ -38,6 +38,6 @@
 
 	/*Free ressources:*/
-	xfree((void**)&thickness);
-	xfree((void**)&bed);
+	xDelete<IssmDouble>(thickness);
+	xDelete<IssmDouble>(bed);
 	xdelete(&vz);
 	return 1;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/VecMergex/VecMergex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/VecMergex/VecMergex.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/VecMergex/VecMergex.cpp	(revision 12878)
@@ -15,5 +15,5 @@
 	int i;
 	int configuration_type;
-	double* uf_serial=NULL;
+	IssmDouble* uf_serial=NULL;
 
 	/*retrieve parameters: */
@@ -41,5 +41,5 @@
 	}
 	/*Free ressources:*/
-	xfree((void**)&uf_serial);
+	xDelete<IssmDouble>(uf_serial);
 
 	/*Assemble vector: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/VecMergex/VecMergex.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/VecMergex/VecMergex.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/VecMergex/VecMergex.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/VerticesDofx/VerticesDofx.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/VerticesDofx/VerticesDofx.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/VerticesDofx/VerticesDofx.h	(revision 12878)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/branches/trunk-jpl-damage/src/c/modules/Xy2llx/Xy2llx.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/Xy2llx/Xy2llx.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/Xy2llx/Xy2llx.cpp	(revision 12878)
@@ -53,5 +53,5 @@
 	double  sl,rho,cm,T,chi;
 
-	if((sgn!=1) && (sgn!=-1)) _error_("Sign should be either +1 or -1.\n");
+	if((sgn!=1) && (sgn!=-1)) _error2_("Sign should be either +1 or -1.\n");
 
 	delta = central_meridian;
@@ -124,12 +124,12 @@
 		*pdelta= 45;
 		*pslat = 70;
-		_printf_(flag,"Warning: expecting coordinates in polar stereographic (Std Latitude: 70N Meridian: 45).\n");
+		if(flag) _pprintLine_("Warning: expecting coordinates in polar stereographic (Std Latitude: 70N Meridian: 45).");
 	}
 	else if (sgn == -1) {
 		*pdelta= 0;
 		*pslat = 71;
-		_printf_(flag,"Warning: expecting coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).\n");
+		if(flag) _pprintLine_("Warning: expecting coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).");
 	}
-	else _error_("Sign should be either +1 or -1.\n");
+	else _error2_("Sign should be either +1 or -1.\n");
 
 	return;
Index: /issm/branches/trunk-jpl-damage/src/c/modules/modules.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/modules/modules.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/modules/modules.h	(revision 12878)
@@ -25,4 +25,5 @@
 #include "./CreateNodalConstraintsx/CreateNodalConstraintsx.h"
 #include "./DakotaResponsesx/DakotaResponsesx.h"
+#include "./Delta18oParameterizationx/Delta18oParameterizationx.h"
 #include "./DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
 #include "./ElementConnectivityx/ElementConnectivityx.h"
@@ -36,4 +37,5 @@
 #include "./GroundinglineMigrationx/GroundinglineMigrationx.h"
 #include "./HoleFillerx/HoleFillerx.h"
+#include "./TotalSmbx/TotalSmbx.h"
 #include "./IceVolumex/IceVolumex.h"
 #include "./InputControlUpdatex/InputControlUpdatex.h"
@@ -94,4 +96,5 @@
 #include "./ConstraintsStatex/ConstraintsStatex.h"
 #include "./PointCloudFindNeighborsx/PointCloudFindNeighborsx.h"
+#include "./PositiveDegreeDayx/PositiveDegreeDayx.h"
 #include "./PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h"
 #include "./Dakotax/Dakotax.h"
@@ -105,4 +108,5 @@
 #include "./RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h"
 #include "./Scotchx/Scotchx.h"
+#include "./SmbGradientsx/SmbGradientsx.h"
 #include "./Solverx/Solverx.h"
 #include "./SpcNodesx/SpcNodesx.h"
@@ -120,4 +124,3 @@
 #include "./VerticesDofx/VerticesDofx.h"
 #include "./VecMergex/VecMergex.h"
-
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/python/include/python_macros.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/python/include/python_macros.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/python/include/python_macros.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _PYTHON_MACROS_H_
 
-/*Header {{{1*/
+/*Header {{{*/
 
 #ifdef HAVE_CONFIG_H
@@ -16,5 +16,5 @@
 
 #ifdef _HAVE_PYTHON_
-/* MODULEBOOT/MODULEEND {{{1*/
+/* MODULEBOOT/MODULEEND {{{*/
 
 /*The following macros hide the error exception handling in a matlab module. Just put 
@@ -30,5 +30,5 @@
 //}}}
 #if _PYTHON_MAJOR_ >=3
-/* WRAPPER 3.2 {{{1*/
+/* WRAPPER 3.2 {{{*/
 #define WRAPPER(modulename,...)  \
 \
@@ -57,5 +57,5 @@
 /*}}}*/
 #else
-/* WRAPPER 2.7 {{{1*/
+/* WRAPPER 2.7 {{{*/
 #define WRAPPER(modulename,...)  \
 \
@@ -75,5 +75,5 @@
 /*}}}*/
 #endif
-/* CHECKARGUMENTS {{{1*/
+/* CHECKARGUMENTS {{{*/
 #define CHECKARGUMENTS(NLHS,NRHS,functionpointer) CheckNumPythonArguments(args, NRHS,functionpointer)
 /*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/python/io/CheckNumPythonArguments.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/python/io/CheckNumPythonArguments.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/python/io/CheckNumPythonArguments.cpp	(revision 12878)
@@ -27,9 +27,9 @@
 	if (size==0){
 		function();
-		_error_("usage: see above");
+		_error2_("usage: see above");
 	}
 	else if (size!=NRHS ) {
 		function(); 
-		_error_("usage error.");
+		_error2_("usage error.");
 	}
 	return 1;
Index: /issm/branches/trunk-jpl-damage/src/c/python/io/FetchPythonData.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/python/io/FetchPythonData.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/python/io/FetchPythonData.cpp	(revision 12878)
@@ -15,7 +15,8 @@
 #include "../../include/include.h"
 #include "../../shared/shared.h"
+#include "../../io/io.h"
 
 /*Primitive data types*/
-/*FUNCTION FetchData(double* pscalar,PyObject* py_float){{{1*/
+/*FUNCTION FetchData(double* pscalar,PyObject* py_float){{{*/
 void FetchData(double* pscalar,PyObject* py_float){
 
@@ -29,5 +30,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(int* pinteger,PyObject* py_long){{{1*/
+/*FUNCTION FetchData(int* pinteger,PyObject* py_long){{{*/
 void FetchData(int* pinteger, PyObject* py_long){
 
@@ -41,5 +42,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(bool* pboolean,PyObject* py_boolean){{{1*/
+/*FUNCTION FetchData(bool* pboolean,PyObject* py_boolean){{{*/
 void FetchData(bool* pboolean,PyObject* py_boolean){
 
@@ -47,5 +48,5 @@
 	
 	/*check this is indeed a subtype of long type: */
-	if(!PyBool_Check(py_boolean))_error_("expecting a boolean in input!");
+	if(!PyBool_Check(py_boolean))_error2_("expecting a boolean in input!");
 
 	/*extract boolean: */
@@ -57,5 +58,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(double** pmatrix,int* pM, int* pN, PyObject* py_matrix){{{1*/
+/*FUNCTION FetchData(double** pmatrix,int* pM, int* pN, PyObject* py_matrix){{{*/
 void FetchData(double** pmatrix,int* pM,int *pN,PyObject* py_matrix){
 
@@ -68,5 +69,5 @@
 	/*retrive dimensions: */
 	ndim=PyArray_NDIM((const PyArrayObject*)py_matrix);
-	if(ndim!=2)_error_("expecting an MxN matrix in input!");
+	if(ndim!=2)_error2_("expecting an MxN matrix in input!");
 	dims=PyArray_DIMS((PyArrayObject*)py_matrix);
 	M=dims[0]; N=dims[1];
@@ -81,5 +82,37 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(double** pvector,int* pM, PyObject* py_vector){{{1*/
+/*FUNCTION FetchData(int** pmatrix,int* pM, int* pN, PyObject* py_matrix){{{*/
+void FetchData(int** pmatrix,int* pM,int *pN,PyObject* py_matrix){
+
+	/*output: */
+	double* dmatrix=NULL;
+	int* matrix=NULL;
+	int M,N;
+
+	/*intermediary:*/
+	int i;
+	int ndim;
+	npy_intp*  dims=NULL;
+
+	/*retrive dimensions: */
+	ndim=PyArray_NDIM((const PyArrayObject*)py_matrix);
+	if(ndim!=2)_error2_("expecting an MxN matrix in input!");
+	dims=PyArray_DIMS((PyArrayObject*)py_matrix);
+	M=dims[0]; N=dims[1];
+	
+	/*retrieve internal value: */
+	dmatrix=(double*)PyArray_DATA((PyArrayObject*)py_matrix);
+
+	/*transform into integer matrix: */
+	matrix=xNew<int>(M*N);
+	for(i=0;i<M*N;i++)matrix[i]=(int)dmatrix[i];
+
+	/*output: */
+	if(pM)*pM=M;
+	if(pN)*pN=N;
+	if(pmatrix)*pmatrix=matrix;
+}
+/*}}}*/
+/*FUNCTION FetchData(double** pvector,int* pM, PyObject* py_vector){{{*/
 void FetchData(double** pvector,int* pM,PyObject* py_vector){
 
@@ -92,5 +125,5 @@
 	/*retrive dimensions: */
 	ndim=PyArray_NDIM((const PyArrayObject*)py_vector);
-	if(ndim!=1)_error_("expecting an Mx1 vector in input!");
+	if(ndim!=1)_error2_("expecting an Mx1 vector in input!");
 	dims=PyArray_DIMS((PyArrayObject*)py_vector);
 	M=dims[0]; 
@@ -104,8 +137,21 @@
 }
 /*}}}*/
+/*FUNCTION FetchData(Options** poptions,int istart, int nrhs,PyObject* arguments){{{*/
+void FetchData(Options** poptions,int istart, int nrhs,PyObject* arguments){
+
+	/*Initialize output*/
+	Options* options=new Options();
+
+	_pprintLine_("FetchData for Options not implemented yet, ignoring them!");
+
+	/*Assign output pointers:*/
+	*poptions=options;
+
+}
+/*}}}*/
 
 /*Python version dependent: */
 #if _PYTHON_MAJOR_ >= 3 
-/*FUNCTION FetchData(char** pstring,PyObject* py_unicode){{{1*/
+/*FUNCTION FetchData(char** pstring,PyObject* py_unicode){{{*/
 void FetchData(char** pstring,PyObject* py_unicode){
 
@@ -124,5 +170,5 @@
 /*}}}*/
 #else
-/*FUNCTION FetchData(char** pstring,PyObject* py_string){{{1*/
+/*FUNCTION FetchData(char** pstring,PyObject* py_string){{{*/
 void FetchData(char** pstring,PyObject* py_string){
 
Index: /issm/branches/trunk-jpl-damage/src/c/python/io/WritePythonData.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/python/io/WritePythonData.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/python/io/WritePythonData.cpp	(revision 12878)
@@ -21,12 +21,11 @@
 
 
-/*FUNCTION WriteData(PyObject* py_tuple,int index,char* string){{{1*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index,char* string){{{*/
 void WriteData(PyObject* py_tuple, int index, char* string){
 	
 	PyTuple_SetItem(py_tuple, index, PyUnicode_FromString(string));
 
-}
-/*}}}*/
-/*FUNCTION WriteData(PyObject* tuple,int index,Matrix* matrix){{{1*/
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* tuple,int index,Matrix* matrix){{{*/
 void WriteData(PyObject* tuple,int index,Matrix* matrix){
 	
@@ -45,6 +44,6 @@
 
 
-}
-/*FUNCTION WriteData(PyObject* py_tuple,int index,Vector* vector){{{1*/
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index,Vector* vector){{{*/
 void WriteData(PyObject* tuple,int index,Vector* vector){
 	
@@ -64,5 +63,5 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(PyObject* py_tuple,int index, double* matrix, int M, int N){{{1*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index, double* matrix, int M, int N){{{*/
 void WriteData(PyObject* tuple, int index, double* matrix, int M,int N){
 	
@@ -76,3 +75,3 @@
 	PyTuple_SetItem(tuple, index, array);
 
-}
+}/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/python/io/pythonio.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/python/io/pythonio.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/python/io/pythonio.h	(revision 12878)
@@ -13,5 +13,5 @@
 
 
-#include "../../objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../Container/Container.h"
 #include "../../include/include.h"
@@ -47,8 +47,10 @@
 void FetchData(double** pvector,int* pM,PyObject* py_ref);
 void FetchData(double** pmatrix,int* pM,int *pN,PyObject* py_array);
+void FetchData(int** pmatrix,int* pM,int *pN,PyObject* py_matrix);
 void FetchData(char** pstring,PyObject* py_unicode);
 void FetchData(double* pscalar,PyObject* py_float);
 void FetchData(int* pinteger,PyObject* py_long);
 void FetchData(bool* pbool,PyObject* py_boolean);
+void FetchData(Options** poptions,int istart, int nrhs,PyObject* arguments);
 
 int CheckNumPythonArguments(PyObject* inputs,int NRHS, void (*function)( void ));
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Alloc/alloc.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Alloc/alloc.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Alloc/alloc.cpp	(revision 12878)
@@ -25,5 +25,5 @@
 #include "../Exceptions/exceptions.h"
 #include "../../include/include.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 void* xmalloc(int size){
@@ -31,9 +31,9 @@
 	void* memptr=NULL;
 
-	if(!size)_error_(" attempting to 0 size allocation!");
+	if(!size)_error2_("attempting to 0 size allocation!");
 
 	/* Use the c library to do the allocation: */
 	memptr=malloc(size);
-	if(!memptr) _error_("memory allocation failed!");
+	if(!memptr) _error2_("memory allocation failed!");
 
 	return memptr;
@@ -44,9 +44,9 @@
 	void* memptr=NULL;
 	
-	if(!size)_error_("attempting to 0 size allocation!");
+	if(!size)_error2_("attempting to 0 size allocation!");
 
 	/* Use the c library to do the allocation: */
 	memptr=calloc(n,size);
-	if(!memptr) _error_("memory allocation failed!");
+	if(!memptr) _error2_("memory allocation failed!");
 
 	return memptr;
@@ -84,14 +84,13 @@
 }
 
-
 void* xrealloc( void* pv, int size){
 	
 	register void* value=NULL;
 	
-	if(!size)_error_("attempting to realloc to zero");
+	if(!size)_error2_("attempting to realloc to zero");
 	value = (void*)realloc(pv,size);
 
 	if (value == NULL) {
-		_error_("virtual memory exhausted");
+		_error2_("virtual memory exhausted");
 	}
 	return value;
Index: sm/branches/trunk-jpl-damage/src/c/shared/Alloc/alloc_module.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Alloc/alloc_module.cpp	(revision 12877)
+++ 	(revision )
@@ -1,41 +1,0 @@
-/* \file alloc_module.h
- */
-
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile without HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#include  "./alloc_module.h"
-#include "../Exceptions/exceptions.h"
-#include "../../include/include.h"
-#include "../../objects/objects.h"
-
-void xdelete_module(Matrix** pv){
-	
-	if (pv && *pv){
-		/*Actually, still get rid of internal Petsc matrix. Quick fix until Matlab handles C++ 
-		 * correctly: */
-		#ifdef _HAVE_PETSC_
-			MatFree(&(*pv)->matrix);
-		#endif
-		*pv=NULL;
-	}
-}
-
-void xdelete_module(Vector** pv){
-
-	if (pv && *pv){
-		/*Actually, still get rid of internal Petsc vector. Quick fix until Matlab handles C++ 
-		 * correctly: */
-		#ifdef _HAVE_PETSC_
-			VecFree(&(*pv)->vector);
-		#endif
-		*pv=NULL;
-	}
-}
Index: sm/branches/trunk-jpl-damage/src/c/shared/Alloc/alloc_module.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Alloc/alloc_module.h	(revision 12877)
+++ 	(revision )
@@ -1,11 +1,0 @@
-/* \file alloc.h
- */
-
-#ifndef _ALLOC_MODULE_H_
-#define _ALLOC_MODULE_H_
-class Matrix;
-class Vector;
-void xdelete_module(Matrix** pvptr);
-void xdelete_module(Vector** pvptr);
-
-#endif
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Alloc/xNewDelete.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Alloc/xNewDelete.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Alloc/xNewDelete.h	(revision 12878)
@@ -0,0 +1,97 @@
+/* \file xNewDelete.h
+ * \brief: header file for templated new/delete checking for non-null pointers
+ */
+
+#ifndef _XNEWDELETE_H_
+#define _XNEWDELETE_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 on may alternatively use C memory managment
+// 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* 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>
+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 
+}
+
+#endif
+
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Bamg/OppositeAngle.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Bamg/OppositeAngle.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Bamg/OppositeAngle.h	(revision 12878)
@@ -2,5 +2,5 @@
 #define _OPPOSITEANGLE_H_
 
-#include "../../objects/Bamg/include.h"
+#include "../../classes/bamg/include.h"
 
 /*Return the opposite angle modulo 2 Pi*/
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Bamg/det.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Bamg/det.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Bamg/det.h	(revision 12878)
@@ -2,5 +2,5 @@
 #define _BAMGDET_H_
 
-#include "../../objects/Bamg/include.h"
+#include "../../classes/bamg/include.h"
 
 namespace bamg {
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/Arrhenius.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/Arrhenius.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/Arrhenius.cpp	(revision 12878)
@@ -6,5 +6,5 @@
 #include <math.h>
 
-double Arrhenius(double temperature,double depth,double n){
+IssmDouble Arrhenius(IssmDouble temperature,IssmDouble depth,IssmDouble n){
 	/*Use EISMINT Parameterization for the rheology: Payne2000
 	 *
@@ -25,9 +25,9 @@
 
 	/*Some physical constants (Payne2000)*/
-	double beta=8.66*pow(10.,-4.);
-	double R=8.314;
+	IssmDouble beta=8.66*pow(10.,-4.);
+	IssmDouble R=8.314;
 
 	/*Intermediaries*/
-	double A,B,Tstar;
+	IssmDouble A,B,Tstar;
 
 	/*convert temperature to absolute temperature*/
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp	(revision 12878)
@@ -0,0 +1,38 @@
+/* file:  ComputeTemperaturePrecipitation.cpp
+   Compute the temperature and precipitation at time t from 
+   the data at present day and delta18O
+ */
+
+#include "./elements.h"
+
+void ComputeDelta18oTemperaturePrecipitation(IssmDouble Delta18oSurfacePresent, IssmDouble Delta18oSurfaceLgm, IssmDouble Delta18oSurfaceTime,
+				     IssmDouble Delta18oPresent, IssmDouble Delta18oLgm, IssmDouble Delta18oTime, 
+				     IssmDouble* PrecipitationsPresentday,
+				     IssmDouble* TemperaturesLgm, IssmDouble* TemperaturesPresentday, 
+				     IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout){
+
+  IssmDouble monthlytemperaturestmp[12],monthlyprectmp[12];
+  IssmDouble delta18oLapseRate=-6.2*pow(10.,-3);
+  IssmDouble glacialindex; // used to vary present day temperature
+  int imonth=0;
+  // printf("Delta18oTime %f\n",Delta18oTime);
+  // printf("Delta18oPresent %f\n",Delta18oPresent);
+  // printf("Delta18oLgm %f\n",Delta18oLgm);
+
+  glacialindex = (Delta18oTime-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceTime-Delta18oSurfacePresent))
+    /(Delta18oLgm-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceLgm-Delta18oSurfacePresent));
+  // printf(" monthlytemperatureseeeeee %f\n",TemperaturesPresentday[1]);
+  // printf(" monthlypreceeeeeeee %f\n",TemperaturesLgm[1]);
+  // printf(" glacialindex %f\n",glacialindex);
+
+  for (int imonth = 0; imonth<12; imonth++){  
+    monthlytemperaturestmp[imonth] = TemperaturesPresentday[imonth];//glacialindex*TemperaturesLgm[imonth] + (1-glacialindex)*TemperaturesPresentday[imonth];
+    //monthlyprectmp[imonth] = 1.5*pow(2,((monthlytemperaturestmp[imonth]-273.15-0)/10)); //equation from rob's paper
+    monthlyprectmp[imonth] = PrecipitationsPresentday[imonth];
+
+    /*Assign output pointer*/
+    *(monthlytemperaturesout+imonth) = monthlytemperaturestmp[imonth];
+    *(monthlyprecout+imonth) = monthlyprectmp[imonth];
+  }
+  // printf(" tempera %f\n",monthlytemperaturestmp[1]);
+}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/CoordinateSystemTransform.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/CoordinateSystemTransform.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/CoordinateSystemTransform.cpp	(revision 12878)
@@ -5,12 +5,12 @@
 #include <math.h>
 
-void CoordinateSystemTransform(double** ptransform,Node** nodes,int numnodes,int* cs_array){
+void CoordinateSystemTransform(IssmDouble** ptransform,Node** nodes,int numnodes,int* cs_array){
 
 	int     i,counter;
 	int     numdofs           = 0;
-	double  norm;
-	double *transform         = NULL;
-	double *values            = NULL;
-	double  coord_system[3][3];
+	IssmDouble  norm;
+	IssmDouble *transform         = NULL;
+	IssmDouble *values            = NULL;
+	IssmDouble  coord_system[3][3];
 
 	/*Some checks in debugging mode*/
@@ -22,10 +22,10 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error_("Coordinate system %s not supported yet",EnumToStringx(cs_array[i]));
+			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
 
 	/*Allocate and initialize transform matrix*/
-	transform=(double*)xmalloc(numdofs*numdofs*sizeof(double));
+	transform=xNew<IssmDouble>(numdofs*numdofs);
 	for(i=0;i<numdofs*numdofs;i++) transform[i]=0.0;
 
@@ -67,5 +67,5 @@
 				break;
 			default:
-				_error_("Coordinate system %s not supported yet",EnumToStringx(cs_array[i]));
+				_error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/GetGlobalDofList.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/GetGlobalDofList.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/GetGlobalDofList.cpp	(revision 12878)
@@ -14,5 +14,5 @@
 
 		/*Allocate:*/
-		ndof_list=(int*)xmalloc(numnodes*sizeof(int));
+		ndof_list=xNew<int>(numnodes);
 
 		/*First, figure out size of doflist: */
@@ -25,5 +25,5 @@
 		if(numdof){
 			/*Allocate: */
-			doflist=(int*)xmalloc(numdof*sizeof(int));
+			doflist=xNew<int>(numdof);
 
 			/*Populate: */
@@ -37,5 +37,5 @@
 	}
 	/*Free ressources:*/
-	xfree((void**)&ndof_list);
+	xDelete<int>(ndof_list);
 
 	return doflist;
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/GetLocalDofList.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/GetLocalDofList.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/GetLocalDofList.cpp	(revision 12878)
@@ -13,6 +13,6 @@
 	if(numnodes){
 		/*allocate: */
-		ndof_list=(int*)xmalloc(numnodes*sizeof(int));
-		ngdof_list_cumulative=(int*)xmalloc(numnodes*sizeof(int));
+		ndof_list=xNew<int>(numnodes);
+		ngdof_list_cumulative=xNew<int>(numnodes);
 
 
@@ -33,5 +33,5 @@
 		if(numdof){
 			/*Allocate: */
-			doflist=(int*)xmalloc(numdof*sizeof(int));
+			doflist=xNew<int>(numdof);
 
 			/*Populate: */
@@ -55,6 +55,6 @@
 
 	/*Free ressources:*/
-	xfree((void**)&ndof_list);
-	xfree((void**)&ngdof_list_cumulative);
+	xDelete<int>(ndof_list);
+	xDelete<int>(ngdof_list_cumulative);
 
 	/*CLean-up and return*/
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/GetVerticesCoordinates.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/GetVerticesCoordinates.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/GetVerticesCoordinates.cpp	(revision 12878)
@@ -5,5 +5,5 @@
 #include "./elements.h"
 
-void GetVerticesCoordinates(double* xyz,  Node** nodes, int numvertices){
+void GetVerticesCoordinates(IssmDouble* xyz,  Node** nodes, int numvertices){
 
 	/*In debugging mode, check that nodes is not a NULL pointer*/
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/Paterson.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/Paterson.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/Paterson.cpp	(revision 12878)
@@ -7,9 +7,11 @@
 #include <math.h>
 
-double Paterson(double temperature){
+#include "../../include/include.h"
+
+IssmDouble Paterson(IssmDouble temperature){
 	
 	/*output: */
-	double B;
-	double T;
+	IssmDouble B;
+	IssmDouble T;
 
 	/*Switch to celsius from Kelvin: */
@@ -30,39 +32,39 @@
 
 	if(T<=-45.0){
-		B=pow((double)10,(double)8)*(-0.000292866376675*pow(T+50,3)+ 0.011672640664130*pow(T+50,2)  -0.325004442485481*(T+50)+  6.524779401948101);
+		B=pow((IssmPDouble)10,(IssmPDouble)8)*(-0.000292866376675*pow(T+50,3)+ 0.011672640664130*pow(T+50,2)  -0.325004442485481*(T+50)+  6.524779401948101);
 	}
 	else if((T>=-45.0) && (T<=-40.0)){
-		B=pow((double)10,(double)8)*(-0.000292866376675*pow(T+45,3)+ 0.007279645014004*pow(T+45,2)  -0.230243014094813*(T+45)+  5.154964909039554);
+		B=pow((IssmPDouble)10,(IssmPDouble)8)*(-0.000292866376675*pow(T+45,3)+ 0.007279645014004*pow(T+45,2)  -0.230243014094813*(T+45)+  5.154964909039554);
 	}
 	else if((T>=-40.0) && (T<=-35.0)){
-		B=pow((double)10,(double)8)*(0.000072737147457*pow(T+40,3)+  0.002886649363879*pow(T+40,2)  -0.179411542205399*(T+40)+  4.149132666831214);
+		B=pow((IssmPDouble)10,(IssmPDouble)8)*(0.000072737147457*pow(T+40,3)+  0.002886649363879*pow(T+40,2)  -0.179411542205399*(T+40)+  4.149132666831214);
 	}
 	else if((T>=-35.0) && (T<=-30.0)){
-		B=pow((double)10,(double)8)*(-0.000086144770023*pow(T+35,3)+ 0.003977706575736*pow(T+35,2)  -0.145089762507325*(T+35)+  3.333333333333331);
+		B=pow((IssmPDouble)10,(IssmPDouble)8)*(-0.000086144770023*pow(T+35,3)+ 0.003977706575736*pow(T+35,2)  -0.145089762507325*(T+35)+  3.333333333333331);
 	}
 	else if((T>=-30.0) && (T<=-25.0)){
-		B=pow((double)10,(double)8)*(-0.000043984685769*pow(T+30,3)+ 0.002685535025386*pow(T+30,2)  -0.111773554501713*(T+30)+  2.696559088937191);
+		B=pow((IssmPDouble)10,(IssmPDouble)8)*(-0.000043984685769*pow(T+30,3)+ 0.002685535025386*pow(T+30,2)  -0.111773554501713*(T+30)+  2.696559088937191);
 	}
 	else if((T>=-25.0) && (T<=-20.0)){
-		B=pow((double)10,(double)8)*(-0.000029799523463*pow(T+25,3)+ 0.002025764738854*pow(T+25,2)  -0.088217055680511*(T+25)+  2.199331606342181);
+		B=pow((IssmPDouble)10,(IssmPDouble)8)*(-0.000029799523463*pow(T+25,3)+ 0.002025764738854*pow(T+25,2)  -0.088217055680511*(T+25)+  2.199331606342181);
 	}
 	else if((T>=-20.0) && (T<=-15.0)){
-		B=pow((double)10,(double)8)*(0.000136920904777*pow(T+20,3)+  0.001578771886910*pow(T+20,2)  -0.070194372551690*(T+20)+  1.805165505978111);
+		B=pow((IssmPDouble)10,(IssmPDouble)8)*(0.000136920904777*pow(T+20,3)+  0.001578771886910*pow(T+20,2)  -0.070194372551690*(T+20)+  1.805165505978111);
 	}
 	else if((T>=-15.0) && (T<=-10.0)){
-		B=pow((double)10,(double)8)*(-0.000899763781026*pow(T+15,3)+ 0.003632585458564*pow(T+15,2)  -0.044137585824322*(T+15)+  1.510778053489523);
+		B=pow((IssmPDouble)10,(IssmPDouble)8)*(-0.000899763781026*pow(T+15,3)+ 0.003632585458564*pow(T+15,2)  -0.044137585824322*(T+15)+  1.510778053489523);
 	}
 	else if((T>=-10.0) && (T<=-5.0)){
-		B=pow((double)10,(double)8)*(0.001676964325070*pow(T+10,3)-  0.009863871256831*pow(T+10,2)  -0.075294014815659*(T+10)+  1.268434288203714);
+		B=pow((IssmPDouble)10,(IssmPDouble)8)*(0.001676964325070*pow(T+10,3)-  0.009863871256831*pow(T+10,2)  -0.075294014815659*(T+10)+  1.268434288203714);
 	}
 	else if((T>=-5.0) && (T<=-2.0)){
-		B=pow((double)10,(double)8)*(-0.003748937622487*pow(T+5,3)+0.015290593619213*pow(T+5,2)  -0.048160403003748*(T+5)+  0.854987973338348);
+		B=pow((IssmPDouble)10,(IssmPDouble)8)*(-0.003748937622487*pow(T+5,3)+0.015290593619213*pow(T+5,2)  -0.048160403003748*(T+5)+  0.854987973338348);
 	}
 	else if(T>=-2.0){
-		B=pow((double)10,(double)8)*(-0.003748937622488*pow(T+2,3)-0.018449844983174*pow(T+2,2)  -0.057638157095631*(T+2)+  0.746900791092860);
+		B=pow((IssmPDouble)10,(IssmPDouble)8)*(-0.003748937622488*pow(T+2,3)-0.018449844983174*pow(T+2,2)  -0.057638157095631*(T+2)+  0.746900791092860);
 	}
 
 	/*B cannot be negative!*/
-	if(B<0) B=pow((double)10,(double)6);
+	if(B<0) B=pow((IssmPDouble)10,(IssmPDouble)6);
 
 	return B;
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/PddSurfaceMassBalance.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 12878)
@@ -0,0 +1,205 @@
+/* file:  PddSurfaceMassBlance.cpp
+   Calculating the surface mass balance using the positive degree day method.
+ */
+
+#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){
+
+  // output:
+  IssmDouble B;    // surface mass balance, melt+accumulation
+
+  int    iqj,imonth, j;
+  
+  IssmDouble saccu;     // yearly surface accumulation
+  IssmDouble smelt;     // yearly melt
+  IssmDouble precrunoff;      // yearly runoff
+  IssmDouble prect; // total precipitation during 1 year taking into account des. ef.
+  IssmDouble water; //water=rain + snowmelt 
+  IssmDouble runoff; //meltwater only, does not include rain 
+  IssmDouble sconv; //rhow_rain/rhoi / 12 months
+  
+  IssmDouble density;
+  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 s0t=0.;         // should be set to elevation from temperature source
+  IssmDouble st;             // elevation between altitude of the temp record and current altitude
+  IssmDouble sp;             // elevation between altitude of the prec record and current altitude
+  
+  // PDD and PD constants and variables
+  IssmDouble siglim;          // sigma limit for the integration which is equal to 2.5 sigmanorm
+  IssmDouble signormc = signorm - 0.5;     // sigma of the temperature distribution for cloudy day
+  IssmDouble siglimc, siglim0, siglim0c;
+  IssmDouble PDup, pddsig, PDCUT = 2.0; // PDcut: rain/snow cutoff temperature (C)
+  IssmDouble DT = 0.02;
+  IssmDouble pddt, pd; // pd: snow/precip fraction, precipitation falling as snow
+  
+  IssmDouble q, qmpt; // q is desert/elev. fact, hnpfac is huybrect fact, and pd is normal dist.
+  IssmDouble qm = 0.;        // snow part of the precipitation 
+  IssmDouble qmt = 0.;       // precipitation without desertification effect adjustment
+  IssmDouble qmp = 0.;       // desertification taken into account
+  IssmDouble pdd = 0.;     
+  IssmDouble frzndd = 0.;  
+  
+  IssmDouble tstar;          // monthly mean surface temp
+  IssmDouble Tsum= 0.;       // average summer (JJA) temperature
+  IssmDouble Tsurf = 0.;     // average annual temperature    
+  
+
+  IssmDouble deltm=1./12.;
+  int    ismon[12]={11,0,1,2,3,4,5,6,7,8,9,10};
+  
+  IssmDouble snwm;  // snow that could have been melted in a year.
+  IssmDouble snwmf; //  ablation factor for snow per positive degree day.
+  IssmDouble smf;   //  ablation factor for ice per pdd (Braithwaite 1995 from tarasov 2002).
+  
+  IssmDouble dfrz=1.5, CovrLm=2009./3.35e+5, dCovrLm=dfrz*CovrLm; //m*J kg^-1 C^-1 /(J kg^-1)=m/C yr
+  IssmDouble supice,supcap,diffndd;
+  IssmDouble fsupT=0.5,  fsupndd=0.5;  // Tsurf mode factors for supice
+  IssmDouble pddtj, hmx2;
+  
+  sconv=(rho_water/rho_ice)/12.; //rhow_rain/rhoi / 12 months
+
+  /*PDD constant*/
+  siglim = 2.5*signorm; 
+  siglimc = 2.5*signormc;
+  siglim0 = siglim/DT + 0.5;
+  siglim0c = siglimc/DT + 0.5;
+  PDup = siglimc+PDCUT;
+  
+  // seasonal loop
+    for (iqj = 0; iqj < 12; iqj++){
+      imonth =  ismon[iqj];
+  
+      st=(s-s0t)/1000.;
+      tstar = monthlytemperatures[imonth] - lapser *max(st,sealev);
+      Tsurf = tstar*deltm+Tsurf;        
+      
+      /*********compute PD ****************/
+      if (tstar < PDup){
+	pd = 1.;
+	if (tstar >= -siglimc){ pd = pds[int(tstar/DT + siglim0c)];}}
+      else { 
+	pd = 0.;}
+      
+      /******exp des/elev precip reduction*******/
+      sp=(s-s0p)/1000.; // deselev effect is wrt chng in topo
+      if (sp>0.0){q = exp(-desfac*sp);}
+      else {q = 1.0;}
+      
+      qmt= qmt + monthlyprec[imonth]*sconv;  //*sconv to convert in m of ice equivalent per month
+      qmpt= q*monthlyprec[imonth]*sconv;           
+      qmp= qmp + qmpt;
+      qm= qm + qmpt*pd;
+      
+      /*********compute PDD************/
+      // ndd(month)=-(tstar-pdd(month)) since ndd+pdd gives expectation of
+      // gaussian=T_m, so ndd=-(Tsurf-pdd)
+      if (iqj>5 &&  iqj<9){ Tsum=Tsum+tstar;} 
+      if (tstar >= siglim) {pdd = pdd + tstar*deltm;}
+      else if (tstar> -siglim){
+	pddsig=pdds[int(tstar/DT + siglim0)];
+	pdd = pdd + pddsig*deltm;
+	frzndd = frzndd - (tstar-pddsig)*deltm;}
+      else{frzndd = frzndd - tstar*deltm; }
+  } // end of seasonal loop 
+  
+  //******************************************************************
+    saccu = qm;
+    prect = qmp;     // total precipitation during 1 year taking into account des. ef.
+    Tsum=Tsum/3;
+    
+    /***** determine PDD factors *****/
+    if(Tsum< -1.) {
+      snwmf=2.65*0.001;   //  ablation factor for snow per positive degree day.*0.001 to go from mm to m/ppd
+      smf=17.22*0.001;    //  ablation factor for ice per pdd (Braithwaite 1995 from tarasov 2002)
+    } 
+    else if(Tsum< 10){
+      snwmf = (0.15*Tsum + 2.8)*0.001;
+      smf = (0.0067*pow((10.-Tsum),3) + 8.3)*0.001;
+    }
+    else{
+      snwmf=4.3*0.001;
+      smf=8.3*0.001;
+    }
+    snwmf=0.95*snwmf;
+    smf=0.95*smf;
+    
+    /*****  compute PDD ablation and refreezing *****/
+    pddt = pdd *365;
+    snwm = snwmf*pddt;       // snow that could have been melted in a year
+    hmx2 = min(h,dfrz);   // refreeze active layer max depth: dfrz
+    
+    if(snwm < saccu) {
+      water=prect-saccu + snwm; //water=rain + snowmelt
+      //     l 2.2= capillary factor
+      //     Should refreezing be controlled by frzndd or by mean annual Tsurf?
+      //     dCovrLm concept is of warming of active layer (thickness =d@=1-
+      //     >2m)
+      //     problem with water seepage into ice: should be sealed after
+      //     refreezing
+      //     so everything needs to be predicated on 1 year scale, except for
+      //     thermal
+      //     conductivity through ice
+      //     also, need to account that melt season has low accum, so what's
+      //     going to
+      //     hold the meltwater around for refreezing? And melt-time will have
+      //     low seasonal frzndd
+      
+      //      Superimposed ice :  Pfeffer et al. 1991, Tarasov 2002
+      
+      supice= min(hmx2*CovrLm*frzndd+2.2*(saccu-snwm), water); // superimposed ice
+      supcap=min(2.2*(saccu-snwm),water);
+      runoff=snwm - supice;  //meltwater only, does not include rain
+    }
+    else {  //all snow melted
+      supice= min(hmx2*CovrLm*frzndd, prect );
+      runoff= saccu + smf*(pddt-saccu/snwmf) - supice;
+      supcap=0;
+    }
+    //     pdd melting doesn't cool Tsurf, so ndd refreeze shouldn't warm it
+    //     except pdd melt heat source is atmosphere, while refreeze is
+    //     ground/ice stored interim
+    //     assume pdd=ndd, then melt should equal refreeze and Tsurf should=0
+    //     assume ndd=2*pdd, then all supice is refrozen, but Tsurf should be
+    //     <0
+    //     assume ndd>pdd, little melt => little supice 
+    //     bottom line: compare for Tsurf<0 : supice and no supice case,
+    //     expect Tsurf difference
+    //     except some of cooling flux comes from atmosphere//
+    //     1 dm supice should not raise Tsurf by 1/dCovrLm = 16.675C
+    //     does supice make sense when H< 0.1m? then d=thermoactive ice layer ////
+    //     < 0.1 
+    
+    //     make more sense to just use residual pdd-ndd except that pdd
+    //     residual not clear yet
+    //     frzndd should not be used up by refreezing in snow, so stick in
+    //     supcap.
+    diffndd=0;
+    if (frzndd>0) {
+      diffndd=fsupndd*min((supice-supcap)/dCovrLm ,frzndd);
+      frzndd=frzndd-diffndd;
+    }
+    if(runoff<0){
+      saccu= saccu -runoff;
+      smelt = 0;
+      precrunoff=prect-saccu;
+      //here assume pdd residual is 0, => 
+      Tsurf= max(Tsurf,-frzndd);
+    }
+    else {
+      smelt = runoff;
+      precrunoff=prect-max(0.,supice)-saccu;}
+    //here really need pdd balance, try 0.5 fudge factor?
+    //at least runoff>0 => it's fairly warm, so Tsurf is !<<0,
+    //yet from site plots, can be ice free with Tsurf=-5.5C
+    if(Tsurf<0) {
+      Tsurf= min(Tsurf+fsupT*diffndd , 0.);}
+    
+    B = -smelt+saccu;
+    B = B/yts;
+    pddtj=pddt;
+  
+  return B;
+}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/PrintArrays.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/PrintArrays.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/PrintArrays.cpp	(revision 12878)
@@ -0,0 +1,33 @@
+
+#include "./elements.h"
+#include "../../include/macros.h"
+using namespace std;
+
+void printarray(IssmPDouble* array,int lines,int cols){
+	_printLine_("");
+	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_(" ]");
+	}  
+	_printLine_("");
+}
+void printarray(int* array,int lines,int cols){
+	_printLine_("");
+	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_(" ]");
+	}  
+	_printLine_("");
+}
+void printbinary(int n){
+	unsigned int i=1L<<(sizeof(n)*8-1);
+	while (i>0) {
+		if (n&i)
+		 _printString_("1");
+		else
+		 _printString_("0");
+		i>>=1;
+	}
+}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp	(revision 12878)
@@ -9,5 +9,5 @@
 
 	/*All nodes have the same Coordinate System*/
-	cs_array=(int*)xmalloc(numnodes*sizeof(int));
+	cs_array=xNew<int>(numnodes);
 	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
 
@@ -16,5 +16,5 @@
 
 	/*Clean-up*/
-	xfree((void**)&cs_array);
+	xDelete<int>(cs_array);
 }
 
@@ -23,6 +23,6 @@
 	int     i,j;
 	int     numdofs   = 0;
-	double *transform = NULL;
-	double *values    = NULL;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
 
 	/*Get total number of dofs*/
@@ -31,10 +31,10 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error_("Coordinate system %s not supported yet",EnumToStringx(cs_array[i]));
+			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
 
 	/*Copy current stiffness matrix*/
-	values=(double*)xmalloc(Ke->nrows*Ke->ncols*sizeof(double));
+	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];
 
@@ -49,5 +49,5 @@
 
 	/*Free Matrix*/
-	xfree((void**)&transform);
-	xfree((void**)&values);
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformLoadVectorCoord.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformLoadVectorCoord.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformLoadVectorCoord.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 
 	/*All nodes have the same Coordinate System*/
-	cs_array=(int*)xmalloc(numnodes*sizeof(int));
+	cs_array=xNew<int>(numnodes);
 	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
 
@@ -15,5 +15,5 @@
 
 	/*Clean-up*/
-	xfree((void**)&cs_array);
+	xDelete<int>(cs_array);
 }
 
@@ -22,6 +22,6 @@
 	int     i,j;
 	int     numdofs   = 0;
-	double *transform = NULL;
-	double *values    = NULL;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
 
 	/*Get total number of dofs*/
@@ -30,10 +30,10 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error_("Coordinate system %s not supported yet",EnumToStringx(cs_array[i]));
+			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
 
 	/*Copy current load vector*/
-	values=(double*)xmalloc(pe->nrows*sizeof(double));
+	values=xNew<IssmDouble>(pe->nrows);
 	for(i=0;i<pe->nrows;i++) values[i]=pe->values[i];
 
@@ -46,6 +46,6 @@
 				&pe->values[0],0);
 
-	/*Free Matrix*/
-	xfree((void**)&transform);
-	xfree((void**)&values);
+	/*Free Matrices*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformSolutionCoord.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformSolutionCoord.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformSolutionCoord.cpp	(revision 12878)
@@ -4,10 +4,10 @@
 #include "./elements.h"
 
-void TransformSolutionCoord(double* solution,Node** nodes,int numnodes,int cs_enum){
+void TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int cs_enum){
 
 	int* cs_array=NULL;
 
 	/*All nodes have the same Coordinate System*/
-	cs_array=(int*)xmalloc(numnodes*sizeof(int));
+	cs_array=xNew<int>(numnodes);
 	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
 
@@ -16,13 +16,13 @@
 
 	/*Clean-up*/
-	xfree((void**)&cs_array);
+	xDelete<int>(cs_array);
 }
 
-void TransformSolutionCoord(double* solution,Node** nodes,int numnodes,int* cs_array){
+void TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int* cs_array){
 
 	int     i,j;
 	int     numdofs   = 0;
-	double *transform = NULL;
-	double *values    = NULL;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
 
 	/*Get total number of dofs*/
@@ -31,10 +31,10 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error_("Coordinate system %s not supported yet",EnumToStringx(cs_array[i]));
+			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
 
 	/*Copy current solution vector*/
-	values=(double*)xmalloc(numdofs*sizeof(double));
+	values=xNew<IssmDouble>(numdofs);
 	for(i=0;i<numdofs;i++) values[i]=solution[i];
 
@@ -47,6 +47,6 @@
 				&solution[0],0);
 
-	/*Free Matrix*/
-	xfree((void**)&transform);
-	xfree((void**)&values);
+	/*Free Matrices*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp	(revision 12878)
@@ -9,5 +9,5 @@
 
 	/*All nodes have the same Coordinate System*/
-	cs_array=(int*)xmalloc(numnodes*sizeof(int));
+	cs_array=xNew<int>(numnodes);
 	for(int i=0;i<numnodes;i++) cs_array[i]=cs_enum;
 
@@ -16,5 +16,5 @@
 
 	/*Clean-up*/
-	xfree((void**)&cs_array);
+	xDelete<int>(cs_array);
 }
 
@@ -23,6 +23,6 @@
 	int     i,j;
 	int     numdofs   = 0;
-	double *transform = NULL;
-	double *values    = NULL;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
 
 	/*Get total number of dofs*/
@@ -31,10 +31,10 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error_("Coordinate system %s not supported yet",EnumToStringx(cs_array[i]));
+			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
 
 	/*Copy current stiffness matrix*/
-	values=(double*)xmalloc(Ke->nrows*Ke->ncols*sizeof(double));
+	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];
 
@@ -49,5 +49,5 @@
 
 	/*Free Matrix*/
-	xfree((void**)&transform);
-	xfree((void**)&values);
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Elements/elements.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Elements/elements.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Elements/elements.h	(revision 12878)
@@ -4,19 +4,27 @@
 
 #ifndef _SHARED_ELEMENTS_H_
-#define  _SHARED_ELEMENTS_H_
+#define _SHARED_ELEMENTS_H_
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 class ElementMatrix;
 class ElementVector;
 
-double Paterson(double temperature);
-double Arrhenius(double temperature,double depth,double n);
-void   GetVerticesCoordinates(double* xyz,  Node** nodes, int numvertices);
+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);
+void ComputeDelta18oTemperaturePrecipitation(IssmDouble Delta18oSurfacePresent, IssmDouble Delta18oSurfaceLgm, IssmDouble Delta18oSurfaceTime,
+				     IssmDouble Delta18oPresent, IssmDouble Delta18oLgm, IssmDouble Delta18oTime, 
+				     IssmDouble* PrecipitationsPresentday,
+				     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(double** ptransform,Node** nodes,int numnodes,int* cs_array);
+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);
@@ -25,37 +33,11 @@
 void   TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int cs_enum);
 void   TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int* cs_array);
-void   TransformSolutionCoord(double* solution,Node** nodes,int numnodes,int cs_enum);
-void   TransformSolutionCoord(double* solution,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
 
-inline void printarray(double* array,int lines,int cols=1){
-	printf("\n");
-	for(int i=0;i<lines;i++){  
-		printf("   [ ");
-		for(int j=0;j<cols;j++) printf(" %12.7g ",array[i*cols+j]);
-		printf(" ]\n");
-	}  
-	printf("\n");
-}
-inline void printarray(int* array,int lines,int cols=1){
-	printf("\n");
-	for(int i=0;i<lines;i++){  
-		printf("   [ ");
-		for(int j=0;j<cols;j++) printf(" %6i",array[i*cols+j]);
-		printf(" ]\n");
-	}  
-	printf("\n");
-}
-inline void printbinary(int n) {
-	unsigned int i=1L<<(sizeof(n)*8-1);
-
-	while (i>0) {
-		if (n&i)
-		 printf("1");
-		else
-		 printf("0");
-		i>>=1;
-	}
-}
-
+/*Print arrays*/
+void printarray(IssmPDouble* array,int lines,int cols=1);
+void printarray(int* array,int lines,int cols=1);
+void printbinary(int n);
 #endif //ifndef _SHARED_ELEMENTS_H_
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Exceptions/Exceptions.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Exceptions/Exceptions.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Exceptions/Exceptions.cpp	(revision 12878)
@@ -20,5 +20,5 @@
 }
 
-ErrorException::ErrorException(string what_file,string what_function,int what_line,string what_arg){
+ErrorException::ErrorException(const string& what_file, const string& what_function,int what_line, const string& what_arg){
 
 	what_str=what_arg;
@@ -44,14 +44,14 @@
 
 	if (function_name=="" || file_line==0){ //WINDOWS
-		printf("%s%s","Error message: ",what());
+		_printString_("Error message: " << what());
 	}
 	else{
 		if(num_procs==1){
-			printf("\n??? Error using ==> %s:%i\n",file_name.c_str(),file_line);
-			printf("%s error message: %s\n\n",function_name.c_str(),what());
+			_printLine_("\n??? Error using ==> " << file_name.c_str() << ":" << file_line);
+			_printLine_(function_name.c_str() << " error message: " << what() << "\n");
 		}
 		else{
-			printf("\n[%i] ??? Error using ==> %s:%i\n",my_rank,file_name.c_str(),file_line);
-			printf("[%i] %s error message: %s\n\n",my_rank,function_name.c_str(),what());
+			_printLine_("\n[" << my_rank << "] ??? Error using ==> " << file_name.c_str() << ":" << file_line);
+			_printLine_("[" << my_rank << "] " << function_name.c_str() << " error message: " << what() << "\n");
 		}
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Exceptions/exceptions.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Exceptions/exceptions.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Exceptions/exceptions.h	(revision 12878)
@@ -24,5 +24,5 @@
 	public:
 	ErrorException(const string &what_arg); //for windows
-	ErrorException(string what_file,string what_function,int what_line,string what_arg);//UNIX
+	ErrorException(const string&  what_file,const string& what_function,int what_line,const string& what_arg);//UNIX
 	~ErrorException() throw();
 	virtual const char *what() const throw();
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Exceptions/exprintf.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Exceptions/exprintf.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Exceptions/exprintf.cpp	(revision 12878)
@@ -9,4 +9,5 @@
 #include <stdarg.h>
 #include <stdio.h>
+#include "../Alloc/xNewDelete.h"
 #include "../Alloc/alloc.h"
 
@@ -14,17 +15,37 @@
 
 	/*returned string: */
-	char* string=NULL;
+	char *buffer = NULL;
+	int   n,size = 100;
+	int   string_size;
 
-	/*Assum nobody will print more that 1024 characters!*/
-	string=(char*)xmalloc(1024*sizeof(char));//assume that nobody will print more than 1024 characters at once.
-                                                                                                                                                                                                     
 	//variable list of arguments
-	va_list ap;
+	va_list args;
 
-	//First use vsprintf to get the whole input string.
-	va_start(ap,format);
-	vsprintf(string,format,ap); //printf style coding 
-	va_end(ap); 
+	while(true){
 
-	return string;
+		/*allocate buffer for given string size*/
+		buffer=xNew<char>(size);
+
+		/* Try to print in the allocated space. */
+		va_start(args, format);
+#ifndef WIN32
+		n=vsnprintf(buffer,size,format,args);
+#else
+		n=vsnprintf(buffer,size,format,args);
+#endif
+		va_end(args);
+
+		/* If that worked, return the string. */
+		if(n>-1 && n<size) break;
+
+		/* Else try again with more space. */
+		if(n>-1)   /* glibc 2.1 */
+		 size=n+1; /* precisely what is needed */
+		else       /* glibc 2.0 */
+		 size*=2;  /* twice the old size */
+
+		xDelete<char>(buffer);
+	}
+
+	return buffer;
 }
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineRead.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineRead.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineRead.cpp	(revision 12878)
@@ -7,7 +7,8 @@
 
 #include <stdio.h>
+#include <cstring> 
 #include "../Alloc/alloc.h"
 #include "../../include/include.h"
-#include "../../objects/objects.h"
+#include "../../classes/classes.h"
 #include "../Exceptions/exceptions.h"
 #include "../../Container/DataSet.h"
@@ -19,24 +20,24 @@
 
 	/*I/O: */
-	FILE* fid=NULL;
-	char chardummy[256];
+	FILE   *fid = NULL;
+	char    chardummy[256];
 	double  ddummy;
 
 	/*output: */
-	int nprof; //number of profiles in the domainname file
-	int* profnvertices=NULL; //array holding the number of vertices for the nprof profiles
-	double** pprofx=NULL; //array of profiles x coordinates
-	double** pprofy=NULL; //array of profiles y coordinates
-	bool* closed=NULL; //array holding closed flags for the nprof profiles
+	int      nprof;                //number of profiles in the domainname file
+	int     *profnvertices = NULL; //array holding the number of vertices for the nprof profiles
+	double **pprofx        = NULL; //array of profiles x coordinates
+	double **pprofy        = NULL; //array of profiles y coordinates
+	bool    *closed        = NULL; //array holding closed flags for the nprof profiles
 
 	/*For each profile: */
-	int n;
-	double* x=NULL;
-	double* y=NULL;
-	bool cl;
+	int     n;
+	double *x  = NULL;
+	double *y  = NULL;
+	bool    cl;
 
 	/*open domain outline file for reading: */
 	if ((fid=fopen(domainname,"r"))==NULL){
-		_error_("%s%s","could not find domain file ",domainname); 
+		_error2_("could not find domain file " << domainname); 
 	}
 
@@ -61,12 +62,12 @@
 	
 	/*Allocate and initialize all the profiles: */
-	profnvertices=(int*)xmalloc(nprof*sizeof(int));
-	pprofx=(double**)xmalloc(nprof*sizeof(double*));
-	pprofy=(double**)xmalloc(nprof*sizeof(double*));
+	profnvertices=xNew<int>(nprof);
+	pprofx=xNew<double*>(nprof);
+	pprofy=xNew<double*>(nprof);
 	for (i=0;i<nprof;i++){
 		pprofx[i]=NULL;
 		pprofy[i]=NULL;
 	}
-	closed=(bool*)xmalloc(nprof*sizeof(bool));
+	closed=xNew<bool>(nprof);
 
 	/*Reaset file pointer to beginning of file: */
@@ -88,8 +89,7 @@
 
 		/*Allocate vertices: */
-		x=(double*)xmalloc(n*sizeof(double));
-		y=(double*)xmalloc(n*sizeof(double));
+		x=xNew<double>(n);
+		y=xNew<double>(n);
 		
-
 		/*Read vertices: */
 		for (i=0;i<n;i++){
@@ -118,6 +118,8 @@
 	*ppprofx=pprofx;
 	*ppprofy=pprofy;
-	if(pclosed)*pclosed=closed;
-	else       xfree((void**)&closed);
+	if(pclosed)
+	 *pclosed=closed;
+	else
+	 xDelete<bool>(closed);
 }
 
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineWrite.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineWrite.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Exp/DomainOutlineWrite.cpp	(revision 12878)
@@ -23,5 +23,5 @@
 	/*open domain outline file for writing: */
 	if ((fid=fopen(domainname,"w"))==NULL){
-		_error_("%s%s","could not open domain file ",domainname); 
+		_error2_("could not open domain file " << domainname); 
 		noerr=0; goto cleanupandreturn;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Exp/IsInPoly.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Exp/IsInPoly.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Exp/IsInPoly.cpp	(revision 12878)
@@ -14,5 +14,5 @@
 #endif
 
-/*IsInPoly {{{1*/
+/*IsInPoly {{{*/
 int IsInPoly(Vector* in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue){
 
@@ -55,5 +55,5 @@
 	 return 1;
 }/*}}}*/
-/*IsOutsidePoly {{{1*/
+/*IsOutsidePoly {{{*/
 int IsOutsidePoly(Vector* in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue){
 
@@ -96,5 +96,5 @@
 	return 1;
 }/*}}}*/
-/*pnpoly{{{1*/
+/*pnpoly{{{*/
 int pnpoly(int npol, double *xp, double *yp, double x, double y, int edgevalue) {
 	int i, j, c = 0;
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Exp/exp.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Exp/exp.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Exp/exp.h	(revision 12878)
@@ -7,5 +7,5 @@
 #define _EXP_H_
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../toolkits/toolkits.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Matrix/MatrixUtils.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Matrix/MatrixUtils.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Matrix/MatrixUtils.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 /*Headers*/
-/*{{{1*/
+/*{{{*/
 #include "./matrix.h"
 #include "../Exceptions/exceptions.h"
@@ -16,10 +16,10 @@
 /*}}}*/
 
-/*FUNCTION TripleMultiply {{{1*/
-int TripleMultiply( double* a, int nrowa, int ncola, int itrna, double* b, int nrowb, int ncolb, int itrnb, double* c, int nrowc, int ncolc, int itrnc, double* d, int iaddd){
+/*FUNCTION TripleMultiply {{{*/
+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){
 	/*TripleMultiply    Perform triple matrix product a*b*c+d.*/
 	
 	int idima,idimb,idimc,idimd;
-	double* dtemp;
+	IssmDouble* dtemp;
 
 /*  set up dimensions for triple product  */
@@ -36,5 +36,5 @@
 	if (!itrnb) {
 		if (nrowb != idimb) {
-			_error_("Matrix A and B inner vectors not equal size.");
+			_error2_("Matrix A and B inner vectors not equal size.");
 		}
 		idimc=ncolb;
@@ -42,5 +42,5 @@
 	else {
 		if (ncolb != idimb) {
-			_error_("Matrix A and B inner vectors not equal size.");
+			_error2_("Matrix A and B inner vectors not equal size.");
 		}
 		idimc=nrowb;
@@ -49,5 +49,5 @@
 	if (!itrnc) {
 		if (nrowc != idimc) {
-			_error_("Matrix B and C inner vectors not equal size.");
+			_error2_("Matrix B and C inner vectors not equal size.");
 		}
 		idimd=ncolc;
@@ -55,5 +55,5 @@
 	else {
 		if (ncolc != idimc) {
-			_error_("Matrix B and C inner vectors not equal size.");
+			_error2_("Matrix B and C inner vectors not equal size.");
 		}
 		idimd=nrowc;
@@ -62,6 +62,6 @@
 /*  perform the matrix triple product in the order that minimizes the
 	number of multiplies and the temporary space used, noting that
-	(a*b)*c requires ac(b+d) multiplies and ac doubles, and a*(b*c)
-	requires bd(a+c) multiplies and bd doubles (both are the same for
+	(a*b)*c requires ac(b+d) multiplies and ac IssmDoubles, and a*(b*c)
+	requires bd(a+c) multiplies and bd IssmDoubles (both are the same for
 	a symmetric triple product)  */
 
@@ -69,14 +69,9 @@
 
 	if (idima*idimc*(idimb+idimd) <= idimb*idimd*(idima+idimc)) {
-		dtemp=(double *) xmalloc(idima*idimc*sizeof(double));
-
-		MatrixMultiply(a    ,nrowa,ncola,itrna,
-				   b    ,nrowb,ncolb,itrnb,
-				   dtemp,0);
-		MatrixMultiply(dtemp,idima,idimc,0    ,
-				   c    ,nrowc,ncolc,itrnc,
-				   d    ,iaddd);
-
-		xfree((void **)&dtemp);
+		dtemp=xNew<IssmDouble>(idima*idimc);
+
+		MatrixMultiply(a,nrowa,ncola,itrna,b,nrowb,ncolb,itrnb,dtemp,0);
+		MatrixMultiply(dtemp,idima,idimc,0,c,nrowc,ncolc,itrnc,d,iaddd);
+		xDelete<IssmDouble>(dtemp);
 	}
 
@@ -84,20 +79,15 @@
 
 	else {
-		dtemp=(double *) xmalloc(idimb*idimd*sizeof(double));
-
-		MatrixMultiply(b    ,nrowb,ncolb,itrnb,
-				   c    ,nrowc,ncolc,itrnc,
-				   dtemp,0);
-		MatrixMultiply(a    ,nrowa,ncola,itrna,
-				   dtemp,idimb,idimd,0    ,
-				   d    ,iaddd);
-
-		xfree((void **)&dtemp);
+		dtemp=xNew<IssmDouble>(idimb*idimd);
+
+		MatrixMultiply(b,nrowb,ncolb,itrnb,c,nrowc,ncolc,itrnc,dtemp,0);
+		MatrixMultiply(a,nrowa,ncola,itrna,dtemp,idimb,idimd,0,d,iaddd);
+		xDelete<IssmDouble>(dtemp);
 	}
 
 	return 1;
 }/*}}}*/
-/*FUNCTION MatrixMuliply {{{1*/
-int MatrixMultiply( double* a, int nrowa, int ncola, int itrna, double* b, int nrowb, int ncolb, int itrnb, double* c, int iaddc ){
+/*FUNCTION MatrixMuliply {{{*/
+int MatrixMultiply( IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int iaddc ){
 	/*MatrixMultiply    Perform matrix multiplication a*b+c.*/
 	int noerr=1;
@@ -134,5 +124,5 @@
 
 	if (ntrma != ntrmb) {
-		_error_("Matrix A and B inner vectors not equal size");
+		_error2_("Matrix A and B inner vectors not equal size");
 	    noerr=0;	
 		return noerr;
@@ -167,6 +157,6 @@
 	return noerr;
 }/*}}}*/
-/*FUNCTION MatrixInverse {{{1*/
-int MatrixInverse( double* a, int ndim, int nrow, double* b, int nvec, double* pdet ){
+/*FUNCTION MatrixInverse {{{*/
+int MatrixInverse( IssmDouble* a, int ndim, int nrow, IssmDouble* b, int nvec, IssmDouble* pdet ){
 /* MatrixInverse    Perform matrix inversion and linear equation solution.
 
@@ -181,9 +171,9 @@
 	int noerr=1;
 	int i,j,k,ipt,jpt,irow,icol,ipiv,ncol;
-	int (*pivrc)[2],*pindx;
-	double pivot,det,dtemp;
+	int *pivrc1,*pivrc2,*pindx;
+	IssmDouble pivot,det,dtemp;
 
 	if (!b && nvec) {
-		_error_("No right-hand side for nvec=%d.",nvec);
+		_error2_("No right-hand side for nvec=" << nvec << ".");
 		noerr=0;
 		return noerr;
@@ -198,7 +188,7 @@
 	ncol=nrow;
 	det=1.;
-
-	pivrc = (int (*)[2]) xmalloc((nrow*2)*sizeof(int));
-	pindx = (int (*)   ) xcalloc( nrow   ,sizeof(int));
+	pivrc1 =xNew<int>(nrow);
+	pivrc2 =xNew<int>(nrow);
+	pindx =xNew<int>(nrow);
 
 /*  loop over the rows/columns of the matrix  */
@@ -221,13 +211,14 @@
 
 		if (fabs(pivot) < DBL_EPSILON) {
-			xfree((void **)&pivrc);
-			xfree((void **)&pindx);
-			_error_("Pivot %f less than machine epsilon",pivot);
+			xDelete<int>(pivrc1);
+			xDelete<int>(pivrc2);
+			xDelete<int>(pindx);
+			_error2_("Pivot " << pivot << " less than machine epsilon");
 			noerr=0;
 			return noerr;
 		}
 
-		pivrc[i][0]=irow;
-		pivrc[i][1]=icol;
+		pivrc1[i]=irow;
+		pivrc2[i]=icol;
 
 		ipiv=icol;
@@ -319,7 +310,7 @@
 		j=(nrow-1)-i;
 
-		if (pivrc[j][0] != pivrc[j][1]) {
-			irow=pivrc[j][0];
-			icol=pivrc[j][1];
+		if (pivrc1[j] != pivrc2[j]) {
+			irow=pivrc1[j];
+			icol=pivrc2[j];
 
 //			_printf_(true,"column switch back for j=%d: irow=%d, icol=%d\n",
@@ -336,14 +327,12 @@
 	}
 
-	if (pdet)
-		*pdet=det;
-
-	xfree((void **)&pivrc);
-	xfree((void **)&pindx);
-
+	if (pdet) *pdet=det;
+	xDelete<int>(pivrc1);
+	xDelete<int>(pivrc2);
+	xDelete<int>(pindx);
 	return noerr;
 }/*}}}*/
-/*FUNCTION Matrix2x2Determinant(double* Adet,double* A) {{{1*/
-void Matrix2x2Determinant(double* Adet,double* A){
+/*FUNCTION Matrix2x2Determinant(IssmDouble* Adet,IssmDouble* A) {{{*/
+void Matrix2x2Determinant(IssmDouble* Adet,IssmDouble* A){
 	/*Compute determinant of a 2x2 matrix*/
 
@@ -352,13 +341,13 @@
 }
 /*}}}*/
-/*FUNCTION Matrix2x2Invert(double* Ainv,double* A) {{{1*/
-void Matrix2x2Invert(double* Ainv,double* A){
+/*FUNCTION Matrix2x2Invert(IssmDouble* Ainv,IssmDouble* A) {{{*/
+void Matrix2x2Invert(IssmDouble* Ainv,IssmDouble* A){
 
 	/*Intermediaries*/
-	double det;
+	IssmDouble det;
 
 	/*Compute determinant*/
 	Matrix2x2Determinant(&det,A);
-	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller that machine epsilon");
+	if (fabs(det) < DBL_EPSILON) _error2_("Determinant smaller that machine epsilon");
 
 	/*Compute invert*/
@@ -369,6 +358,6 @@
 
 }/*}}}*/
-/*FUNCTION Matrix3x3Determinant(double* Adet,double* A) {{{1*/
-void Matrix3x3Determinant(double* Adet,double* A){
+/*FUNCTION Matrix3x3Determinant(IssmDouble* Adet,IssmDouble* A) {{{*/
+void Matrix3x3Determinant(IssmDouble* Adet,IssmDouble* A){
 	/*Compute determinant of a 3x3 matrix*/
 
@@ -377,13 +366,13 @@
 }
 /*}}}*/
-/*FUNCTION Matrix3x3Invert(double* Ainv,double* A) {{{1*/
-void Matrix3x3Invert(double* Ainv,double* A){
+/*FUNCTION Matrix3x3Invert(IssmDouble* Ainv,IssmDouble* A) {{{*/
+void Matrix3x3Invert(IssmDouble* Ainv,IssmDouble* A){
 
 	/*Intermediaries*/
-	double det;
+	IssmDouble det;
 
 	/*Compute determinant*/
 	Matrix3x3Determinant(&det,A);
-	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller that machine epsilon");
+	if (fabs(det) < DBL_EPSILON) _error2_("Determinant smaller that machine epsilon");
 
 	/*Compute invert*/
@@ -399,6 +388,6 @@
 
 }/*}}}*/
-/*FUNCTION MatrixTranspose(double* Adet,double* A) {{{1*/
-void MatrixTranspose(double* tA,double* A, int nrows, int ncols){
+/*FUNCTION MatrixTranspose(IssmDouble* Adet,IssmDouble* A) {{{*/
+void MatrixTranspose(IssmDouble* tA,IssmDouble* A, int nrows, int ncols){
 	/*Transpose a n*m matrix*/
 
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Matrix/matrix.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Matrix/matrix.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Matrix/matrix.h	(revision 12878)
@@ -6,12 +6,14 @@
 #define _MATRIXUTILS_H_
 
-int  TripleMultiply( double* a, int nrowa, int ncola, int itrna, double* b, int nrowb, int ncolb, int itrnb, double* c, int nrowc, int ncolc, int itrnc, double* d, int iaddd);
-int  MatrixMultiply( double* a, int nrowa, int ncola, int itrna, double* b, int nrowb, int ncolb, int itrnb, double* c, int iaddc );
-int  MatrixInverse( double* a, int ndim, int nrow, double* b, int nvec, double* pdet );
-void Matrix2x2Invert(double* Ainv, double* A);
-void Matrix2x2Determinant(double* Adet,double* A);
-void Matrix3x3Invert(double* Ainv, double* A);
-void Matrix3x3Determinant(double* Adet,double* A);
-void MatrixTranspose(double* tA,double* A,int nrows, int ncols);
+#include "../../include/include.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);
+int  MatrixMultiply( IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int iaddc );
+int  MatrixInverse( IssmDouble* a, int ndim, int nrow, IssmDouble* b, int nvec, IssmDouble* pdet );
+void Matrix2x2Invert(IssmDouble* Ainv, IssmDouble* A);
+void Matrix2x2Determinant(IssmDouble* Adet,IssmDouble* A);
+void Matrix3x3Invert(IssmDouble* Ainv, IssmDouble* A);
+void Matrix3x3Determinant(IssmDouble* Adet,IssmDouble* A);
+void MatrixTranspose(IssmDouble* tA,IssmDouble* A,int nrows, int ncols);
 
 #endif //ifndef _MATRIXUTILS_H_
Index: /issm/branches/trunk-jpl-damage/src/c/shared/MemOps/xMemCpy.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/MemOps/xMemCpy.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/MemOps/xMemCpy.h	(revision 12878)
@@ -0,0 +1,19 @@
+/* \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/branches/trunk-jpl-damage/src/c/shared/Numerics/BrentSearch.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/BrentSearch.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/BrentSearch.cpp	(revision 12878)
@@ -10,11 +10,12 @@
 
 #include "./numerics.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../include/include.h"
 #include "../../io/io.h"
 #include "../../shared/shared.h"
 #include <float.h>
-
-void BrentSearch(double* psearch_scalar,double* pJ,OptPars* optpars,double (*f)(double,OptArgs*), OptArgs* optargs){
+#include <iomanip>
+
+void BrentSearch(IssmDouble* psearch_scalar,IssmDouble* pJ,OptPars* optpars,IssmDouble (*f)(IssmDouble,OptArgs*), OptArgs* optargs){
 
 	/* This routine is optimizing a given function using Brent's method
@@ -22,15 +23,15 @@
 
 	/*Intermediary*/
-	double si,gold,intervalgold,oldintervalgold;
-	double parab_num,parab_den;
-	double distance,cm_jump;
-	double fxmax,fxmin,fxbest;
-	double fx,fx1,fx2;
-	double xmax,xmin,xbest;
-	double x,x1,x2,xm;
-	double tol1,tol2,seps;
-	double tolerance=1.e-4;
-	int    maxiter,iter;
-	bool   loop=true,goldenflag;
+	IssmDouble si,gold,intervalgold,oldintervalgold;
+	IssmDouble parab_num,parab_den;
+	IssmDouble distance,cm_jump;
+	IssmDouble fxmax,fxmin,fxbest;
+	IssmDouble fx,fx1,fx2;
+	IssmDouble xmax,xmin,xbest;
+	IssmDouble x,x1,x2,xm;
+	IssmDouble tol1,tol2,seps;
+	IssmDouble tolerance = 1.e-4;
+	int        maxiter ,iter;
+	bool       loop= true,goldenflag;
 
 	/*Recover parameters:*/
@@ -43,13 +44,16 @@
 	iter=0;
 	fxmin = (*f)(xmin,optargs);
-	if (isnan(fxmin)) _error_("Function evaluation returned NaN");
-	_printf_(VerboseControl(),"\n        Iteration         x           f(x)       Tolerance         Procedure\n\n");
-	_printf_(VerboseControl(),"        %s    %12.6g  %12.6g  %s","   N/A",xmin,fxmin,"         N/A         boundary\n");
+	if (xIsNan<IssmDouble>(fxmin)) _error2_("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");
 	fxmax = (*f)(xmax,optargs);
-	if (isnan(fxmax)) _error_("Function evaluation returned NaN");
-	_printf_(VerboseControl(),"        %s    %12.6g  %12.6g  %s","   N/A",xmax,fxmax,"         N/A         boundary\n");
+	if (xIsNan<IssmDouble>(fxmax)) _error2_("Function evaluation returned NaN");
+	if(VerboseControl()) _pprintLine_("           N/A    "<<setw(12)<<xmax<<"  "<<setw(12)<<fxmax<<"           N/A         boundary");
 
 	/*test if jump option activated and xmin==0*/
-	if (!isnan(cm_jump) && (xmin==0) && (fxmax/fxmin)<cm_jump){
+	if (!xIsNan<IssmDouble>(cm_jump) && (xmin==0) && (fxmax/fxmin)<cm_jump){
 		*psearch_scalar=xmax;
 		*pJ=fxmax;
@@ -58,5 +62,5 @@
 
 	/*initialize optimization variables*/
-	seps=sqrt(DBL_EPSILON);    //precision of a double
+	seps=sqrt(DBL_EPSILON);    //precision of a IssmDouble
 	distance=0.0;              //new_x=old_x + distance
 	gold=0.5*(3.0-sqrt(5.0));  //gold = 1 - golden ratio
@@ -71,5 +75,5 @@
 	/*2: call the function to be evaluated*/
 	fxbest = (*f)(x,optargs);
-	if(isnan(fxbest)) _error_("Function evaluation returned NaN");
+	if(xIsNan<IssmDouble>(fxbest)) _error2_("Function evaluation returned NaN");
 	iter=iter+1;
 
@@ -84,7 +88,8 @@
 
 	/*4: print result*/
-	_printf_(VerboseControl(),"         %5i    %12.6g  %12.6g  %12.6g  %s\n",iter,xbest,fxbest,pow(pow(xbest-xm,2),0.5),"       initial");
-	if (!isnan(cm_jump) && (xmin==0) && ((fxbest/fxmin)<cm_jump)){
-		_printf_(VerboseControl(),"      optimization terminated: current x satisfies criteria 'cm_jump'=%g\n",cm_jump);
+	if(VerboseControl())
+	 _pprintLine_("         "<<setw(5)<<iter<<"    "<<setw(12)<<xbest<<"  "<<setw(12)<<fxbest<<"  "<<setw(12)<<pow(pow(xbest-xm,2),0.5)<<"         initial");
+	if (!xIsNan<IssmDouble>(cm_jump) && (xmin==0) && ((fxbest/fxmin)<cm_jump)){
+		if(VerboseControl()) _pprintLine_("      optimization terminated: current x satisfies criteria 'cm_jump'=" << cm_jump);
 		loop=false;
 	}
@@ -154,5 +159,5 @@
 		//evaluate function on x
 		fx = (*f)(x,optargs);
-		if(isnan(fx)) _error_("Function evaluation returned NaN");
+		if(xIsNan<IssmDouble>(fx)) _error2_("Function evaluation returned NaN");
 		iter=iter+1;
 
@@ -179,17 +184,19 @@
 		tol1=seps*pow(pow(xbest,2),0.5)+tolerance/3.0;
 		tol2=2.0*tol1;
-		_printf_(VerboseControl(),"         %5i    %12.6g  %12.6g  %12.6g  %s\n",iter,x,fx,pow(pow(xbest-xm,2),0.5),goldenflag?"       golden":"       parabolic");
+		if(VerboseControl())
+		 _pprintLine_("         "<<setw(5)<<iter<<"    "<<setw(12)<<x<<"  "<<setw(12)<<fx<<"  "<<setw(12)<<pow(pow(xbest-xm,2),0.5)<<
+					 "         "<<(goldenflag?"golden":"parabolic"));
 
 		/*Stop the optimization?*/
 		if (sqrt(pow(xbest-xm,2)) < (tol2-0.5*(xmax-xmin))){
-			_printf_(VerboseControl(),"      optimization terminated: current x satisfies criteria 'tolx'=%g\n",tolerance);
+			if(VerboseControl()) _pprintLine_("      optimization terminated: current x satisfies criteria 'tolx'=" << tolerance);
 			loop=false;
 		}
 		else if (iter>=maxiter){
-			_printf_(VerboseControl(),"      exiting: Maximum number of iterations has been exceeded  ('maxiter'=%i)\n",maxiter);
+			if(VerboseControl()) _pprintLine_("      exiting: Maximum number of iterations has been exceeded  ('maxiter'=" << maxiter << ")");
 			loop=false;
 		}
-		else if (!isnan(cm_jump) && (xmin==0) && ((fxbest/fxmin)<cm_jump)){
-			_printf_(VerboseControl(),"      optimization terminated: current x satisfies criteria 'cm_jump'=%g\n",cm_jump);
+		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);
 			loop=false;
 		}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.cpp	(revision 12878)
@@ -1,7 +1,7 @@
 /*  Gauss point structures and prototypes  */
 
+#include "../../include/include.h"
 #include "./GaussPoints.h"
 #include "../Alloc/alloc.h"
-#include "../../include/include.h"
 #include "../../io/io.h"
 #include "../Exceptions/exceptions.h"
@@ -10,6 +10,6 @@
 
 /*General Gauss points*/
-/*FUNCTION GaussLegendreLinear {{{1*/
-void GaussLegendreLinear( double** pxgaus, double** pxwgt, int ngaus){
+/*FUNCTION GaussLegendreLinear {{{*/
+void GaussLegendreLinear( IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus){
 	/* Gauss-Legendre quadrature points.
 
@@ -25,33 +25,33 @@
 	/*Intermediaries*/
 	int i;
-	double *alpha,*beta;
+	IssmPDouble *alpha,*beta;
 
 	/*p= 1, npoint= 1*/
-	static double wgt1[]={2.000000000000000};
-	static double xi1[]={0.000000000000000};
+	static IssmPDouble wgt1[]={2.000000000000000};
+	static IssmPDouble xi1[]={0.000000000000000};
 
 	/*p= 3, npoint= 2*/
-	static double wgt2[]={1.000000000000000, 1.000000000000000};
-	static double xi2[]={-0.577350269189626, 0.577350269189626};
+	static IssmPDouble wgt2[]={1.000000000000000, 1.000000000000000};
+	static IssmPDouble xi2[]={-0.577350269189626, 0.577350269189626};
 
 	/*p= 5, npoint= 3*/
-	static double wgt3[]={0.555555555555556, 0.888888888888889, 0.555555555555556};
-	static double xi3[]={-0.774596669241483, 0.000000000000000, 0.774596669241483};
+	static IssmPDouble wgt3[]={0.555555555555556, 0.888888888888889, 0.555555555555556};
+	static IssmPDouble xi3[]={-0.774596669241483, 0.000000000000000, 0.774596669241483};
 
 	/*p= 7, npoint= 4*/
-	static double wgt4[]={0.347854845137454, 0.652145154862546, 0.652145154862546, 0.347854845137454};
-	static double xi4[]={-0.861136311594053,-0.339981043584856, 0.339981043584856, 0.861136311594053};
-
-	static double* wgtp[MAX_LINE_GAUS_PTS]={wgt1 ,wgt2 ,wgt3 ,wgt4 };
-	static double* xip [MAX_LINE_GAUS_PTS]={xi1  ,xi2  ,xi3  ,xi4  };
-
-	static int np[MAX_LINE_GAUS_PTS]={sizeof(wgt1 )/sizeof(double),
-		sizeof(wgt2 )/sizeof(double),
-		sizeof(wgt3 )/sizeof(double),
-		sizeof(wgt4 )/sizeof(double)};
-
-	//	_printf_(true,"Gauss-Legendre recurrence coefficients ngaus=%d\n",ngaus);
-	*pxgaus = (double *) xmalloc(ngaus*sizeof(double));
-	*pxwgt  = (double *) xmalloc(ngaus*sizeof(double));
+	static IssmPDouble wgt4[]={0.347854845137454, 0.652145154862546, 0.652145154862546, 0.347854845137454};
+	static IssmPDouble xi4[]={-0.861136311594053,-0.339981043584856, 0.339981043584856, 0.861136311594053};
+
+	static IssmPDouble* wgtp[MAX_LINE_GAUS_PTS]={wgt1 ,wgt2 ,wgt3 ,wgt4 };
+	static IssmPDouble* xip [MAX_LINE_GAUS_PTS]={xi1  ,xi2  ,xi3  ,xi4  };
+
+	static int np[MAX_LINE_GAUS_PTS]={sizeof(wgt1 )/sizeof(IssmPDouble),
+		sizeof(wgt2 )/sizeof(IssmPDouble),
+		sizeof(wgt3 )/sizeof(IssmPDouble),
+		sizeof(wgt4 )/sizeof(IssmPDouble)};
+
+	//	_pprintLine_("Gauss-Legendre recurrence coefficients ngaus=" << ngaus);
+	*pxgaus =xNew<IssmPDouble>(ngaus);
+	*pxwgt  =xNew<IssmPDouble>(ngaus);
 
 	/*  check to see if Gauss points need to be calculated  */
@@ -70,6 +70,6 @@
 
 		/*  calculate the Gauss points using recurrence relations  */
-		alpha=(double *) xmalloc(ngaus*sizeof(double));
-		beta =(double *) xmalloc(ngaus*sizeof(double));
+		alpha=xNew<IssmPDouble>(ngaus);
+		beta =xNew<IssmPDouble>(ngaus);
 
 		/*  calculate the Legendre recurrence coefficients  */
@@ -84,10 +84,10 @@
 		/*  calculate the Gauss points  */
 		GaussRecur(*pxgaus, *pxwgt, ngaus, alpha, beta );
-		xfree((void **)&beta );
-		xfree((void **)&alpha);
+		xDelete<IssmPDouble>(beta);
+		xDelete<IssmPDouble>(alpha);
 	}
-}/*}}}1*/
-/*FUNCTION GaussLegendreTria{{{1*/
-void GaussLegendreTria( int* pngaus, double** pl1, double** pl2, double** pl3, double** pwgt, int iord ) {
+}/*}}}*/
+/*FUNCTION GaussLegendreTria{{{*/
+void GaussLegendreTria( int* pngaus, IssmPDouble** pl1, IssmPDouble** pl2, IssmPDouble** pl3, IssmPDouble** pwgt, int iord ) {
 	/*Gauss quadrature points for the triangle.
 
@@ -98,98 +98,98 @@
 	/*Intermediaries*/
 	int i,j,ipt,nigaus;
-	double xi,eta;
-	double *xgaus=NULL,*xwgt=NULL,*egaus,*ewgt;
+	IssmPDouble xi,eta;
+	IssmPDouble *xgaus=NULL,*xwgt=NULL,*egaus,*ewgt;
 
 	/*Hardcoded Gauss points declaration*/
-	/*p= 1, npoint= 1{{{2*/
-	static double wgt1[]={
+	/*p= 1, npoint= 1{{{*/
+	static IssmPDouble wgt1[]={
 		1.732050807568877};
-	static double l11[]={
+	static IssmPDouble l11[]={
 		0.333333333333333};
-	static double l21[]={
+	static IssmPDouble l21[]={
 		0.333333333333333};
-	static double l31[]={
+	static IssmPDouble l31[]={
 		0.333333333333333};
-	/*}}}2*/
-	/*p= 2, npoint= 3  {{{2*/
-	static double wgt2[]={
+	/*}}}*/
+	/*p= 2, npoint= 3  {{{*/
+	static IssmPDouble wgt2[]={
 		0.577350269189625, 0.577350269189625, 0.577350269189625};
-	static double l12[]={
+	static IssmPDouble l12[]={
 		0.666666666666667, 0.166666666666667, 0.166666666666667};
-	static double l22[]={
+	static IssmPDouble l22[]={
 		0.166666666666667, 0.666666666666667, 0.166666666666667};
-	static double l32[]={
+	static IssmPDouble l32[]={
 		0.166666666666667, 0.166666666666667, 0.666666666666667};
-	/*}}}2*/
-	/*p= 3, npoint= 4  {{{2*/
-	static double wgt3[]={
+	/*}}}*/
+	/*p= 3, npoint= 4  {{{*/
+	static IssmPDouble wgt3[]={
 		-0.974278579257493, 0.902109795608790, 0.902109795608790, 
 		0.902109795608790};
-	static double l13[]={
+	static IssmPDouble l13[]={
 		0.333333333333333, 0.600000000000000, 0.200000000000000, 
 		0.200000000000000};
-	static double l23[]={
+	static IssmPDouble l23[]={
 		0.333333333333333, 0.200000000000000, 0.600000000000000, 
 		0.200000000000000};
-	static double l33[]={
+	static IssmPDouble l33[]={
 		0.333333333333333, 0.200000000000000, 0.200000000000000, 
 		0.600000000000000};
-	/*}}}2*/
-	/*p= 4, npoint= 6  {{{2*/
-	static double wgt4[]={
+	/*}}}*/
+	/*p= 4, npoint= 6  {{{*/
+	static IssmPDouble wgt4[]={
 		0.386908262797819, 0.386908262797819, 0.386908262797819, 
 		0.190442006391807, 0.190442006391807, 0.190442006391807};
-	static double l14[]={
+	static IssmPDouble l14[]={
 		0.108103018168070, 0.445948490915965, 0.445948490915965, 
 		0.816847572980459, 0.091576213509771, 0.091576213509771};
-	static double l24[]={
+	static IssmPDouble l24[]={
 		0.445948490915965, 0.108103018168070, 0.445948490915965, 
 		0.091576213509771, 0.816847572980459, 0.091576213509771};
-	static double l34[]={
+	static IssmPDouble l34[]={
 		0.445948490915965, 0.445948490915965, 0.108103018168070, 
 		0.091576213509771, 0.091576213509771, 0.816847572980459};
-	/*}}}2*/
-	/*p= 5, npoint= 7  {{{2*/
-	static double wgt5[]={
+	/*}}}*/
+	/*p= 5, npoint= 7  {{{*/
+	static IssmPDouble wgt5[]={
 		0.389711431702997, 0.229313399254729, 0.229313399254729, 
 		0.229313399254729, 0.218133059367230, 0.218133059367230, 
 		0.218133059367230};
-	static double l15[]={
+	static IssmPDouble l15[]={
 		0.333333333333333, 0.059715871789770, 0.470142064105115, 
 		0.470142064105115, 0.797426985353087, 0.101286507323456, 
 		0.101286507323456};
-	static double l25[]={
+	static IssmPDouble l25[]={
 		0.333333333333333, 0.470142064105115, 0.059715871789770, 
 		0.470142064105115, 0.101286507323456, 0.797426985353087, 
 		0.101286507323456};
-	static double l35[]={
+	static IssmPDouble l35[]={
 		0.333333333333333, 0.470142064105115, 0.470142064105115, 
 		0.059715871789770, 0.101286507323456, 0.101286507323456, 
 		0.797426985353087};
-	/*}}}2*/
-	/*p= 6, npoint=12  {{{2*/
-	static double wgt6[]={
+	/*}}}*/
+	/*p= 6, npoint=12  {{{*/
+	static IssmPDouble wgt6[]={
 		0.202279763184836, 0.202279763184836, 0.202279763184836, 
 		0.088065961139281, 0.088065961139281, 0.088065961139281, 
 		0.143502272432755, 0.143502272432755, 0.143502272432755, 
 		0.143502272432755, 0.143502272432755, 0.143502272432755};
-	static double l16[]={
+	static IssmPDouble l16[]={
 		0.501426509658179, 0.249286745170910, 0.249286745170910, 
 		0.873821971016996, 0.063089014491502, 0.063089014491502, 
 		0.053145049844817, 0.053145049844817, 0.310352451033784, 
 		0.636502499121399, 0.310352451033784, 0.636502499121399};
-	static double l26[]={
+	static IssmPDouble l26[]={
 		0.249286745170910, 0.501426509658179, 0.249286745170910, 
 		0.063089014491502, 0.873821971016996, 0.063089014491502, 
 		0.310352451033784, 0.636502499121399, 0.053145049844817, 
 		0.053145049844817, 0.636502499121399, 0.310352451033784};
-	static double l36[]={
+	static IssmPDouble l36[]={
 		0.249286745170910, 0.249286745170910, 0.501426509658179, 
 		0.063089014491502, 0.063089014491502, 0.873821971016996, 
 		0.636502499121399, 0.310352451033784, 0.636502499121399, 
 		0.310352451033784, 0.053145049844817, 0.053145049844817};
-	/*}}}2*/
-	/*p= 7, npoint=13  {{{2*/
-	static double wgt7[]={
+	/*}}}*/
+	/*p= 7, npoint=13  {{{*/
+	static IssmPDouble wgt7[]={
 		-0.259062916308362, 0.304174548458604, 0.304174548458604, 
 		0.304174548458604, 0.092400122517855, 0.092400122517855, 
@@ -197,5 +197,5 @@
 		0.133564951824643, 0.133564951824643, 0.133564951824643, 
 		0.133564951824643};
-	static double l17[]={
+	static IssmPDouble l17[]={
 		0.333333333333333, 0.479308067841920, 0.260345966079040, 
 		0.260345966079040, 0.869739794195568, 0.065130102902216, 
@@ -203,5 +203,5 @@
 		0.312865496004874, 0.638444188569810, 0.312865496004874, 
 		0.638444188569810};
-	static double l27[]={
+	static IssmPDouble l27[]={
 		0.333333333333333, 0.260345966079040, 0.479308067841920, 
 		0.260345966079040, 0.065130102902216, 0.869739794195568, 
@@ -209,5 +209,5 @@
 		0.048690315425316, 0.048690315425316, 0.638444188569810, 
 		0.312865496004874};
-	static double l37[]={
+	static IssmPDouble l37[]={
 		0.333333333333333, 0.260345966079040, 0.260345966079040, 
 		0.479308067841920, 0.065130102902216, 0.065130102902216, 
@@ -215,7 +215,7 @@
 		0.638444188569810, 0.312865496004874, 0.048690315425316, 
 		0.048690315425316};
-	/*}}}2*/
-	/*p= 8, npoint=16  {{{2*/
-	static double wgt8[]={
+	/*}}}*/
+	/*p= 8, npoint=16  {{{*/
+	static IssmPDouble wgt8[]={
 		0.249961964823104, 0.164703541925695, 0.164703541925695, 
 		0.164703541925695, 0.178777729989794, 0.178777729989794, 
@@ -224,5 +224,5 @@
 		0.047164287656184, 0.047164287656184, 0.047164287656184, 
 		0.047164287656184};
-	static double l18[]={
+	static IssmPDouble l18[]={
 		0.333333333333333, 0.081414823414554, 0.459292588292723, 
 		0.459292588292723, 0.658861384496480, 0.170569307751760, 
@@ -231,5 +231,5 @@
 		0.263112829634638, 0.728492392955404, 0.263112829634638, 
 		0.728492392955404};
-	static double l28[]={
+	static IssmPDouble l28[]={
 		0.333333333333333, 0.459292588292723, 0.081414823414554, 
 		0.459292588292723, 0.170569307751760, 0.658861384496480, 
@@ -238,5 +238,5 @@
 		0.008394777409958, 0.008394777409958, 0.728492392955404, 
 		0.263112829634638};
-	static double l38[]={
+	static IssmPDouble l38[]={
 		0.333333333333333, 0.459292588292723, 0.459292588292723, 
 		0.081414823414554, 0.170569307751760, 0.170569307751760, 
@@ -245,7 +245,7 @@
 		0.728492392955404, 0.263112829634638, 0.008394777409958, 
 		0.008394777409958};
-	/*}}}2*/
-	/*p= 9, npoint=19  {{{2*/
-	static double wgt9[]={
+	/*}}}*/
+	/*p= 9, npoint=19  {{{*/
+	static IssmPDouble wgt9[]={
 		0.168244134395468, 0.054273292833345, 0.054273292833345, 
 		0.054273292833345, 0.134801255248419, 0.134801255248419, 
@@ -255,5 +255,5 @@
 		0.074969289332873, 0.074969289332873, 0.074969289332873, 
 		0.074969289332873};
-	static double l19[]={
+	static IssmPDouble l19[]={
 		0.333333333333333, 0.020634961602525, 0.489682519198738, 
 		0.489682519198738, 0.125820817014127, 0.437089591492937, 
@@ -263,5 +263,5 @@
 		0.221962989160766, 0.741198598784498, 0.221962989160766, 
 		0.741198598784498};
-	static double l29[]={
+	static IssmPDouble l29[]={
 		0.333333333333333, 0.489682519198738, 0.020634961602525, 
 		0.489682519198738, 0.437089591492937, 0.125820817014127, 
@@ -271,5 +271,5 @@
 		0.036838412054736, 0.036838412054736, 0.741198598784498, 
 		0.221962989160766};
-	static double l39[]={
+	static IssmPDouble l39[]={
 		0.333333333333333, 0.489682519198738, 0.489682519198738, 
 		0.020634961602525, 0.437089591492937, 0.437089591492937, 
@@ -279,7 +279,7 @@
 		0.741198598784498, 0.221962989160766, 0.036838412054736, 
 		0.036838412054736};
-	/*}}}2*/
-	/*p=10, npoint=25  {{{2*/
-	static double wgt10[]={
+	/*}}}*/
+	/*p=10, npoint=25  {{{*/
+	static IssmPDouble wgt10[]={
 		0.157301373584232, 0.063611224790829, 0.063611224790829, 
 		0.063611224790829, 0.078498377595183, 0.078498377595183, 
@@ -291,5 +291,5 @@
 		0.016318805873179, 0.016318805873179, 0.016318805873179, 
 		0.016318805873179};
-	static double l110[]={
+	static IssmPDouble l110[]={
 		0.333333333333333, 0.028844733232685, 0.485577633383657, 
 		0.485577633383657, 0.781036849029926, 0.109481575485037, 
@@ -301,5 +301,5 @@
 		0.066803251012200, 0.923655933587500, 0.066803251012200, 
 		0.923655933587500};
-	static double l210[]={
+	static IssmPDouble l210[]={
 		0.333333333333333, 0.485577633383657, 0.028844733232685, 
 		0.485577633383657, 0.109481575485037, 0.781036849029926, 
@@ -311,5 +311,5 @@
 		0.009540815400299, 0.009540815400299, 0.923655933587500, 
 		0.066803251012200};
-	static double l310[]={
+	static IssmPDouble l310[]={
 		0.333333333333333, 0.485577633383657, 0.485577633383657, 
 		0.028844733232685, 0.109481575485037, 0.109481575485037, 
@@ -321,7 +321,7 @@
 		0.923655933587500, 0.066803251012200, 0.009540815400299, 
 		0.009540815400299};
-	/*}}}2*/
-	/*p=11, npoint=27  {{{2*/
-	static double wgt11[]={
+	/*}}}*/
+	/*p=11, npoint=27  {{{*/
+	static IssmPDouble wgt11[]={
 		0.001605622060698, 0.001605622060698, 0.001605622060698, 
 		0.133626914252765, 0.133626914252765, 0.133626914252765, 
@@ -333,5 +333,5 @@
 		0.035866718600836, 0.035866718600836, 0.035866718600836, 
 		0.035866718600836, 0.035866718600836, 0.035866718600836};
-	static double l111[]={
+	static IssmPDouble l111[]={
 		-0.069222096541517, 0.534611048270758, 0.534611048270758, 
 		0.202061394068290, 0.398969302965855, 0.398969302965855, 
@@ -343,5 +343,5 @@
 		0.021022016536166, 0.021022016536166, 0.171488980304042, 
 		0.807489003159792, 0.171488980304042, 0.807489003159792};
-	static double l211[]={
+	static IssmPDouble l211[]={
 		0.534611048270758,-0.069222096541517, 0.534611048270758, 
 		0.398969302965855, 0.202061394068290, 0.398969302965855, 
@@ -353,5 +353,5 @@
 		0.171488980304042, 0.807489003159792, 0.021022016536166, 
 		0.021022016536166, 0.807489003159792, 0.171488980304042};
-	static double l311[]={
+	static IssmPDouble l311[]={
 		0.534611048270758, 0.534611048270758,-0.069222096541517, 
 		0.398969302965855, 0.398969302965855, 0.202061394068290, 
@@ -363,7 +363,7 @@
 		0.807489003159792, 0.171488980304042, 0.807489003159792, 
 		0.171488980304042, 0.021022016536166, 0.021022016536166};
-	/*}}}2*/
-	/*p=12, npoint=33  {{{2*/
-	static double wgt12[]={
+	/*}}}*/
+	/*p=12, npoint=33  {{{*/
+	static IssmPDouble wgt12[]={
 		0.044567514407799, 0.044567514407799, 0.044567514407799, 
 		0.075677707051848, 0.075677707051848, 0.075677707051848, 
@@ -377,5 +377,5 @@
 		0.029992592075802, 0.029992592075802, 0.029992592075802, 
 		0.029992592075802, 0.029992592075802, 0.029992592075802};
-	static double l112[]={
+	static IssmPDouble l112[]={
 		0.023565220452390, 0.488217389773805, 0.488217389773805, 
 		0.120551215411079, 0.439724392294460, 0.439724392294460, 
@@ -389,5 +389,5 @@
 		0.025734050548330, 0.025734050548330, 0.116251915907597, 
 		0.858014033544073, 0.116251915907597, 0.858014033544073};
-	static double l212[]={
+	static IssmPDouble l212[]={
 		0.488217389773805, 0.023565220452390, 0.488217389773805, 
 		0.439724392294460, 0.120551215411079, 0.439724392294460, 
@@ -401,5 +401,5 @@
 		0.116251915907597, 0.858014033544073, 0.025734050548330, 
 		0.025734050548330, 0.858014033544073, 0.116251915907597};
-	static double l312[]={
+	static IssmPDouble l312[]={
 		0.488217389773805, 0.488217389773805, 0.023565220452390, 
 		0.439724392294460, 0.439724392294460, 0.120551215411079, 
@@ -413,7 +413,7 @@
 		0.858014033544073, 0.116251915907597, 0.858014033544073, 
 		0.116251915907597, 0.025734050548330, 0.025734050548330};
-	/*}}}2*/
-	/*  p=13, npoint=37  {{{2*/
-	static double wgt13[]={
+	/*}}}*/
+	/*  p=13, npoint=37  {{{*/
+	static IssmPDouble wgt13[]={
 		0.090968907790622, 0.019537784619314, 0.019537784619314, 
 		0.019537784619314, 0.054427130356344, 0.054427130356344, 
@@ -429,5 +429,5 @@
 		0.026884523429480, 0.026884523429480, 0.026884523429480, 
 		0.026884523429480};
-	static double l113[]={
+	static IssmPDouble l113[]={
 		0.333333333333333, 0.009903630120591, 0.495048184939705, 
 		0.495048184939705, 0.062566729780852, 0.468716635109574, 
@@ -443,5 +443,5 @@
 		0.126357385491669, 0.851409537834241, 0.126357385491669, 
 		0.851409537834241};
-	static double l213[]={
+	static IssmPDouble l213[]={
 		0.333333333333333, 0.495048184939705, 0.009903630120591, 
 		0.495048184939705, 0.468716635109574, 0.062566729780852, 
@@ -457,5 +457,5 @@
 		0.022233076674090, 0.022233076674090, 0.851409537834241, 
 		0.126357385491669};
-	static double l313[]={
+	static IssmPDouble l313[]={
 		0.333333333333333, 0.495048184939705, 0.495048184939705, 
 		0.009903630120591, 0.468716635109574, 0.468716635109574, 
@@ -471,7 +471,7 @@
 		0.851409537834241, 0.126357385491669, 0.022233076674090, 
 		0.022233076674090};
-	/*}}}2*/
-	/*p=14, npoint=42{{{2*/
-	static double wgt14[]={
+	/*}}}*/
+	/*p=14, npoint=42{{{*/
+	static IssmPDouble wgt14[]={
 		0.037903474783419, 0.037903474783419, 0.037903474783419, 
 		0.056791094234956, 0.056791094234956, 0.056791094234956, 
@@ -488,5 +488,5 @@
 		0.008677970905831, 0.008677970905831, 0.008677970905831, 
 		0.008677970905831, 0.008677970905831, 0.008677970905831};
-	static double l114[]={
+	static IssmPDouble l114[]={
 		0.022072179275643, 0.488963910362179, 0.488963910362179, 
 		0.164710561319092, 0.417644719340454, 0.417644719340454, 
@@ -503,5 +503,5 @@
 		0.001268330932872, 0.001268330932872, 0.118974497696957, 
 		0.879757171370171, 0.118974497696957, 0.879757171370171};
-	static double l214[]={
+	static IssmPDouble l214[]={
 		0.488963910362179, 0.022072179275643, 0.488963910362179, 
 		0.417644719340454, 0.164710561319092, 0.417644719340454, 
@@ -518,5 +518,5 @@
 		0.118974497696957, 0.879757171370171, 0.001268330932872, 
 		0.001268330932872, 0.879757171370171, 0.118974497696957};
-	static double l314[]={
+	static IssmPDouble l314[]={
 		0.488963910362179, 0.488963910362179, 0.022072179275643, 
 		0.417644719340454, 0.417644719340454, 0.164710561319092, 
@@ -533,7 +533,7 @@
 		0.879757171370171, 0.118974497696957, 0.879757171370171, 
 		0.118974497696957, 0.001268330932872, 0.001268330932872};
-	/*}}}2*/
-	/*p=15, npoint=48{{{2*/
-	static double wgt15[]={
+	/*}}}*/
+	/*p=15, npoint=48{{{*/
+	static IssmPDouble wgt15[]={
 		0.003320126005206, 0.003320126005206, 0.003320126005206, 
 		0.076641563419124, 0.076641563419124, 0.076641563419124, 
@@ -552,5 +552,5 @@
 		0.013291658531346, 0.013291658531346, 0.013291658531346, 
 		0.013291658531346, 0.013291658531346, 0.013291658531346};
-	static double l115[]={
+	static IssmPDouble l115[]={
 		-0.013945833716486, 0.506972916858243, 0.506972916858243, 
 		0.137187291433955, 0.431406354283023, 0.431406354283023, 
@@ -569,5 +569,5 @@
 		0.012459809331199, 0.012459809331199, 0.103575616576386, 
 		0.883964574092416, 0.103575616576386, 0.883964574092416};
-	static double l215[]={
+	static IssmPDouble l215[]={
 		0.506972916858243,-0.013945833716486, 0.506972916858243, 
 		0.431406354283023, 0.137187291433955, 0.431406354283023, 
@@ -586,5 +586,5 @@
 		0.103575616576386, 0.883964574092416, 0.012459809331199, 
 		0.012459809331199, 0.883964574092416, 0.103575616576386};
-	static double l315[]={
+	static IssmPDouble l315[]={
 		0.506972916858243, 0.506972916858243,-0.013945833716486, 
 		0.431406354283023, 0.431406354283023, 0.137187291433955, 
@@ -603,7 +603,7 @@
 		0.883964574092416, 0.103575616576386, 0.883964574092416, 
 		0.103575616576386, 0.012459809331199, 0.012459809331199};
-	/*}}}2*/
-	/*p=16, npoint=52  {{{2*/
-	static double wgt16[]={
+	/*}}}*/
+	/*p=16, npoint=52  {{{*/
+	static IssmPDouble wgt16[]={
 		0.081191089584902, 0.011095307165226, 0.011095307165226, 
 		0.011095307165226, 0.072244353151393, 0.072244353151393, 
@@ -624,5 +624,5 @@
 		0.011864642509229, 0.011864642509229, 0.011864642509229, 
 		0.011864642509229};
-	static double l116[]={
+	static IssmPDouble l116[]={
 		0.333333333333333, 0.005238916103123, 0.497380541948438, 
 		0.497380541948438, 0.173061122901295, 0.413469438549352, 
@@ -643,5 +643,5 @@
 		0.085283615682657, 0.900399064086661, 0.085283615682657, 
 		0.900399064086661};
-	static double l216[]={
+	static IssmPDouble l216[]={
 		0.333333333333333, 0.497380541948438, 0.005238916103123, 
 		0.497380541948438, 0.413469438549352, 0.173061122901295, 
@@ -662,5 +662,5 @@
 		0.014317320230681, 0.014317320230681, 0.900399064086661, 
 		0.085283615682657};
-	static double l316[]={
+	static IssmPDouble l316[]={
 		0.333333333333333, 0.497380541948438, 0.497380541948438, 
 		0.005238916103123, 0.413469438549352, 0.413469438549352, 
@@ -681,7 +681,7 @@
 		0.900399064086661, 0.085283615682657, 0.014317320230681, 
 		0.014317320230681};
-	/*}}}2*/
-	/*p=17, npoint=61{{{2*/
-	static double wgt17[]={
+	/*}}}*/
+	/*p=17, npoint=61{{{*/
+	static IssmPDouble wgt17[]={
 		0.057914928034477, 0.008822054327014, 0.008822054327014, 
 		0.008822054327014, 0.025410682752829, 0.025410682752829, 
@@ -705,5 +705,5 @@
 		0.011545213295771, 0.011545213295771, 0.011545213295771, 
 		0.011545213295771};
-	static double l117[]={
+	static IssmPDouble l117[]={
 		0.333333333333333, 0.005658918886452, 0.497170540556774, 
 		0.497170540556774, 0.035647354750751, 0.482176322624625, 
@@ -727,5 +727,5 @@
 		0.080711313679564, 0.904625504095608, 0.080711313679564, 
 		0.904625504095608};
-	static double l217[]={
+	static IssmPDouble l217[]={
 		0.333333333333333, 0.497170540556774, 0.005658918886452, 
 		0.497170540556774, 0.482176322624625, 0.035647354750751, 
@@ -749,5 +749,5 @@
 		0.014663182224828, 0.014663182224828, 0.904625504095608, 
 		0.080711313679564};
-	static double l317[]={
+	static IssmPDouble l317[]={
 		0.333333333333333, 0.497170540556774, 0.497170540556774, 
 		0.005658918886452, 0.482176322624625, 0.482176322624625, 
@@ -771,8 +771,8 @@
 		0.904625504095608, 0.080711313679564, 0.014663182224828, 
 		0.014663182224828};
-	/*}}}2*/
-	/*  p=18, npoint=70  {{{2*/
-
-	static double wgt18[]={
+	/*}}}*/
+	/*  p=18, npoint=70  {{{*/
+
+	static IssmPDouble wgt18[]={
 		0.053364381350150, 0.015713921277179, 0.015713921277179, 
 		0.015713921277179, 0.032495554156279, 0.032495554156279, 
@@ -799,5 +799,5 @@
 		0.000079999375178, 0.000079999375178, 0.000079999375178, 
 		0.000079999375178};
-	static double l118[]={
+	static IssmPDouble l118[]={
 		0.333333333333333, 0.013310382738157, 0.493344808630921, 
 		0.493344808630921, 0.061578811516086, 0.469210594241957, 
@@ -824,5 +824,5 @@
 		0.020874755282586, 1.014347260005363, 0.020874755282586, 
 		1.014347260005363};
-	static double l218[]={
+	static IssmPDouble l218[]={
 		0.333333333333333, 0.493344808630921, 0.013310382738157, 
 		0.493344808630921, 0.469210594241957, 0.061578811516086, 
@@ -849,5 +849,5 @@
 		-0.035222015287949,-0.035222015287949, 1.014347260005363, 
 		0.020874755282586};
-	static double l318[]={
+	static IssmPDouble l318[]={
 		0.333333333333333, 0.493344808630921, 0.493344808630921, 
 		0.013310382738157, 0.469210594241957, 0.469210594241957, 
@@ -874,8 +874,8 @@
 		1.014347260005363, 0.020874755282586,-0.035222015287949, 
 		-0.035222015287949};
-	/*}}}2*/
-	/*p=19, npoint=73  {{{2*/
-
-	static double wgt19[]={
+	/*}}}*/
+	/*p=19, npoint=73  {{{*/
+
+	static IssmPDouble wgt19[]={
 		0.056995437856306, 0.017893352515055, 0.017893352515055, 
 		0.017893352515055, 0.038775849701151, 0.038775849701151, 
@@ -903,5 +903,5 @@
 		0.006581669842530, 0.006581669842530, 0.006581669842530, 
 		0.006581669842530};
-	static double l119[]={
+	static IssmPDouble l119[]={
 		0.333333333333333, 0.020780025853987, 0.489609987073006, 
 		0.489609987073006, 0.090926214604215, 0.454536892697893, 
@@ -929,5 +929,5 @@
 		0.065494628082938, 0.924344252620784, 0.065494628082938, 
 		0.924344252620784};
-	static double l219[]={
+	static IssmPDouble l219[]={
 		0.333333333333333, 0.489609987073006, 0.020780025853987, 
 		0.489609987073006, 0.454536892697893, 0.090926214604215, 
@@ -955,5 +955,5 @@
 		0.010161119296278, 0.010161119296278, 0.924344252620784, 
 		0.065494628082938};
-	static double l319[]={
+	static IssmPDouble l319[]={
 		0.333333333333333, 0.489609987073006, 0.489609987073006, 
 		0.020780025853987, 0.454536892697893, 0.454536892697893, 
@@ -981,7 +981,7 @@
 		0.924344252620784, 0.065494628082938, 0.010161119296278, 
 		0.010161119296278};
-	/*}}}2*/
-	/*p=20, npoint=79 {{{2*/
-	static double wgt20[]={
+	/*}}}*/
+	/*p=20, npoint=79 {{{*/
+	static IssmPDouble wgt20[]={
 		0.057256499746719, 0.001501721280705, 0.001501721280705, 
 		0.001501721280705, 0.020195803723819, 0.020195803723819, 
@@ -1011,5 +1011,5 @@
 		0.006190192638113, 0.006190192638113, 0.006190192638113, 
 		0.006190192638113};
-	static double l120[]={
+	static IssmPDouble l120[]={
 		0.333333333333333,-0.001900928704400, 0.500950464352200, 
 		0.500950464352200, 0.023574084130543, 0.488212957934729, 
@@ -1039,5 +1039,5 @@
 		0.059696109149007, 0.929756171556853, 0.059696109149007, 
 		0.929756171556853};
-	static double l220[]={
+	static IssmPDouble l220[]={
 		0.333333333333333, 0.500950464352200,-0.001900928704400, 
 		0.500950464352200, 0.488212957934729, 0.023574084130543, 
@@ -1067,5 +1067,5 @@
 		0.010547719294141, 0.010547719294141, 0.929756171556853, 
 		0.059696109149007};
-	static double l320[]={
+	static IssmPDouble l320[]={
 		0.333333333333333, 0.500950464352200, 0.500950464352200, 
 		-0.001900928704400, 0.488212957934729, 0.488212957934729, 
@@ -1095,22 +1095,22 @@
 		0.929756171556853, 0.059696109149007, 0.010547719294141, 
 		0.010547719294141};
-	/*}}}2*/
-
-	static double* wgtp[MAX_TRIA_SYM_ORD]={
+	/*}}}*/
+
+	static IssmPDouble* wgtp[MAX_TRIA_SYM_ORD]={
 		wgt1 ,wgt2 ,wgt3 ,wgt4 ,wgt5 ,
 		wgt6 ,wgt7 ,wgt8 ,wgt9 ,wgt10,
 		wgt11,wgt12,wgt13,wgt14,wgt15,
 		wgt16,wgt17,wgt18,wgt19,wgt20};
-	static double* l1p [MAX_TRIA_SYM_ORD]={
+	static IssmPDouble* l1p [MAX_TRIA_SYM_ORD]={
 		l11  ,l12  ,l13  ,l14  ,l15  ,
 		l16  ,l17  ,l18  ,l19  ,l110 ,
 		l111 ,l112 ,l113 ,l114 ,l115 ,
 		l116 ,l117 ,l118 ,l119 ,l120 };
-	static double* l2p [MAX_TRIA_SYM_ORD]={
+	static IssmPDouble* l2p [MAX_TRIA_SYM_ORD]={
 		l21  ,l22  ,l23  ,l24  ,l25  ,
 		l26  ,l27  ,l28  ,l29  ,l210 ,
 		l211 ,l212 ,l213 ,l214 ,l215 ,
 		l216 ,l217 ,l218 ,l219 ,l220 };
-	static double* l3p [MAX_TRIA_SYM_ORD]={
+	static IssmPDouble* l3p [MAX_TRIA_SYM_ORD]={
 		l31  ,l32  ,l33  ,l34  ,l35  ,
 		l36  ,l37  ,l38  ,l39  ,l310 ,
@@ -1118,26 +1118,26 @@
 		l316 ,l317 ,l318 ,l319 ,l320 };
 
-	static int np[MAX_TRIA_SYM_ORD]={sizeof(wgt1 )/sizeof(double),
-		sizeof(wgt2 )/sizeof(double),
-		sizeof(wgt3 )/sizeof(double),
-		sizeof(wgt4 )/sizeof(double),
-		sizeof(wgt5 )/sizeof(double),
-		sizeof(wgt6 )/sizeof(double),
-		sizeof(wgt7 )/sizeof(double),
-		sizeof(wgt8 )/sizeof(double),
-		sizeof(wgt9 )/sizeof(double),
-		sizeof(wgt10)/sizeof(double),
-		sizeof(wgt11)/sizeof(double),
-		sizeof(wgt12)/sizeof(double),
-		sizeof(wgt13)/sizeof(double),
-		sizeof(wgt14)/sizeof(double),
-		sizeof(wgt15)/sizeof(double),
-		sizeof(wgt16)/sizeof(double),
-		sizeof(wgt17)/sizeof(double),
-		sizeof(wgt18)/sizeof(double),
-		sizeof(wgt19)/sizeof(double),
-		sizeof(wgt20)/sizeof(double)};
-
-	//	_printf_(true,"GaussLegendreTria: iord=%d\n",iord);
+	static int np[MAX_TRIA_SYM_ORD]={sizeof(wgt1 )/sizeof(IssmPDouble),
+		sizeof(wgt2 )/sizeof(IssmPDouble),
+		sizeof(wgt3 )/sizeof(IssmPDouble),
+		sizeof(wgt4 )/sizeof(IssmPDouble),
+		sizeof(wgt5 )/sizeof(IssmPDouble),
+		sizeof(wgt6 )/sizeof(IssmPDouble),
+		sizeof(wgt7 )/sizeof(IssmPDouble),
+		sizeof(wgt8 )/sizeof(IssmPDouble),
+		sizeof(wgt9 )/sizeof(IssmPDouble),
+		sizeof(wgt10)/sizeof(IssmPDouble),
+		sizeof(wgt11)/sizeof(IssmPDouble),
+		sizeof(wgt12)/sizeof(IssmPDouble),
+		sizeof(wgt13)/sizeof(IssmPDouble),
+		sizeof(wgt14)/sizeof(IssmPDouble),
+		sizeof(wgt15)/sizeof(IssmPDouble),
+		sizeof(wgt16)/sizeof(IssmPDouble),
+		sizeof(wgt17)/sizeof(IssmPDouble),
+		sizeof(wgt18)/sizeof(IssmPDouble),
+		sizeof(wgt19)/sizeof(IssmPDouble),
+		sizeof(wgt20)/sizeof(IssmPDouble)};
+
+	//	_pprintLine_("GaussLegendreTria: iord=" << iord);
 
 	/*  check to see if Gauss points need to be calculated  */
@@ -1150,8 +1150,8 @@
 		*pngaus=np[iord-1];
 
-		*pl1  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pl2  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pl3  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pwgt = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl1  =xNew<IssmPDouble>(*pngaus);
+		*pl2  =xNew<IssmPDouble>(*pngaus);
+		*pl3  =xNew<IssmPDouble>(*pngaus);
+		*pwgt =xNew<IssmPDouble>(*pngaus);
 
 		for (i=0; i<*pngaus; i++) {
@@ -1168,8 +1168,8 @@
 		*pngaus=nigaus*nigaus;
 
-		*pl1  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pl2  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pl3  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pwgt = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl1  =xNew<IssmPDouble>(*pngaus);
+		*pl2  =xNew<IssmPDouble>(*pngaus);
+		*pl3  =xNew<IssmPDouble>(*pngaus);
+		*pwgt =xNew<IssmPDouble>(*pngaus);
 
 		/*  get the gauss points in each direction  */
@@ -1195,9 +1195,9 @@
 			}
 		}
-		xfree((void **)&xwgt );
-		xfree((void **)&xgaus);
+		xDelete<IssmPDouble>(xwgt );
+		xDelete<IssmPDouble>(xgaus);
 	}
 
-	//	_printf_(true,"GaussLegendreTria - ngaus=%d\n",*pngaus);
+	//	_pprintLine_("GaussLegendreTria - ngaus=" << *pngaus);
 	//	for (i=0; i<*pngaus; i++)
 	//		_printf_(true,"i=%d: l1gaus=%f,l2gaus=%f,l3gaus=%f,wgt=%f\n",
@@ -1205,7 +1205,7 @@
 
 	return;
-}/*}}}1*/
-/*FUNCTION GaussLegendreTetra{{{1*/
-void GaussLegendreTetra( int* pngaus, double** pl1, double** pl2, double** pl3, double** pl4, double** pwgt, int iord ) {
+}/*}}}*/
+/*FUNCTION GaussLegendreTetra{{{*/
+void GaussLegendreTetra( int* pngaus, IssmPDouble** pl1, IssmPDouble** pl2, IssmPDouble** pl3, IssmPDouble** pl4, IssmPDouble** pwgt, int iord ) {
 	/* Gauss quadrature points for the tetrahedron.
 
@@ -1220,86 +1220,86 @@
 	/*Intermediaries*/
 	int i,j,k,ipt,nigaus;
-	double xi,eta,zeta;
-	double *xgaus=NULL,*xwgt=NULL,*egaus,*ewgt,*zgaus,*zwgt;
+	IssmPDouble xi,eta,zeta;
+	IssmPDouble *xgaus=NULL,*xwgt=NULL,*egaus,*ewgt,*zgaus,*zwgt;
 
 	/*Hardcoded Gauss points definition*/
-	/*p= 1, npoint= 1  {{{2*/
-	static double wgt1[]={
+	/*p= 1, npoint= 1  {{{*/
+	static IssmPDouble wgt1[]={
 		1.000000000000000};
-	static double l11[]={
+	static IssmPDouble l11[]={
 		0.250000000000000};
-	static double l21[]={
+	static IssmPDouble l21[]={
 		0.250000000000000};
-	static double l31[]={
+	static IssmPDouble l31[]={
 		0.250000000000000};
-	static double l41[]={
+	static IssmPDouble l41[]={
 		0.250000000000000};
-	/*}}}2*/
-	/*p= 2, npoint= 4  {{{2*/
-
-	static double wgt2[]={
+	/*}}}*/
+	/*p= 2, npoint= 4  {{{*/
+
+	static IssmPDouble wgt2[]={
 		0.250000000000000, 0.250000000000000, 0.250000000000000,
 		0.250000000000000};
-	static double l12[]={
+	static IssmPDouble l12[]={
 		0.585410196624969, 0.138196601125011, 0.138196601125011,
 		0.138196601125011};
-	static double l22[]={
+	static IssmPDouble l22[]={
 		0.138196601125011, 0.585410196624969, 0.138196601125011,
 		0.138196601125011};
-	static double l32[]={
+	static IssmPDouble l32[]={
 		0.138196601125011, 0.138196601125011, 0.585410196624969,
 		0.138196601125011};
-	static double l42[]={
+	static IssmPDouble l42[]={
 		0.138196601125011, 0.138196601125011, 0.138196601125011,
 		0.585410196624969};
-	/*}}}2*/
-	/*p= 3, npoint= 5  {{{2*/
-	static double wgt3[]={
+	/*}}}*/
+	/*p= 3, npoint= 5  {{{*/
+	static IssmPDouble wgt3[]={
 		-0.800000000000000, 0.450000000000000, 0.450000000000000, 
 		0.450000000000000, 0.450000000000000};
-	static double l13[]={
+	static IssmPDouble l13[]={
 		0.250000000000000, 0.500000000000000, 0.166666666666667, 
 		0.166666666666667, 0.166666666666667};
-	static double l23[]={
+	static IssmPDouble l23[]={
 		0.250000000000000, 0.166666666666667, 0.500000000000000, 
 		0.166666666666667, 0.166666666666667};
-	static double l33[]={
+	static IssmPDouble l33[]={
 		0.250000000000000, 0.166666666666667, 0.166666666666667, 
 		0.500000000000000, 0.166666666666667};
-	static double l43[]={
+	static IssmPDouble l43[]={
 		0.250000000000000, 0.166666666666667, 0.166666666666667, 
 		0.166666666666667, 0.500000000000000};
-	/*}}}2*/
-	/*p= 4, npoint=11  {{{2*/
-
-	static double wgt4[]={
+	/*}}}*/
+	/*p= 4, npoint=11  {{{*/
+
+	static IssmPDouble wgt4[]={
 		-0.013155555555556, 0.007622222222222, 0.007622222222222, 
 		0.007622222222222, 0.007622222222222, 0.024888888888889,
 		0.024888888888889, 0.024888888888889, 0.024888888888889, 
 		0.024888888888889, 0.024888888888889};
-	static double l14[]={
+	static IssmPDouble l14[]={
 		0.250000000000000, 0.785714285714286, 0.071428571428571, 
 		0.071428571428571, 0.071428571428571, 0.399403576166799,
 		0.399403576166799, 0.399403576166799, 0.100596423833201, 
 		0.100596423833201, 0.100596423833201};
-	static double l24[]={
+	static IssmPDouble l24[]={
 		0.250000000000000, 0.071428571428571, 0.785714285714286, 
 		0.071428571428571, 0.071428571428571, 0.399403576166799,
 		0.100596423833201, 0.100596423833201, 0.399403576166799, 
 		0.399403576166799, 0.100596423833201};
-	static double l34[]={
+	static IssmPDouble l34[]={
 		0.250000000000000, 0.071428571428571, 0.071428571428571, 
 		0.785714285714286, 0.071428571428571, 0.100596423833201, 
 		0.399403576166799, 0.100596423833201, 0.399403576166799,
 		0.100596423833201, 0.399403576166799};
-	static double l44[]={
+	static IssmPDouble l44[]={
 		0.250000000000000, 0.071428571428571, 0.071428571428571, 
 		0.071428571428571, 0.785714285714286, 0.100596423833201, 
 		0.100596423833201, 0.399403576166799, 0.100596423833201,
 		0.399403576166799, 0.399403576166799};
-	/*}}}2*/
-	/*p= 5, npoint=15  {{{2*/
-
-	static double wgt5[]={
+	/*}}}*/
+	/*p= 5, npoint=15  {{{*/
+
+	static IssmPDouble wgt5[]={
 		0.030283678097089, 0.006026785714286, 0.006026785714286, 
 		0.006026785714286, 0.006026785714286, 0.011645249086029, 
@@ -1307,5 +1307,5 @@
 		0.010949141561386, 0.010949141561386, 0.010949141561386,
 		0.010949141561386, 0.010949141561386, 0.010949141561386};
-	static double l15[]={
+	static IssmPDouble l15[]={
 		0.250000000000000, 0.000000000000000, 0.333333333333333, 
 		0.333333333333333, 0.333333333333333, 0.727272727272727, 
@@ -1313,5 +1313,5 @@
 		0.066550153573664, 0.066550153573664, 0.066550153573664, 
 		0.433449846426336, 0.433449846426336, 0.433449846426336};
-	static double l25[]={
+	static IssmPDouble l25[]={
 		0.250000000000000, 0.333333333333333, 0.000000000000000, 
 		0.333333333333333, 0.333333333333333, 0.090909090909091, 
@@ -1319,5 +1319,5 @@
 		0.066550153573664, 0.433449846426336, 0.433449846426336, 
 		0.066550153573664, 0.066550153573664, 0.433449846426336};
-	static double l35[]={
+	static IssmPDouble l35[]={
 		0.250000000000000, 0.333333333333333, 0.333333333333333, 
 		0.000000000000000, 0.333333333333333, 0.090909090909091, 
@@ -1325,5 +1325,5 @@
 		0.433449846426336, 0.066550153573664, 0.433449846426336, 
 		0.066550153573664, 0.433449846426336, 0.066550153573664};
-	static double l45[]={
+	static IssmPDouble l45[]={
 		0.250000000000000, 0.333333333333333, 0.333333333333333, 
 		0.333333333333333, 0.000000000000000, 0.090909090909091, 
@@ -1331,8 +1331,8 @@
 		0.433449846426336, 0.433449846426336, 0.066550153573664, 
 		0.433449846426336, 0.066550153573664, 0.066550153573664};
-	/*}}}2*/
-	/*p= 6, npoint=24  {{{2*/
-
-	static double wgt6[]={
+	/*}}}*/
+	/*p= 6, npoint=24  {{{*/
+
+	static IssmPDouble wgt6[]={
 		0.006653791709695, 0.006653791709695, 0.006653791709695, 
 		0.006653791709695, 0.001679535175887, 0.001679535175887, 
@@ -1343,5 +1343,5 @@
 		0.008035714285714, 0.008035714285714, 0.008035714285714, 
 		0.008035714285714, 0.008035714285714, 0.008035714285714};
-	static double l16[]={
+	static IssmPDouble l16[]={
 		0.356191386222545, 0.214602871259152, 0.214602871259152, 
 		0.214602871259152, 0.877978124396166, 0.040673958534611, 
@@ -1353,5 +1353,5 @@
 		0.269672331458316, 0.603005664791649, 0.269672331458316, 
 		0.603005664791649, 0.269672331458316, 0.603005664791649};
-	static double l26[]={
+	static IssmPDouble l26[]={
 		0.214602871259152, 0.356191386222545, 0.214602871259152, 
 		0.214602871259152, 0.040673958534611, 0.877978124396166, 
@@ -1363,5 +1363,5 @@
 		0.063661001875018, 0.063661001875018, 0.063661001875018, 
 		0.063661001875018, 0.603005664791649, 0.269672331458316};
-	static double l36[]={
+	static IssmPDouble l36[]={
 		0.214602871259152, 0.214602871259152, 0.356191386222545, 
 		0.214602871259152, 0.040673958534611, 0.040673958534611, 
@@ -1373,5 +1373,5 @@
 		0.063661001875018, 0.063661001875018, 0.603005664791649, 
 		0.269672331458316, 0.063661001875018, 0.063661001875018};
-	static double l46[]={
+	static IssmPDouble l46[]={
 		0.214602871259152, 0.214602871259152, 0.214602871259152, 
 		0.356191386222545, 0.040673958534611, 0.040673958534611, 
@@ -1383,20 +1383,20 @@
 		0.603005664791649, 0.269672331458316, 0.063661001875018, 
 		0.063661001875018, 0.063661001875018, 0.063661001875018};
-	/*}}}2*/
-
-	static double* wgtp[MAX_TETRA_SYM_ORD]={wgt1,wgt2,wgt3,wgt4,wgt5,wgt6};
-	static double* l1p [MAX_TETRA_SYM_ORD]={l11 ,l12 ,l13 ,l14 ,l15 ,l16 };
-	static double* l2p [MAX_TETRA_SYM_ORD]={l21 ,l22 ,l32 ,l24 ,l25 ,l26 };
-	static double* l3p [MAX_TETRA_SYM_ORD]={l31 ,l32 ,l33 ,l34 ,l35 ,l36 };
-	static double* l4p [MAX_TETRA_SYM_ORD]={l41 ,l42 ,l43 ,l44 ,l45 ,l46 };
-
-	static int np[MAX_TETRA_SYM_ORD]={sizeof(wgt1 )/sizeof(double),
-		sizeof(wgt2 )/sizeof(double),
-		sizeof(wgt3 )/sizeof(double),
-		sizeof(wgt4 )/sizeof(double),
-		sizeof(wgt5 )/sizeof(double),
-		sizeof(wgt6 )/sizeof(double)};
-
-	//	_printf_(true,"GaussLegendreTetra: iord=%d\n",iord);
+	/*}}}*/
+
+	static IssmPDouble* wgtp[MAX_TETRA_SYM_ORD]={wgt1,wgt2,wgt3,wgt4,wgt5,wgt6};
+	static IssmPDouble* l1p [MAX_TETRA_SYM_ORD]={l11 ,l12 ,l13 ,l14 ,l15 ,l16 };
+	static IssmPDouble* l2p [MAX_TETRA_SYM_ORD]={l21 ,l22 ,l32 ,l24 ,l25 ,l26 };
+	static IssmPDouble* l3p [MAX_TETRA_SYM_ORD]={l31 ,l32 ,l33 ,l34 ,l35 ,l36 };
+	static IssmPDouble* l4p [MAX_TETRA_SYM_ORD]={l41 ,l42 ,l43 ,l44 ,l45 ,l46 };
+
+	static int np[MAX_TETRA_SYM_ORD]={sizeof(wgt1 )/sizeof(IssmPDouble),
+		sizeof(wgt2 )/sizeof(IssmPDouble),
+		sizeof(wgt3 )/sizeof(IssmPDouble),
+		sizeof(wgt4 )/sizeof(IssmPDouble),
+		sizeof(wgt5 )/sizeof(IssmPDouble),
+		sizeof(wgt6 )/sizeof(IssmPDouble)};
+
+	//	_pprintLine_("GaussLegendreTetra: iord=" << iord);
 
 	/*  check to see if Gauss points need to be calculated  */
@@ -1410,9 +1410,9 @@
 		*pngaus=np[iord-1];
 
-		*pl1  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pl2  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pl3  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pl4  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pwgt = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl1  =xNew<IssmPDouble>(*pngaus);
+		*pl2  =xNew<IssmPDouble>(*pngaus);
+		*pl3  =xNew<IssmPDouble>(*pngaus);
+		*pl4  =xNew<IssmPDouble>(*pngaus);
+		*pwgt =xNew<IssmPDouble>(*pngaus);
 
 		for (i=0; i<*pngaus; i++) {
@@ -1430,9 +1430,9 @@
 		*pngaus=nigaus*nigaus*nigaus;
 
-		*pl1  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pl2  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pl3  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pl4  = (double *) xmalloc(*pngaus*sizeof(double));
-		*pwgt = (double *) xmalloc(*pngaus*sizeof(double));
+		*pl1  =xNew<IssmPDouble>(*pngaus);
+		*pl2  =xNew<IssmPDouble>(*pngaus);
+		*pl3  =xNew<IssmPDouble>(*pngaus);
+		*pl4  =xNew<IssmPDouble>(*pngaus);
+		*pwgt =xNew<IssmPDouble>(*pngaus);
 
 		/*  get the gauss points in each direction  */
@@ -1467,10 +1467,10 @@
 			}
 		}
-		xfree((void **)&xwgt );
-		xfree((void **)&xgaus);
+		xDelete<IssmPDouble>(xwgt );
+		xDelete<IssmPDouble>(xgaus);
 	}
-}/*}}}1*/
-/*FUNCTION GaussLobatto{{{1*/
-void GaussLobatto( double** pxgaus, double** pxwgt, int ngaus ) {
+}/*}}}*/
+/*FUNCTION GaussLobatto{{{*/
+void GaussLobatto( IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus ) {
 	/*Gauss-Lobatto quadrature points.
 
@@ -1488,40 +1488,40 @@
 
 	int i;
-	double *alpha,*beta;
-	double left=-1.,right= 1.;
-	double p0l=0.,p0r=0.,p1l=1.,p1r=1.,pm1l,pm1r,det;
+	IssmPDouble *alpha,*beta;
+	IssmPDouble left=-1.,right= 1.;
+	IssmPDouble p0l=0.,p0r=0.,p1l=1.,p1r=1.,pm1l,pm1r,det;
 
 	/*p= 1, npoint= 1 (Gauss-Legendre)*/
-	static double wgt1[]={2.000000000000000};
-	static double xi1[]={0.000000000000000};
+	static IssmPDouble wgt1[]={2.000000000000000};
+	static IssmPDouble xi1[]={0.000000000000000};
 
 	/*p= 1, npoint= 2*/
-	static double wgt2[]={1.000000000000000, 1.000000000000000};
-	static double xi2[]={-1.000000000000000, 1.000000000000000};
+	static IssmPDouble wgt2[]={1.000000000000000, 1.000000000000000};
+	static IssmPDouble xi2[]={-1.000000000000000, 1.000000000000000};
 
 	/*p= 3, npoint= 3*/
-	static double wgt3[]={0.333333333333333, 1.333333333333333, 0.333333333333333};
-	static double xi3[]={-1.000000000000000, 0.000000000000000, 1.000000000000000};
+	static IssmPDouble wgt3[]={0.333333333333333, 1.333333333333333, 0.333333333333333};
+	static IssmPDouble xi3[]={-1.000000000000000, 0.000000000000000, 1.000000000000000};
 
 	/*p= 5, npoint= 4*/
-	static double wgt4[]={0.166666666666667, 0.833333333333333, 0.833333333333333, 0.166666666666667};
-	static double xi4[]={-1.000000000000000,-0.447213595499958, 0.447213595499958, 1.000000000000000};
+	static IssmPDouble wgt4[]={0.166666666666667, 0.833333333333333, 0.833333333333333, 0.166666666666667};
+	static IssmPDouble xi4[]={-1.000000000000000,-0.447213595499958, 0.447213595499958, 1.000000000000000};
 
 	/*p= 7, npoint= 5*/
-	static double wgt5[]={0.100000000000000, 0.544444444444444, 0.711111111111111, 0.544444444444444, 0.100000000000000};
-	static double xi5[]={-1.000000000000000,-0.654653670707977, 0.000000000000000, 0.654653670707977, 1.000000000000000};
-
-	static double* wgtp[MAX_LINE_GLOB_PTS]={wgt1 ,wgt2 ,wgt3 ,wgt4 ,wgt5 };
-	static double* xip [MAX_LINE_GLOB_PTS]={xi1  ,xi2  ,xi3  ,xi4  ,xi5  };
-
-	static int np[MAX_LINE_GLOB_PTS]={sizeof(wgt1 )/sizeof(double),
-		sizeof(wgt2 )/sizeof(double),
-		sizeof(wgt3 )/sizeof(double),
-		sizeof(wgt4 )/sizeof(double),
-		sizeof(wgt5 )/sizeof(double)};
-
-	//	_printf_(true,"Gauss-Lobatto recurrence coefficients ngaus=%d\n",ngaus);
-	*pxgaus = (double *) xmalloc(ngaus*sizeof(double));
-	*pxwgt  = (double *) xmalloc(ngaus*sizeof(double));
+	static IssmPDouble wgt5[]={0.100000000000000, 0.544444444444444, 0.711111111111111, 0.544444444444444, 0.100000000000000};
+	static IssmPDouble xi5[]={-1.000000000000000,-0.654653670707977, 0.000000000000000, 0.654653670707977, 1.000000000000000};
+
+	static IssmPDouble* wgtp[MAX_LINE_GLOB_PTS]={wgt1 ,wgt2 ,wgt3 ,wgt4 ,wgt5 };
+	static IssmPDouble* xip [MAX_LINE_GLOB_PTS]={xi1  ,xi2  ,xi3  ,xi4  ,xi5  };
+
+	static int np[MAX_LINE_GLOB_PTS]={sizeof(wgt1 )/sizeof(IssmPDouble),
+		sizeof(wgt2 )/sizeof(IssmPDouble),
+		sizeof(wgt3 )/sizeof(IssmPDouble),
+		sizeof(wgt4 )/sizeof(IssmPDouble),
+		sizeof(wgt5 )/sizeof(IssmPDouble)};
+
+	//	_pprintLine_("Gauss-Lobatto recurrence coefficients ngaus=" << ngaus);
+	*pxgaus =xNew<IssmPDouble>(ngaus);
+	*pxwgt  =xNew<IssmPDouble>(ngaus);
 
 	/*  check to see if Gauss points need to be calculated  */
@@ -1539,6 +1539,6 @@
 
 		/*  calculate the Gauss points using recurrence relations  */
-		alpha=(double *) xmalloc(ngaus*sizeof(double));
-		beta =(double *) xmalloc(ngaus*sizeof(double));
+		alpha=xNew<IssmPDouble>(ngaus);
+		beta =xNew<IssmPDouble>(ngaus);
 
 		/*  calculate the Legendre recurrence coefficients  */
@@ -1575,11 +1575,11 @@
 		/*  calculate the Gauss points  */
 		GaussRecur(*pxgaus, *pxwgt, ngaus, alpha, beta );
-		xfree((void **)&beta );
-		xfree((void **)&alpha);
+		xDelete<IssmPDouble>(beta );
+		xDelete<IssmPDouble>(alpha);
 	}
 
-}/*}}}1*/
-/*FUNCTION GaussRecur{{{1*/
-void GaussRecur( double* zero, double* weight, int n, double* alpha, double* beta ) {
+}/*}}}*/
+/*FUNCTION GaussRecur{{{*/
+void GaussRecur( IssmPDouble* zero, IssmPDouble* weight, int n, IssmPDouble* alpha, IssmPDouble* beta ) {
 	/*Gauss quadrature points from recursion coefficients.
 	 *
@@ -1589,6 +1589,6 @@
 	/*Intermediaries*/
 	int i,j,k,l,m,ii,mml,iter;
-	double p,g,r,s,c,f,b;
-	double* work;
+	IssmPDouble p,g,r,s,c,f,b;
+	IssmPDouble* work;
 
 	if (n==1){
@@ -1598,5 +1598,5 @@
 	}
 
-	work=(double*)xmalloc(n*sizeof(double));
+	work=xNew<IssmPDouble>(n);
 
 	zero[0]  =alpha[0];
@@ -1669,6 +1669,6 @@
 		} while (iter < MAX_GAUS_ITER);
 		if (iter >= MAX_GAUS_ITER) {
-			xfree((void **)&work);
-			_error_("%s%i"," Max iterations exceeded for l=",MAX_GAUS_ITER);
+			xDelete<IssmPDouble>(work);
+			_error2_("Max iterations exceeded for l=" << MAX_GAUS_ITER);
 		}
 	}
@@ -1698,11 +1698,11 @@
 
 	/*Cleanup*/
-	xfree((void **)&work);
-
-}/*}}}1*/
+	xDelete<IssmPDouble>(work);
+
+}/*}}}*/
 
 /*Element Gauss points TO BE REMOVED*/
-/*FUNCTION gaussQuad{{{1*/
-void gaussQuad( double** pxgaus, double** pxwgt, double** pegaus, double** pewgt, int nigaus, int njgaus ) { 
+/*FUNCTION gaussQuad{{{*/
+void gaussQuad( IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, int nigaus, int njgaus ) {
 	/*Gauss quadrature points for the quadrilaterial.*/
 
@@ -1710,7 +1710,7 @@
 	GaussLegendreLinear(pxgaus, pxwgt, nigaus);
 	GaussLegendreLinear(pegaus, pewgt, njgaus);
-}/*}}}1*/
-/*FUNCTION gaussHexa{{{1*/
-void gaussHexa( double** pxgaus, double** pxwgt, double** pegaus, double** pewgt, double** pzgaus, double** pzwgt, int nigaus, int njgaus, int nkgaus ) {
+}/*}}}*/
+/*FUNCTION gaussHexa{{{*/
+void gaussHexa( IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, IssmPDouble** pzgaus, IssmPDouble ** pzwgt, int nigaus, int njgaus, int nkgaus ) {
 	/*Gauss quadrature points for the hexahedron.*/
 
@@ -1719,3 +1719,3 @@
 	GaussLegendreLinear(pegaus, pewgt, njgaus);
 	GaussLegendreLinear(pzgaus, pzwgt, nkgaus);
-}/*}}}1*/
+}/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/GaussPoints.h	(revision 12878)
@@ -3,20 +3,21 @@
  */ 
 
+#include "../../include/types.h"
 #ifndef _GAUSSPOINTS_H
 #define _GAUSSPOINTS_H
 
 #define MAX_LINE_GAUS_PTS    4
-void GaussLegendreLinear( double** pxgaus, double** pxwgt, int ngaus ); 
+void GaussLegendreLinear(IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus);
 #define MAX_TRIA_SYM_ORD    20
-void GaussLegendreTria( int* pngaus, double** pl1, double** pl2, double** pl3, double** pwgt, int iord );
+void GaussLegendreTria(int* pngaus, IssmPDouble** pl1, IssmPDouble** pl2, IssmPDouble** pl3, IssmPDouble** pwgt, int iord);
 #define MAX_TETRA_SYM_ORD    6
-void GaussLegendreTetra( int* pngaus, double** pl1, double** pl2, double** pl3, double** pl4, double** pwgt, int iord );
+void GaussLegendreTetra(int* pngaus, IssmPDouble** pl1, IssmPDouble** pl2, IssmPDouble** pl3, IssmPDouble** pl4, IssmPDouble** pwgt, int iord);
 #define MAX_LINE_GLOB_PTS    5
-void GaussLobatto( double** pxgaus, double** pxwgt, int ngaus ); 
+void GaussLobatto(IssmPDouble** pxgaus, IssmPDouble** pxwgt, int ngaus);
 #define MAX_GAUS_ITER   30
-void GaussRecur( double* zero, double* weight, int n, double* alpha, double* beta );
+void GaussRecur(IssmPDouble* zero, IssmPDouble* weight, int n, IssmPDouble* alpha, IssmPDouble* beta);
 
-void gaussQuad( double** pxgaus, double** pxwgt, double** pegaus, double** pewgt, int nigaus, int njgaus );
-void gaussHexa( double** pxgaus, double** pxwgt, double** pegaus, double** pewgt, double** pzgaus, double** pzwgt, int nigaus, int njgaus, int nkgaus );
+void gaussQuad(IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, int nigaus, int njgaus);
+void gaussHexa(IssmPDouble** pxgaus, IssmPDouble** pxwgt, IssmPDouble** pegaus, IssmPDouble** pewgt, IssmPDouble** pzgaus, IssmPDouble ** pzwgt, int nigaus, int njgaus, int nkgaus);
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/IsInputConverged.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/IsInputConverged.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/IsInputConverged.cpp	(revision 12878)
@@ -12,19 +12,19 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
-void IsInputConverged(double* peps, Input** new_inputs,Input** old_inputs,int num_inputs,int criterion_enum){
+void IsInputConverged(IssmDouble* peps, Input** new_inputs,Input** old_inputs,int num_inputs,int criterion_enum){
 
 	int i,j;
 
 	/*output: */
-	double eps;
+	IssmDouble eps;
 	
 	/*intermediary: */
-	double *newvalues     = NULL;
-	double *oldvalues     = NULL;
+	IssmDouble *newvalues     = NULL;
+	IssmDouble *oldvalues     = NULL;
 	int     num_values;
-	double  ndu        = 0;
-	double  nu         = 0;
+	IssmDouble  ndu        = 0;
+	IssmDouble  nu         = 0;
 
 	if(criterion_enum==RelativeEnum){
@@ -50,8 +50,8 @@
 
 		/*now, compute eps: */
-		if(nu)eps=ndu/nu;
+		if(reCast<bool>(nu))eps=ndu/nu;
 		else eps=0;
 	}
-	else _error_("%s%s%s"," convergence criterion ",EnumToStringx(criterion_enum)," not supported yet!");
+	else _error2_("convergence criterion " << EnumToStringx(criterion_enum) << " not supported yet!");
 
 	/*Assign output pointers:*/
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/OptimalSearch.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/OptimalSearch.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/OptimalSearch.cpp	(revision 12878)
@@ -10,5 +10,5 @@
 
 #include "./numerics.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../io/io.h"
 #include "../../include/include.h"
@@ -16,15 +16,15 @@
 #include <float.h>
 
-void OptimalSearch(double* psearch_scalar,double* pJ,OptPars* optpars,double (*f)(double,OptArgs*), OptArgs* optargs){
+void OptimalSearch(IssmDouble* psearch_scalar,IssmDouble* pJ,OptPars* optpars,IssmDouble (*f)(IssmDouble,OptArgs*), OptArgs* optargs){
 
 	/* This routine is optimizing a given function*/
 
 	/*function values: */
-	double fx1,fx2,fxbest;
-	double x1,x2,xmin,xbest;
+	IssmDouble fx1,fx2,fxbest;
+	IssmDouble x1,x2,xmin,xbest;
 
 	/*tolerances: */
-	double seps;
-	double tolerance=1.e-4;
+	IssmDouble seps;
+	IssmDouble tolerance=1.e-4;
 	int    maxiter;
 
@@ -41,7 +41,10 @@
 	//get the value of the function at the first boundary
 	fx1= (*f)(x1,optargs);
-	if (isnan(fx1)) _error_("Function evaluation returned NaN");
-	_printf_(VerboseControl(),"\n        Iteration         x           f(x)       Tolerance\n\n");
-	_printf_(VerboseControl(),"        %s    %12.6g  %12.6g  %s","   N/A",x1,fx1,"         N/A\n");
+	if (xIsNan<IssmDouble>(fx1)) _error2_("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");
 
 	//update tolerances
@@ -54,14 +57,15 @@
 		iter++;
 		fx2 = (*f)(x2,optargs);
-		if (isnan(fx2)) _error_("Function evaluation returned NaN");
-		_printf_(VerboseControl(),"         %5i    %12.6g  %12.6g  %12.6g\n",iter,x2,fx2,fabs(x2-x1)>fabs(fx2-fx1)?fabs(fx2-fx1):fabs(x2-x1));
+		if (xIsNan<IssmDouble>(fx2)) _error2_("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)));
 
 		//Stop the optimization?
 		if ((fabs(x2-x1)+seps)<tolerance || (fabs(fx2-fx1)+seps)<tolerance){
-			_printf_(VerboseControl(),"      %s%g\n","optimization terminated: the current x satisfies the termination criteria using 'tolx' of " ,tolerance);
+			if(VerboseControl()) _pprintLine_("      " << "optimization terminated: the current x satisfies the termination criteria using 'tolx' of "  << tolerance);
 			loop=false;
 		}
 		else if (iter>=maxiter){
-			_printf_(VerboseControl(),"      %s\n","exiting: Maximum number of iterations has been exceeded  - increase 'maxiter'\n");
+			if(VerboseControl()) _pprintLine_("      " << "exiting: Maximum number of iterations has been exceeded  - increase 'maxiter'");
 			loop=false;
 		}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/OptionsFromAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/OptionsFromAnalysis.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/OptionsFromAnalysis.cpp	(revision 12878)
@@ -9,5 +9,7 @@
 #endif
 
-#include "../../objects/objects.h"
+#include <cstring>
+
+#include "../../classes/objects/objects.h"
 #include "../../Container/Parameters.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
@@ -20,5 +22,5 @@
 	/*intermediary: */
 	int     dummy;
-	double* analyses=NULL;
+	IssmDouble* analyses=NULL;
 	char**  strings=NULL;
 	char*   string=NULL;
@@ -55,20 +57,18 @@
 	if (found==-1){
 		/*ok, we did not find anything, this is not good! error out: */
-		_error_("%s%s","could find neither a default analysis  nor analysis ",EnumToStringx(analysis_type));
+		_error2_("could find neither a default analysis  nor analysis " << EnumToStringx(analysis_type));
 	}
 
 	/*ok, grab the option string: */
-	outstring=(char*)xmalloc((strlen(strings[found])+1)*sizeof(char));
+	outstring=xNew<char>(strlen(strings[found])+1);
 	strcpy(outstring,strings[found]);
 
 	/*Free ressources*/
-	xfree((void**)&analyses);
+	xDelete<IssmDouble>(analyses);
 	for(i=0;i<numanalyses;i++){
 		string=strings[i];
-		xfree((void**)&string);
+		xDelete<char>(string);
 	}
-	xfree((void**)&strings);
-
-
+	xDelete<char*>(strings);
 	return outstring;
 }
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/PetscOptionsFromAnalysis.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/PetscOptionsFromAnalysis.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/PetscOptionsFromAnalysis.cpp	(revision 12878)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Parameters.h"
 #include "../../toolkits/toolkits.h"
@@ -39,4 +39,4 @@
 
 	/*Free ressources:*/
-	xfree((void**)&options);
+	xDelete<char>(options);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/Synchronize.sh
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/Synchronize.sh	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/Synchronize.sh	(revision 12878)
@@ -8,5 +8,5 @@
 #Get all lines of Verbosity.cpp
 cat Verbosity.h |  grep "bool Verbose" | awk '{print $2}' | sed -e "s/(/ /" | awk '{print $1}' | awk '{ printf "%s %s\n", NR, $0 }' >temp
-#Build header of Verbosity.cpp {{{1
+#Build header of Verbosity.cpp {{{
 cat <<END > Verbosity.cpp
 /*
@@ -127,5 +127,5 @@
 done
 
-#Add footer of Verbosity.cpp{{{1
+#Add footer of Verbosity.cpp{{{
 cat <<END >> Verbosity.cpp
 
@@ -135,5 +135,5 @@
 void SetVerbosityLevel(int level){
 
-	if(level<0) _error_("vebosity level should be a positive integer (user provided %i)",level);
+	if(level<0) _error2_("vebosity level should be a positive integer (user provided " << level << ")");
 
 	verbositylevel = level;
@@ -147,5 +147,5 @@
 END
 #}}}
-#Complete verbose.m {{{1
+#Complete verbose.m {{{
 VERBOSEPATH="$ISSM_DIR/src/m/classes/verbose.m"
 cat $VERBOSEPATH  | sed "/%BEGINFIELDS/,$ d"  > temp_begin
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/UnitConversion.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/UnitConversion.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/UnitConversion.cpp	(revision 12878)
@@ -3,5 +3,5 @@
  */ 
 
-/*headers {{{1*/
+/*headers {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -11,14 +11,14 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
 #include "../../shared/shared.h"
 
-double UnitConversionScaleFactor(int type_enum);
+IssmDouble UnitConversionScaleFactor(int type_enum);
 /*}}}*/
 
-void UnitConversion(double* values, int numvalues,int direction_enum, int type_enum){
+void UnitConversion(IssmDouble* values, int numvalues,int direction_enum, int type_enum){
 
-	double scale;
+	IssmDouble scale;
 	int i;
 
@@ -29,9 +29,9 @@
 	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. ");
+	else _error2_("wrong direction for unit conversion, either IuToExtEnum or ExtToIuEnum. ");
 
 }
 
-double UnitConversion(double value, int direction_enum, int type_enum){
+IssmDouble UnitConversion(IssmDouble value, int direction_enum, int type_enum){
 
 	UnitConversion(&value,1,direction_enum,type_enum);
@@ -41,9 +41,9 @@
 
 
-double UnitConversionScaleFactor(int type_enum){
+IssmDouble UnitConversionScaleFactor(int type_enum){
 
-	double yts=365.0*24.0*3600.0;
+	IssmDouble yts=365.0*24.0*3600.0;
 	
-	double scale;
+	IssmDouble scale;
 	switch(type_enum){
 		case TimesteppingStartTimeEnum:              scale=1.0/yts;break; //yr
@@ -66,6 +66,13 @@
 		case SurfaceforcingsPrecipitationEnum:       scale=yts;break; //m/yr
 		case SurfaceforcingsMassBalanceEnum:         scale=yts;break; //m/yr
+		case SurfaceforcingsSmbPosMaxEnum:				scale=yts;break; //m/yr
+		case SurfaceforcingsSmbPosMinEnum:				scale=yts;break; //m/yr
+		case SurfaceforcingsAPosEnum:						scale=yts;break; //m/yr
+		case SurfaceforcingsBPosEnum:						scale=yts;break; //m/yr
+		case SurfaceforcingsANegEnum:						scale=yts;break; //m/yr
+		case SurfaceforcingsBNegEnum:						scale=yts;break; //m/yr
 		case MisfitEnum:                             scale=pow(yts,2);break; //(m/yr)^2
-		case MassFluxEnum:                           scale=pow((double)10,-12)*yts;break; // (GigaTon/year)
+		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;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/Verbosity.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/Verbosity.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/Verbosity.cpp	(revision 12878)
@@ -34,5 +34,5 @@
 void SetVerbosityLevel(int level){
 
-	if(level<0) _error_("vebosity level should be a positive integer (user provided %i)",level);
+	if(level<0) _error2_("vebosity level should be a positive integer (user provided " << level << ")");
 
 	verbositylevel = level;
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp	(revision 12878)
@@ -5,12 +5,12 @@
 #include <math.h>
 
-void XZvectorsToCoordinateSystem(double* T,double* xzvectors){
+void XZvectorsToCoordinateSystem(IssmDouble* T,IssmDouble* xzvectors){
 
 	int		i,j;
-	double	x[3],y[3],z[3];
-	double	x_norm, y_norm, z_norm;
+	IssmDouble	x[3],y[3],z[3];
+	IssmDouble	x_norm, y_norm, z_norm;
 
 	for(i=0;i<6;i++){
-		if(isnan(xzvectors[i])){
+		if(xIsNan<IssmDouble>(xzvectors[i])){
 			/*At least one NaN found: default to Id*/
 			T[0*3+0] = 1.0;	T[0*3+1] = 0.0;	T[0*3+2] = 0.0;
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/cross.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/cross.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/cross.cpp	(revision 12878)
@@ -9,5 +9,7 @@
 #endif
 
-void cross(double* result,double* vector1,double* vector2){
+#include "../../include/include.h"
+
+void cross(IssmDouble* result,IssmDouble* vector1,IssmDouble* vector2){
 
 	/*result,vector1 and vector2 are all assumed to be of size 3: */
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/extrema.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/extrema.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/extrema.cpp	(revision 12878)
@@ -9,6 +9,7 @@
 #endif
 
+#include "../../include/include.h"
 
-double min(double a,double b){
+IssmDouble min(IssmDouble a,IssmDouble b){
 	if (a<b)return a;
 	else return b;
@@ -18,5 +19,5 @@
 	else return b;
 }
-double max(double a,double b){
+IssmDouble max(IssmDouble a,IssmDouble b){
 	if (a>b)return a;
 	else return b;
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/isnan.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/isnan.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/isnan.cpp	(revision 12878)
@@ -1,9 +1,10 @@
 /*This routine only used by Intel compler: */
-#ifdef _INTEL_WIN_
 
-int isnan(double x){
-	if (x!=x)return 1;
-	else return 0;
+#include "../../include/include.h"
+#include "isnan.h"
+
+#ifdef _HAVE_ADOLC_
+template <> int xIsNan<adouble> (const adouble& X) {
+  return isnan(X.getValue());
 }
 #endif
-
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/isnan.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/isnan.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/isnan.h	(revision 12878)
@@ -3,11 +3,20 @@
  */ 
 
-#ifndef _ISNAN_INTEL_H_
-#define _ISNAN_INTEL_H_
+#ifndef _XISNAN_H_
+#define _XISNAN_H_
 
+#include <cmath>
+
+template <class T> int xIsNan(const T& X) {
 #ifdef _INTEL_WIN_
-int isnan(double X);
+		return (X!=X)?1:0;
+#else
+		return isnan(X);
+#endif
+}
+
+#ifdef _HAVE_ADOLC_
+template <> int xIsNan<adouble> (const adouble& X);
 #endif
 
 #endif
-
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/numerics.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/numerics.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/numerics.h	(revision 12878)
@@ -9,4 +9,5 @@
 #include "./GaussPoints.h"
 #include "./isnan.h"
+#include "./recast.h"
 
 class Input;
@@ -16,17 +17,17 @@
 struct OptPars;
 
-double min(double a,double b);
-double max(double a,double b);
+IssmDouble min(IssmDouble a,IssmDouble b);
+IssmDouble max(IssmDouble a,IssmDouble b);
 int    min(int a,int b);
 int    max(int a,int b);
-double OptFunc(double scalar, OptArgs* optargs);
-void   BrentSearch(double* psearch_scalar,double* pJ,OptPars* optpars,double (*f)(double,OptArgs*), OptArgs* optargs);
-void   OptimalSearch(double* psearch_scalar,double* pJ,OptPars* optpars,double (*f)(double,OptArgs*), OptArgs* optargs);
-void   cross(double* result,double* vector1,double* vector2);
-void   IsInputConverged(double* peps, Input** new_inputs,Input** old_inputs,int num_inputs,int criterion_enum);
-void   UnitConversion(double* values, int numvalues,int direction_enum, int type_enum);
-double UnitConversion(double value, int direction_enum, int type_enum);
+IssmDouble OptFunc(IssmDouble scalar, OptArgs* optargs);
+void   BrentSearch(IssmDouble* psearch_scalar,IssmDouble* pJ,OptPars* optpars,IssmDouble (*f)(IssmDouble,OptArgs*), OptArgs* optargs);
+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(double* T,double* xzvectors);
+void   XZvectorsToCoordinateSystem(IssmDouble* T,IssmDouble* xzvectors);
 #ifdef _HAVE_PETSC_
 void   PetscOptionsFromAnalysis(Parameters* parameters,int analysis_type);
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/recast.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/recast.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Numerics/recast.h	(revision 12878)
@@ -0,0 +1,39 @@
+/*
+ * recast.h
+ *
+ *  Created on: Jun 26, 2012
+ *      Author: utke
+ */
+
+#ifndef _RECAST_H_
+#define _RECAST_H_
+
+#ifndef _HAVE_ADOLC_
+
+template<class To, class From>
+To reCast(const From& from) {
+    return (To)from;
+}
+
+#else
+
+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) {
+    return ForPartialSpecialization<To,From>::reCast(from);
+}
+/**
+ * partial specialization
+ */
+template<class To>
+struct ForPartialSpecialization<To,adouble> {
+    static  To reCast(const adouble& from ) { return (To) (from.getValue());}
+};
+
+#endif
+
+#endif
Index: sm/branches/trunk-jpl-damage/src/c/shared/Sorting/Quicksort.c
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Sorting/Quicksort.c	(revision 12877)
+++ 	(revision )
@@ -1,19 +1,0 @@
-void swap(int *a, int *b) {
-	int t=*a; *a=*b; *b=t;
-}
-void sort(int arr[], int beg, int end) {
-	  
-	if (end > beg + 1) {
-		int piv = arr[beg], l = beg + 1, r = end;
-		while (l < r)
-		{
-			if (arr[l] <= piv)
-				l++;
-			else
-				swap(&arr[l], &arr[--r]);
-		}
-		swap(&arr[--l], &arr[beg]);
-		sort(arr, beg, l);
-		sort(arr, r, end);
-	}
-}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Sorting/binary_search.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Sorting/binary_search.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Sorting/binary_search.cpp	(revision 12878)
@@ -11,9 +11,9 @@
 #include <stdio.h>
 
-int binary_search(int* poffset,int target, int* sorted_integers,int num_integers){
+int binary_search(int* poffset,int target,int* sorted_integers,int num_integers){
 
 	/*output: */
 	int offset;  //offset, if found
-	int found=0;  //found=0 if target is not found, 1 otherwise.
+	int found=0; //found=0 if target is not found, 1 otherwise.
 
 	/*intermediary: */
@@ -64,3 +64,2 @@
 	return found;
 }
-
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Sorting/sorting.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Sorting/sorting.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Sorting/sorting.h	(revision 12878)
@@ -6,7 +6,5 @@
 #define  _SORTING_H_
 
-int binary_search(int* poffset,int target, int* sorted_integers,int num_integers);
-
+int binary_search(int* poffset,int target,int* sorted_integers,int num_integers);
 
 #endif //ifndef _SORTING_H_
-
Index: /issm/branches/trunk-jpl-damage/src/c/shared/String/DescriptorIndex.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/String/DescriptorIndex.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/String/DescriptorIndex.cpp	(revision 12878)
@@ -23,10 +23,10 @@
 	/*retrieve first token, separated by underscore: */
 	pch = strtok (descriptor,"_");
-	if(!pch)_error_("%s%s%s"," descriptor ",descriptor," is not correctly formatted!");
+	if(!pch)_error2_("descriptor " << descriptor << " is not correctly formatted!");
 
 	if (strncmp(pch,"scaled",6)==0){
 		/*we have a scaled variable. recover the root: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error_("%s%s%s"," scaled descriptor ",descriptor," is not correctly formatted!");
+		if(!pch)_error2_("scaled descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 
@@ -44,9 +44,9 @@
 		/*we have an indexed variable. recover the root: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error_("%s%s%s"," indexed descriptor ",descriptor," is not correctly formatted!");
+		if(!pch)_error2_("indexed descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 		/*now recover  the index: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error_("%s%s%s"," indexed descriptor ",descriptor," is not correctly formatted!");
+		if(!pch)_error2_("indexed descriptor " << descriptor << " is not correctly formatted!");
 		sscanf(pch,"%i",pindex);
 		return IndexedEnum;
@@ -55,9 +55,9 @@
 		/*we have an indexed variable. recover the root: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error_("%s%s%s"," nodal descriptor ",descriptor," is not correctly formatted!");
+		if(!pch)_error2_("nodal descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 		/*now recover  the index: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error_("%s%s%s"," nodal descriptor ",descriptor," is not correctly formatted!");
+		if(!pch)_error2_("nodal descriptor " << descriptor << " is not correctly formatted!");
 		sscanf(pch,"%i",pindex);
 		return NodalEnum;
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Sys/ProfilingEnd.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Sys/ProfilingEnd.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Sys/ProfilingEnd.cpp	(revision 12878)
@@ -0,0 +1,43 @@
+/*!\file:  ProfilingEnd.cpp
+ * \brief ProfilingEnd.c: finalize profiling after calling a routine. Needs to mirror a ProfilingStart routine.
+ */
+
+/*Include files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "../../include/macros.h"
+#include "../shared.h"
+#include "../../io/io.h"
+/*}}}*/
+
+void ProfilingEnd(double* pSolution_time, double* pMemory_use, double* pCurrent_flops, double Time_start, double Flops_start){
+
+	double Solution_time, Memory_use, Current_flops;
+	double Time_finish, Flops_finish, memUse;
+	
+	#ifdef _HAVE_PETSC_
+	PetscGetTime(&Time_finish);
+	PetscGetFlops(&Flops_finish);
+	PetscMemoryGetCurrentUsage(&memUse);
+	
+	Solution_time=Time_finish-Time_start;
+	Current_flops=Flops_finish-Flops_start;
+	_pprintLine_("PETSc elapsed time  : " << Solution_time << "  Seconds");
+	_pprintLine_("PETSc elapsed flops : " << Current_flops << "  Flops");
+	_pprintLine_("PETSc memory used   : " << memUse << "  Bytes");
+	#else
+		_error_("Profiling not supported under this numerical toolkit");
+	#endif
+
+	/*Assign pointers: */
+	*pSolution_time=Solution_time;
+	*pMemory_use=memUse;
+	*pCurrent_flops=Current_flops;
+	return;
+}
+
+
+
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Sys/ProfilingStart.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Sys/ProfilingStart.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Sys/ProfilingStart.cpp	(revision 12878)
@@ -0,0 +1,32 @@
+/*!\file:  ProfilingStart.cpp
+ * \brief ProfilingStart.c: initialize profiling before calling a routine
+ */
+
+
+/*Include files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "../../include/macros.h"
+#include "../shared.h"
+#include "../../io/io.h"
+/*}}}*/
+
+void ProfilingStart(double* pTime_start, double* pFlops_start){
+	
+	double Time_start, Flops_start;
+	
+	#ifdef _HAVE_PETSC_
+		PetscGetTime(&Time_start);
+		PetscGetFlops(&Flops_start );
+	#else
+		_error_("Profiling not supported under this numerical toolkit");
+	#endif
+
+	/*Assign pointers: */
+	*pTime_start=Time_start;
+	*pFlops_start=Flops_start;
+	return;
+}
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Sys/sys.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Sys/sys.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Sys/sys.h	(revision 12878)
@@ -0,0 +1,12 @@
+/* \file sys.h
+ * \brief: header file for ISSM system routines (profiling, timing, etc ...)
+ */
+
+
+#ifndef _ISSM_SYS_H_
+#define _ISSM_SYS_H_
+
+void ProfilingEnd(double* pSolution_time, double* pMemory_use, double* pCurrent_flops, double Time_start, double Flops_start);
+void ProfilingStart(double* pTime_start, double* pFlops_start);
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Threads/LaunchThread.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Threads/LaunchThread.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Threads/LaunchThread.cpp	(revision 12878)
@@ -20,5 +20,5 @@
 
 #include "./issm_threads.h"
-#include "../Alloc/alloc.h"
+#include "../Alloc/xNewDelete.h"
 #include "../Exceptions/exceptions.h"
 #include "../../include/include.h"
@@ -28,12 +28,11 @@
 	#ifdef _MULTITHREADING_
 	int i;
-	int* status=NULL;
-
-	pthread_t* threads=NULL;
-	pthread_handle* handles=NULL;
+	int            *status  = NULL;
+	pthread_t      *threads = NULL;
+	pthread_handle *handles = NULL;
 	
 	/*dynamically allocate: */
-	threads=(pthread_t*)xmalloc(num_threads*sizeof(pthread_t));
-	handles=(pthread_handle*)xmalloc(num_threads*sizeof(pthread_handle));
+	threads=xNew<pthread_t>(num_threads);
+	handles=xNew<pthread_handle>(num_threads);
 
 	for(i=0;i<num_threads;i++){
@@ -42,20 +41,19 @@
 		handles[i].num=num_threads;
 	}
-	
 	for(i=0;i<num_threads;i++){
 
 		if(pthread_create(threads+i,NULL,function,(void*)(handles+i))){
-			_error_(" pthread_create error");
+			_error2_("pthread_create error");
 		}
 	}
 	for(i=0;i<num_threads;i++){
 		if(pthread_join(threads[i],(void**)&status)){
-			_error_(" pthread_join error");
+			_error2_("pthread_join error");
 		}
 	}
 	
 	/*Free ressources:*/
-	xfree((void**)&threads);
-	xfree((void**)&handles);
+	xDelete<pthread_t>(threads);
+	xDelete<pthread_handle>(handles);
 
 	#else
@@ -67,4 +65,3 @@
 	function((void*)&handle);
 	#endif
-
 }
Index: /issm/branches/trunk-jpl-damage/src/c/shared/TriMesh/SplitMeshForRifts.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/TriMesh/SplitMeshForRifts.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/TriMesh/SplitMeshForRifts.cpp	(revision 12878)
@@ -3,5 +3,5 @@
  */
 #include "./trimesh.h"
-
+#include "../Alloc/xNewDelete.h"
 #include "../Alloc/alloc.h"
 
@@ -52,5 +52,5 @@
 
 	/*Go through all nodes of the rift segments, and start splitting the mesh: */
-	flags=(int*)xcalloc(nods,sizeof(int)); //to make sure we don't split the same nodes twice!
+	flags=xNewZeroInit<int>(nods); //to make sure we don't split the same nodes twice!
 	for (i=0;i<nriftsegs;i++){
 		for (j=0;j<2;j++){
Index: /issm/branches/trunk-jpl-damage/src/c/shared/TriMesh/TriMeshUtils.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 12878)
@@ -7,4 +7,5 @@
 #include "./trimesh.h"
 #include "../Exceptions/exceptions.h"
+#include "../Alloc/xNewDelete.h"
 #include "../Alloc/alloc.h"
 #include "../../include/include.h"
@@ -53,5 +54,5 @@
 	current_size=max_number_elements;
 	NumGridElements=0;
-	GridElements=(int*)xmalloc(max_number_elements*sizeof(int));
+	GridElements=xNew<int>(max_number_elements);
 
 	for (i=0;i<nel;i++){
@@ -65,5 +66,5 @@
 				else{
 					/*Reallocate another max_number_elements slots in the GridElements: */
-					GridElementsRealloc=(int*)xrealloc(GridElements,(current_size+max_number_elements)*sizeof(int));
+					GridElementsRealloc=xReNew<int>(GridElements,current_size,(current_size+max_number_elements));
 					if (!GridElementsRealloc){
 						noerr=0;
@@ -81,5 +82,5 @@
 	cleanup_and_return:
 	if(!noerr){
-		xfree((void**)&GridElements);
+		xDelete<int>(GridElements);
 	}
 	/*Allocate return pointers: */
@@ -128,5 +129,5 @@
 
 	/*Allocate segmentflags: */
-	riftsegments_uncompressed=(int*)xcalloc(nsegs*5,sizeof(int));
+	riftsegments_uncompressed=xNewZeroInit<int>(nsegs*5);
 
 	/*Find the segments that belong to a rift: they are the ones that see two elements. The other ones belong to a boundary 
@@ -165,5 +166,5 @@
 
 	/*Compress riftsegments_uncompressed:*/
-	riftsegments=(int*)xmalloc(nriftsegs*4*sizeof(int));
+	riftsegments=xNew<int>(nriftsegs*4);
 	counter=0;
 	for (i=0;i<nsegs;i++){
@@ -177,5 +178,5 @@
 	}
 
-	xfree((void**)&riftsegments_uncompressed);
+	xDelete<int>(riftsegments_uncompressed);
 	
 	/*Assign output pointers: */
@@ -202,5 +203,5 @@
 	/*Figure out the list of elements  that are on the same side of the rift. To do so, we start from one 
 	 * side of the rift and keep rotating in the same direction:*/
-	GridElementListOnOneSideOfRift=(int*)xmalloc(NumGridElements*sizeof(int));
+	GridElementListOnOneSideOfRift=xNew<int>(NumGridElements);
 	//bootstrap the GridElementListOnOneSideOfRift by filling elements from riftsegments: */
 	GridElementListOnOneSideOfRift[0]=*(riftsegments+4*segmentnumber+0); /*this one does not belong to the same side, but is just there 
@@ -241,5 +242,5 @@
 
 	/*Free ressources: */
-	xfree((void**)&GridElements);
+	xDelete<int>(GridElements);
 	/*Assign output pointers: */
 	*pNumGridElementListOnOneSideOfRift=NumGridElementListOnOneSideOfRift;
@@ -380,14 +381,14 @@
 
 	/*input: */
-	double* segments=NULL;
-	double* segmentmarkerlist=NULL;
+	double *segments          = NULL;
+	double *segmentmarkerlist = NULL;
 	int numsegs;
 	
 	/*output: */
-	int* riftsnumsegs=NULL;
-	double** riftssegments=NULL;
-	int new_numsegs;
-	double* new_segments=NULL;
-	double* new_segmentmarkers=NULL;
+	int      new_numsegs;
+	int     *riftsnumsegs       = NULL;
+	double **riftssegments      = NULL;
+	double  *new_segments       = NULL;
+	double  *new_segmentmarkers = NULL;
 
 	/*intermediary: */
@@ -406,6 +407,6 @@
 	/*Allocate new segments: */
 	new_numsegs=counter;
-	new_segments=(double*)xmalloc(new_numsegs*3*sizeof(double));
-	new_segmentmarkers=(double*)xmalloc(new_numsegs*sizeof(double));
+	new_segments=xNew<double>(new_numsegs*3);
+	new_segmentmarkers=xNew<double>(new_numsegs);
 
 	/*Copy new segments info : */
@@ -422,6 +423,6 @@
 
 	/*Now deal with rift segments: */
-	riftsnumsegs=(int*)xmalloc(numrifts*sizeof(int));
-	riftssegments=(double**)xmalloc(numrifts*sizeof(double*));
+	riftsnumsegs=xNew<int>(numrifts);
+	riftssegments=xNew<double*>(numrifts);
 	for (i=0;i<numrifts;i++){
 		/*Figure out how many segments for rift i: */
@@ -431,5 +432,5 @@
 		}
 		riftsnumsegs[i]=counter;
-		riftsegment=(double*)xmalloc(counter*3*sizeof(double));
+		riftsegment=xNew<double>(counter*3);
 		/*Copy new segments info :*/
 		counter=0;
@@ -446,5 +447,5 @@
 
 	/*Free ressources: */
-	xfree((void**)&segments);
+	xDelete<double>(segments);
 
 	/*Assign output pointers: */
@@ -465,6 +466,6 @@
 
 	/*output: */
-	int* riftsnumpairs=NULL;
-	double** riftspairs=NULL;
+	int     *riftsnumpairs = NULL;
+	double **riftspairs    = NULL;
 
 	/*intermediary :*/
@@ -474,11 +475,11 @@
 	int     node1,node2,node3,node4;
 
-	riftsnumpairs=(int*)xmalloc(numrifts*sizeof(int));
-	riftspairs=(double**)xmalloc(numrifts*sizeof(double*));
+	riftsnumpairs=xNew<int>(numrifts);
+	riftspairs=xNew<double*>(numrifts);
 	for (i=0;i<numrifts;i++){
 		segments=riftssegments[i];
 		numsegs=riftsnumsegments[i];
 		riftsnumpairs[i]=numsegs;
-		pairs=(double*)xmalloc(2*numsegs*sizeof(double));
+		pairs=xNew<double>(2*numsegs);
 		for (j=0;j<numsegs;j++){
 			*(pairs+2*j+0)=*(segments+3*j+2); //retrieve element to which this segment belongs.
@@ -500,9 +501,7 @@
 	}
 
-
 	/*Assign output pointers: */
 	*priftsnumpairs=riftsnumpairs;
 	*priftspairs=riftspairs;
-
 	return noerr;
 }/*}}}*/
@@ -522,17 +521,16 @@
 
 	/*intermediary: */
-	double* riftsegments=NULL;
-	double* riftpairs=NULL;
+	double *riftsegments = NULL;
+	double *riftpairs    = NULL;
 	int     node1,node2,node3,node4,temp_node;
 	double  el2;
 	int     newnods; //temporary # node counter.
 	double  xmin,ymin;
-	double* xreal=NULL;
-	double* yreal=NULL;
-	int* nodes=NULL;
-	int* mergingnodes=NULL;
+	double *xreal        = NULL;
+	double *yreal        = NULL;
+	int    *nodes        = NULL;
+	int    *mergingnodes = NULL;
 	int     max_size;
 	int     redundant;
-
 
 	/*Recover input: */
@@ -562,6 +560,6 @@
 		max_size+=rifts1numsegs[i];
 	}
-	nodes=(int*)xmalloc(max_size*sizeof(int));
-	mergingnodes=(int*)xmalloc(max_size*sizeof(int));
+	nodes=xNew<int>(max_size);
+	mergingnodes=xNew<int>(max_size);
 
 	/*Go through the rifts segments, and identify which node we are going to merge with its counterpart on the other side 
@@ -678,6 +676,6 @@
 		}
 	}
-	xfree((void**)&x); x=xreal;
-	xfree((void**)&y); y=yreal;
+	xDelete<double>(x); x=xreal;
+	xDelete<double>(y); y=yreal;
 
 	/*Assign output pointers:*/
@@ -688,5 +686,4 @@
 	*psegments=segments;
 	*pnumsegs=numsegs;
-
 	return noerr;
 }/*}}}*/
@@ -716,5 +713,4 @@
 	*priftflag=riftflag;
 	*pnumrifts=numrifts;
-
 	return noerr;
 }/*}}}*/
@@ -726,12 +722,12 @@
 
 	/*intermediary: */
-	double* riftsegments=NULL;
-	double* riftpairs=NULL;
+	double *riftsegments = NULL;
+	double *riftpairs    = NULL;
 	int numsegs;
 
 	/*ordering and copy: */
-	int*    order=NULL;
-	double* riftsegments_copy=NULL;
-	double* riftpairs_copy=NULL;
+	int    *order             = NULL;
+	double *riftsegments_copy = NULL;
+	double *riftpairs_copy    = NULL;
 
 	/*node and element manipulation: */
@@ -744,5 +740,5 @@
 
 	/*Allocate byproduct of this routine, riftstips: */
-	riftstips=(double*)xmalloc(numrifts*2*sizeof(double));
+	riftstips=xNew<double>(numrifts*2);
 
 	/*Go through all rifts: */
@@ -754,7 +750,7 @@
 		/*Allocate copy of riftsegments and riftpairs, 
 		 *as well as ordering vector: */
-		riftsegments_copy=(double*)xmalloc(numsegs*3*sizeof(double));
-		riftpairs_copy=(double*)xmalloc(numsegs*2*sizeof(double));
-		order=(int*)xmalloc(numsegs*sizeof(int));
+		riftsegments_copy=xNew<double>(numsegs*3);
+		riftpairs_copy=xNew<double>(numsegs*2);
+		order=xNew<int>(numsegs);
 
 		/*First find the tips, using the pairs. If a pair of elements has one node in common, this node is a rift tip: */
@@ -814,5 +810,4 @@
 		*(riftstips+2*i+0)=(double)tip1;
 		*(riftstips+2*i+1)=(double)tip2;
-
 
 		/*We have the two tips for this rift.  Go from tip1 to tip2, and figure out the order in which segments are sequential. 
@@ -865,7 +860,7 @@
 		}
 
-		xfree((void**)&order);
-		xfree((void**)&riftsegments_copy);
-		xfree((void**)&riftpairs_copy);
+		xDelete<int>(order);
+		xDelete<double>(riftsegments_copy);
+		xDelete<double>(riftpairs_copy);
 
 	}
@@ -887,7 +882,7 @@
 
 	/*output: */
-	double** riftspenaltypairs=NULL;
-	double*  riftpenaltypairs=NULL;
-	int*     riftsnumpenaltypairs=NULL;
+	double **riftspenaltypairs    = NULL;
+	double  *riftpenaltypairs     = NULL;
+	int     *riftsnumpenaltypairs = NULL;
 
 	/*intermediary: */
@@ -901,6 +896,6 @@
 
 	/*Allocate: */
-	riftspenaltypairs=(double**)xmalloc(numrifts*sizeof(double*));
-	riftsnumpenaltypairs=(int*)xmalloc(numrifts*sizeof(int));
+	riftspenaltypairs=xNew<double*>(numrifts);
+	riftsnumpenaltypairs=xNew<int>(numrifts);
 
 	for(i=0;i<numrifts;i++){
@@ -910,5 +905,5 @@
 
 		/*allocate riftpenaltypairs, and riftnumpenaltypairs: */
-		if((numsegs/2-1)!=0)riftpenaltypairs=(double*)xcalloc((numsegs/2-1)*RIFTPENALTYPAIRSWIDTH,sizeof(double));
+		if((numsegs/2-1)!=0)riftpenaltypairs=xNewZeroInit<double>((numsegs/2-1)*RIFTPENALTYPAIRSWIDTH);
 		
 		/*Go through only one flank of the rifts, not counting the tips: */
@@ -1006,11 +1001,8 @@
 		riftsnumpenaltypairs[i]=(numsegs/2-1);
 	}
-			
-
 
 	/*Assign output pointers: */
 	*priftspenaltypairs=riftspenaltypairs;
 	*priftsnumpenaltypairs=riftsnumpenaltypairs;
-
 	return noerr;
 }
@@ -1143,5 +1135,4 @@
 	*py=y;
 	*pnods=nods;
-
 	return noerr;
 }
Index: /issm/branches/trunk-jpl-damage/src/c/shared/Wrapper/wrappershared.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/Wrapper/wrappershared.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/Wrapper/wrappershared.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define _WRAPPER_SHARED_H_
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 int ModuleBoot(void);
Index: /issm/branches/trunk-jpl-damage/src/c/shared/shared.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/shared/shared.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/shared/shared.h	(revision 12878)
@@ -6,17 +6,17 @@
 #define _SHARED_H_
 
-
 #include "Alloc/alloc.h"
-#include "Alloc/alloc_module.h"
+#include "Alloc/xNewDelete.h"
+#include "Bamg/shared.h"
+#include "Elements/elements.h"
 #include "Exceptions/exceptions.h"
 #include "Exp/exp.h"
+#include "Matrix/matrix.h"
+#include "MemOps/xMemCpy.h"
+#include "Numerics/numerics.h"
+#include "Sorting/sorting.h"
+#include "Sys/sys.h"
+#include "Threads/issm_threads.h"
 #include "TriMesh/trimesh.h"
-#include "Sorting/sorting.h"
-#include "Elements/elements.h"
-#include "Matrix/matrix.h"
-#include "Numerics/numerics.h"
-#include "Dofs/dofs.h"
-#include "Threads/issm_threads.h"
-#include "Bamg/shared.h"
 #include "Wrapper/wrappershared.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp	(revision 12878)
@@ -10,5 +10,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
@@ -35,5 +35,5 @@
 			break;
 		default:
-			_error_("No adjoint has been implemented for solution %s yet",EnumToStringx(solutiontype));
+			_error2_("No adjoint has been implemented for solution " << EnumToStringx(solutiontype) << " yet");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/AnalysisConfiguration.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/AnalysisConfiguration.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/AnalysisConfiguration.cpp	(revision 12878)
@@ -10,5 +10,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
@@ -29,5 +29,5 @@
 		case DiagnosticSolutionEnum:
 			numanalyses=5;
-			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses=xNew<int>(numanalyses);
 			analyses[0]=DiagnosticHorizAnalysisEnum;
 			analyses[1]=DiagnosticVertAnalysisEnum;
@@ -39,5 +39,5 @@
 		case SteadystateSolutionEnum:
 			numanalyses=8;
-			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses=xNew<int>(numanalyses);
 			analyses[0]=DiagnosticHorizAnalysisEnum;
 			analyses[1]=DiagnosticVertAnalysisEnum;
@@ -52,5 +52,5 @@
 		case ThermalSolutionEnum:
 			numanalyses=2;
-			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses=xNew<int>(numanalyses);
 			analyses[0]=ThermalAnalysisEnum;
 			analyses[1]=MeltingAnalysisEnum;
@@ -59,5 +59,5 @@
 		case EnthalpySolutionEnum:
 			numanalyses=1;
-			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses=xNew<int>(numanalyses);
 			analyses[0]=EnthalpyAnalysisEnum;
 			break;
@@ -65,5 +65,5 @@
 		case HydrologySolutionEnum:
 			numanalyses=3;
-			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses=xNew<int>(numanalyses);
 			analyses[0]=HydrologyAnalysisEnum;
 			analyses[1]=SurfaceSlopeAnalysisEnum;
@@ -73,5 +73,5 @@
 		case PrognosticSolutionEnum:
 			numanalyses=1;
-			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses=xNew<int>(numanalyses);
 			analyses[0]=PrognosticAnalysisEnum;
 			break;
@@ -79,5 +79,5 @@
 		case BalancethicknessSolutionEnum:
 			numanalyses=1;
-			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses=xNew<int>(numanalyses);
 			analyses[0]=BalancethicknessAnalysisEnum;
 			break;
@@ -85,5 +85,5 @@
 		case SurfaceSlopeSolutionEnum:
 			numanalyses=1;
-			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses=xNew<int>(numanalyses);
 			analyses[0]=SurfaceSlopeAnalysisEnum;
 			break;
@@ -91,5 +91,5 @@
 		case BedSlopeSolutionEnum:
 			numanalyses=1;
-			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses=xNew<int>(numanalyses);
 			analyses[0]=BedSlopeAnalysisEnum;
 			break;
@@ -97,5 +97,5 @@
 		case TransientSolutionEnum:
 			numanalyses=9;
-			analyses=(int*)xmalloc(numanalyses*sizeof(int));
+			analyses=xNew<int>(numanalyses);
 			analyses[0]=DiagnosticHorizAnalysisEnum;
 			analyses[1]=DiagnosticVertAnalysisEnum;
@@ -110,5 +110,5 @@
 		
 		default:
-			_error_("%s%s%s"," solution type: ",EnumToStringx(solutiontype)," not supported yet!");
+			_error2_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
 			break;
 	}
@@ -117,4 +117,4 @@
 	if(pnumanalyses) *pnumanalyses=numanalyses;
 	if(panalyses)    *panalyses=analyses;
-	else              xfree((void**)&analyses);
+	else              xDelete<int>(analyses);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/CorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/CorePointerFromSolutionEnum.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/CorePointerFromSolutionEnum.cpp	(revision 12878)
@@ -10,5 +10,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
@@ -29,5 +29,5 @@
 			solutioncore=&diagnostic_core;
 			#else
-			_error_("ISSM was not compiled with diagnostic capabilities. Exiting");
+			_error2_("ISSM was not compiled with diagnostic capabilities. Exiting");
 			#endif
 			break;
@@ -36,5 +36,5 @@
 			solutioncore=&steadystate_core;
 			#else
-			_error_("ISSM was not compiled with steady state capabilities. Exiting");
+			_error2_("ISSM was not compiled with steady state capabilities. Exiting");
 			#endif
 			break;
@@ -43,5 +43,5 @@
 			solutioncore=&thermal_core;
 			#else
-			_error_("ISSM was not compiled with thermal capabilities. Exiting");
+			_error2_("ISSM was not compiled with thermal capabilities. Exiting");
 			#endif
 			break;
@@ -50,5 +50,5 @@
 			solutioncore=&enthalpy_core;
 			#else
-			_error_("ISSM was not compiled with thermal capabilities. Exiting");
+			_error2_("ISSM was not compiled with thermal capabilities. Exiting");
 			#endif
 			break;
@@ -57,5 +57,5 @@
 			solutioncore=&balancethickness_core;
 			#else
-			_error_("ISSM was not compiled with balanced capabilities. Exiting");
+			_error2_("ISSM was not compiled with balanced capabilities. Exiting");
 			#endif
 			break;
@@ -64,5 +64,5 @@
 			solutioncore=&hydrology_core;
 			#else
-			_error_("ISSM was not compiled with hydrology capabilities. Exiting");
+			_error2_("ISSM was not compiled with hydrology capabilities. Exiting");
 			#endif
 			break;
@@ -71,5 +71,5 @@
 			solutioncore=&surfaceslope_core;
 			#else
-			_error_("ISSM was not compiled with slope capabilities. Exiting");
+			_error2_("ISSM was not compiled with slope capabilities. Exiting");
 			#endif
 			break;
@@ -78,5 +78,5 @@
 			solutioncore=&bedslope_core;
 			#else
-			_error_("ISSM was not compiled with slope capabilities. Exiting");
+			_error2_("ISSM was not compiled with slope capabilities. Exiting");
 			#endif
 			break;
@@ -85,5 +85,5 @@
 			solutioncore=&transient_core;
 			#else
-			_error_("ISSM was not compiled with transient capabilities. Exiting");
+			_error2_("ISSM was not compiled with transient capabilities. Exiting");
 			#endif
 			break;
@@ -92,9 +92,9 @@
 			solutioncore=&prognostic_core;
 			#else
-			_error_("ISSM was not compiled with prognostic capabilities. Exiting");
+			_error2_("ISSM was not compiled with prognostic capabilities. Exiting");
 			#endif
 			break;
 		default:
-			_error_("%s%s%s"," solution type: ",EnumToStringx(solutiontype)," not supported yet!");
+			_error2_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/ProcessArguments.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/ProcessArguments.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/ProcessArguments.cpp	(revision 12878)
@@ -4,4 +4,6 @@
 
 #include <stdio.h>
+#include <cstring>
+
 #include "../shared/shared.h"
 #include "../include/include.h"
@@ -15,12 +17,12 @@
 	char *lockfilename   = NULL;
 
-	if(argc<2)_error_("Usage error: no solution requested");
+	if(argc<2)_error2_("Usage error: no solution requested");
 	*solution_type=StringToEnumx(argv[1]);
-	if(argc<3)_error_("Usage error: missing model name");
+	if(argc<3)_error2_("Usage error: missing model name");
 	modelname=argv[3];
-	binfilename    = (char*)xmalloc((strlen(modelname)+strlen(".bin")   +1)*sizeof(char)); sprintf(binfilename,   "%s%s",modelname,".bin");
-	outbinfilename = (char*)xmalloc((strlen(modelname)+strlen(".outbin")+1)*sizeof(char)); sprintf(outbinfilename,"%s%s",modelname,".outbin");
-	petscfilename  = (char*)xmalloc((strlen(modelname)+strlen(".petsc") +1)*sizeof(char)); sprintf(petscfilename, "%s%s",modelname,".petsc");
-	lockfilename   = (char*)xmalloc((strlen(modelname)+strlen(".lock")  +1)*sizeof(char)); sprintf(lockfilename,  "%s%s",modelname,".lock");
+	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");
+	petscfilename  = xNew<char>(strlen(modelname)+strlen(".petsc") +1); sprintf(petscfilename, "%s%s",modelname,".petsc");
+	lockfilename   = xNew<char>(strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s",modelname,".lock");
 
 	/*Clean up and assign output pointer*/
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/ResetBoundaryConditions.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/ResetBoundaryConditions.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/ResetBoundaryConditions.cpp	(revision 12878)
@@ -3,5 +3,5 @@
  */ 
 
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../modules/modules.h"
 #include "../io/io.h"
@@ -15,5 +15,5 @@
 	int    i;
 
-	_printf_(VerboseSolution(),"%s\n","   updating boundary conditions...");
+	if(VerboseSolution()) _pprintLine_("   updating boundary conditions...");
 			
 	/*set current analysis: */
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/WriteLockFile.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/WriteLockFile.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/WriteLockFile.cpp	(revision 12878)
@@ -17,8 +17,8 @@
 	if(my_rank==0){
 		fid=fopen(filename,"w");
-		if(fid==NULL) _error_("%s%s","error message: could not open lock file ",filename);
+		if(fid==NULL) _error2_("error message: could not open lock file " << filename);
 
 		/*Close file: */
-		if(fclose(fid)!=0) _error_("%s%s","could not close lock file ",filename);
+		if(fclose(fid)!=0) _error2_("could not close lock file " << filename);
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/adjointbalancethickness_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/adjointbalancethickness_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/adjointbalancethickness_core.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -22,5 +22,5 @@
 
 	/*compute thickness */
-	_printf_(VerboseSolution(),"%s\n","   computing thickness");
+	if(VerboseSolution()) _pprintLine_("   computing thickness");
 	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
 	solver_linear(femmodel);
@@ -30,5 +30,5 @@
 
 	/*compute adjoint*/
-	_printf_(VerboseSolution(),"%s\n","   computing adjoint");
+	if(VerboseSolution()) _pprintLine_("   computing adjoint");
 	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum,AdjointBalancethicknessAnalysisEnum);
 	solver_adjoint_linear(femmodel);
@@ -36,5 +36,5 @@
 	/*Save results*/
 	if(save_results){
-		_printf_(VerboseSolution(),"   saving results\n");
+		if(VerboseSolution()) _pprintLine_("   saving results");
 		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,AdjointEnum);
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/adjointdiagnostic_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/adjointdiagnostic_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/adjointdiagnostic_core.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -25,5 +25,5 @@
 
 	/*Compute velocities*/
-	_printf_(VerboseSolution(),"%s\n","   computing velocities");
+	if(VerboseSolution()) _pprintLine_("   computing velocities");
 	femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
 	solver_nonlinear(femmodel,conserve_loads); 
@@ -33,5 +33,5 @@
 
 	/*Compute adjoint*/
-	_printf_(VerboseSolution(),"%s\n","   computing adjoint");
+	if(VerboseSolution()) _pprintLine_("   computing adjoint");
 	femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum,AdjointHorizAnalysisEnum);
 	solver_adjoint_linear(femmodel);
@@ -39,5 +39,5 @@
 	/*Save results*/
 	if(save_results){
-		_printf_(VerboseSolution(),"   saving results\n");
+		if(VerboseSolution()) _pprintLine_("   saving results");
 		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);
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/balancethickness_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/balancethickness_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/balancethickness_core.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -24,9 +24,9 @@
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
 
-	_printf_(VerboseSolution(),"call computational core:\n");
+	if(VerboseSolution()) _pprintLine_("call computational core:");
 	solver_linear(femmodel);
 
 	if(save_results){
-		_printf_(VerboseSolution(),"   saving results\n");
+		if(VerboseSolution()) _pprintLine_("   saving results");
 		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ThicknessEnum);
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/bedslope_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/bedslope_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/bedslope_core.cpp	(revision 12878)
@@ -5,5 +5,5 @@
 #include "./solutions.h"
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../io/io.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
@@ -19,5 +19,5 @@
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
 
-	_printf_(VerboseSolution(),"%s\n","   computing slope");
+	if(VerboseSolution()) _pprintLine_("   computing slope");
 
 	/*Call on core computations: */
@@ -28,5 +28,5 @@
 	
 	if(save_results){
-		_printf_(VerboseSolution(),"   saving results\n");
+		if(VerboseSolution()) _pprintLine_("   saving results");
 		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/branches/trunk-jpl-damage/src/c/solutions/control_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/control_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/control_core.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -20,5 +20,5 @@
 	int     num_controls,num_responses;
 	int     nsteps;
-	double  tol_cm;
+	IssmDouble  tol_cm;
 	bool    cm_gradient;
 	int     dim;
@@ -28,11 +28,11 @@
 
 	int*    control_type = NULL;
-	double* responses=NULL;
+	IssmDouble* responses=NULL;
 	int*    step_responses=NULL;
-	double* maxiter=NULL;
-	double* cm_jump=NULL;
+	IssmDouble* maxiter=NULL;
+	IssmDouble* cm_jump=NULL;
 		
 	/*intermediary: */
-	double  search_scalar=1;
+	IssmDouble  search_scalar=1;
 	OptArgs optargs;
 	OptPars optpars;
@@ -43,5 +43,5 @@
 
 	/*output: */
-	double* J=NULL;
+	IssmDouble* J=NULL;
 
 	/*Recover parameters used throughout the solution*/
@@ -66,10 +66,10 @@
 
 	/*Launch once a complete solution to set up all inputs*/
-	_printf_(VerboseControl(),"%s\n","   preparing initial solution");
+	if(VerboseControl()) _pprintLine_("   preparing initial solution");
 	if(isstokes) solutioncore(femmodel);
 
 	/*Initialize responses: */
-	J=(double*)xmalloc(nsteps*sizeof(double));
-	step_responses=(int*)xmalloc(num_responses*sizeof(int));
+	J=xNew<IssmDouble>(nsteps);
+	step_responses=xNew<int>(num_responses);
 		
 	/*Initialize some of the BrentSearch arguments: */
@@ -81,5 +81,5 @@
 
 		/*Display info*/
-		_printf_(VerboseControl(),"\n%s%i%s%i\n","   control method step ",n+1,"/",nsteps);
+		if(VerboseControl()) _pprintLine_("\n" << "   control method step " << n+1 << "/" << nsteps);
 		for(i=0;i<num_responses;i++) step_responses[i]=(int)responses[n*num_responses+i];
 		femmodel->parameters->SetParam(step_responses,1,num_responses,StepResponsesEnum);
@@ -88,5 +88,5 @@
 		if(solution_type==SteadystateSolutionEnum) solutioncore(femmodel);
 
-		_printf_(VerboseControl(),"%s\n","   compute adjoint state:");
+		if(VerboseControl()) _pprintLine_("   compute adjoint state:");
 		adjointcore(femmodel);
 		gradient_core(femmodel,n,search_scalar==0);
@@ -98,9 +98,9 @@
 		}
 
-		_printf_(VerboseControl(),"%s\n","   optimizing along gradient direction");
+		if(VerboseControl()) _pprintLine_("   optimizing along gradient direction");
 		optpars.maxiter=(int)maxiter[n]; optpars.cm_jump=cm_jump[n];
 		BrentSearch(&search_scalar,J+n,&optpars,&objectivefunction,&optargs);
 
-		_printf_(VerboseControl(),"%s\n","   updating parameter using optimized search scalar"); //true means update save controls
+		if(VerboseControl()) _pprintLine_("   updating parameter using optimized search scalar"); //true means update save controls
 		InputControlUpdatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,search_scalar,true);
 		
@@ -108,5 +108,5 @@
 	}
 
-	_printf_(VerboseControl(),"%s\n","   preparing final solution");
+	if(VerboseControl()) _pprintLine_("   preparing final solution");
 	femmodel->parameters->SetParam(true,SaveResultsEnum);
 	solutioncore(femmodel);
@@ -120,9 +120,9 @@
 	cleanup_and_return:
 	/*Free ressources: */
-	xfree((void**)&control_type);
-	xfree((void**)&responses);
-	xfree((void**)&step_responses);
-	xfree((void**)&maxiter);
-	xfree((void**)&cm_jump);
-	xfree((void**)&J);
+	xDelete<int>(control_type);
+	xDelete<int>(step_responses);
+	xDelete<IssmDouble>(maxiter);
+	xDelete<IssmDouble>(responses);
+	xDelete<IssmDouble>(cm_jump);
+	xDelete<IssmDouble>(J);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/controlconvergence.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/controlconvergence.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/controlconvergence.cpp	(revision 12878)
@@ -8,5 +8,5 @@
 #endif
 
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -17,5 +17,5 @@
 #include "./solutions.h"
 
-bool controlconvergence(double J, double tol_cm){
+bool controlconvergence(IssmDouble J, IssmDouble tol_cm){
 
 	int i;
@@ -23,7 +23,7 @@
 
 	/*Has convergence been reached?*/
-	if (!isnan(tol_cm) && J<tol_cm){
+	if (!xIsNan<IssmDouble>(tol_cm) && J<tol_cm){
 		converged=true;
-		_printf_(VerboseConvergence(),"      Convergence criterion reached: J = %g < %g",J,tol_cm);
+		if(VerboseConvergence()) _pprintString_("      Convergence criterion reached: J = " << J << " < " << tol_cm);
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/controlrestart.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/controlrestart.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/controlrestart.cpp	(revision 12878)
@@ -7,5 +7,5 @@
 #include "../EnumDefinitions/EnumDefinitions.h"
 
-void controlrestart(FemModel* femmodel,double* J){
+void controlrestart(FemModel* femmodel,IssmDouble* J){
 
 	int      num_controls;
@@ -33,4 +33,4 @@
 
 	/*Clean up and return*/
-	xfree((void**)&control_type);
+	xDelete<int>(control_type);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/controltao_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/controltao_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/controltao_core.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 #include <config.h>
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -17,5 +17,5 @@
 
 /*Local prototype*/
-int FormFunctionGradient(TaoSolver,Vec,double*,Vec,void*);
+int FormFunctionGradient(TaoSolver,Vec,IssmDouble*,Vec,void*);
 int IssmMonitor(TaoSolver,void*);
 typedef struct {
@@ -30,6 +30,6 @@
 	int        nsteps,maxiter;
 	AppCtx     user;
-	TaoSolver  tao;
-	double    *dummy          = NULL;
+	TaoSolver  tao = 0;
+	IssmDouble    *dummy          = NULL;
 	int       *control_list   = NULL;
 	Vector    *X              = NULL;
@@ -41,5 +41,5 @@
 	PetscGetArgs(&argc,&args);
 	ierr = TaoInitialize(&argc,&args,(char*)0,"");
-	if(ierr) _error_("Could not initialize Tao");
+	if(ierr) _error2_("Could not initialize Tao");
 
 	/*Recover some parameters*/
@@ -50,9 +50,9 @@
 	femmodel->parameters->FindParam(&dummy,NULL,NULL,InversionMaxiterPerStepEnum);
 	femmodel->parameters->SetParam(false,SaveResultsEnum);
-	maxiter=nsteps*(int)dummy[0]; xfree((void**)&dummy);
+	maxiter=nsteps*(int)dummy[0]; xDelete<IssmDouble>(dummy);
 
 	/*Initialize TAO*/
-	_printf_(VerboseControl(),"%s\n","   Initializing the Toolkit for Advanced Optimization (TAO)");
 	TaoCreate(PETSC_COMM_WORLD,&tao);
+	if(VerboseControl()) _pprintLine_("   Initializing the Toolkit for Advanced Optimization (TAO)");
 	TaoSetFromOptions(tao);
 	TaoSetType(tao,"tao_blmvm");
@@ -78,5 +78,5 @@
 
 	/*Solver optimization problem*/
-	_printf_(VerboseControl(),"%s\n","   Starting optimization");
+	if(VerboseControl()) _pprintLine_("   Starting optimization");
 	TaoSolve(tao);
 	TaoView(tao,PETSC_VIEWER_STDOUT_WORLD);
@@ -88,5 +88,5 @@
 
 	/*Finalize*/
-	_printf_(VerboseControl(),"%s\n","   preparing final solution");
+	if(VerboseControl()) _pprintLine_("   preparing final solution");
 	femmodel->parameters->SetParam(true,SaveResultsEnum);
 	void (*solutioncore)(FemModel*)=NULL;
@@ -95,10 +95,10 @@
 
 	/*Clean up and return*/
-	xfree((void**)&control_list);
+	xDelete<int>(control_list);
 	xdelete(&X);
 	TaoDestroy(&tao);
 	TaoFinalize();
 }
-int FormFunctionGradient(TaoSolver tao, Vec Xpetsc, double *fcn,Vec G,void *userCtx){
+int FormFunctionGradient(TaoSolver tao, Vec Xpetsc, IssmDouble *fcn,Vec G,void *userCtx){
 
 	/*Retreive arguments*/
@@ -107,5 +107,5 @@
 	FemModel *femmodel       = user->femmodel;
 	int      *cost_functions = NULL;
-	double   *cost_functionsd= NULL;
+	IssmDouble   *cost_functionsd= NULL;
 	Vector   *gradient       = NULL;
 	Vector   *X              = NULL;
@@ -125,5 +125,5 @@
 
 	/*Prepare objective function*/
-	cost_functions=(int*)xmalloc(num_cost_functions*sizeof(int));
+	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);
@@ -146,6 +146,6 @@
 
 	/*Clean-up and return*/
-	xfree((void**)&cost_functions);
-	xfree((void**)&cost_functionsd);
+	xDelete<int>(cost_functions);
+	xDelete<IssmDouble>(cost_functionsd);
 	return 0;
 }
@@ -153,5 +153,5 @@
 
 	int       i,its,num_responses;
-	double    f,gnorm,cnorm,xdiff;
+	IssmDouble    f,gnorm,cnorm,xdiff;
 	AppCtx   *user      = (AppCtx *)userCtx;
 	FemModel *femmodel  = user->femmodel;
@@ -163,17 +163,17 @@
 
 	TaoGetSolutionStatus(tao, &its, &f, &gnorm, &cnorm, &xdiff, NULL);
-	if(its==0) _printf_(true,"Iter       Function      Residual  |  List of contributions\n");
-	if(its==0) _printf_(true,"-----------------------------------+-----------------------\n");
-	_printf_(true,"%4i   %12.7g  %12.7g  | ",its,f,gnorm);
+	if(its==0) _pprintLine_("Iter       Function      Residual  |  List of contributions");
+	if(its==0) _pprintLine_("-----------------------------------+-----------------------");
+	_pprintString_(setw(4)<<its<<"   "<<setw(12)<<setprecision(7)<<f<<"  "<<setw(12)<<setprecision(7)<<gnorm<<"  | ");
 
 	/*Retrieve objective functions independently*/
 	for(i=0;i<num_responses;i++){
 		Responsex(&f,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EnumToStringx(responses[i]),false,i);
-		_printf_(true," %12.7g ","",f);
+		_pprintString_(" "<<setw(12)<<setprecision(7)<<f);
 	}
-	_printf_(true,"\n");
+	_pprintLine_("");
 
 	/*Clean-up and return*/
-	xfree((void**)&responses);
+	xDelete<int>(responses);
 	return 0;
 }
@@ -181,5 +181,5 @@
 #else
 void controltao_core(FemModel* femmodel){
-	_error_("TAO not installed or PETSc version not supported");
+	_error2_("TAO not installed or PETSc version not supported");
 }
 #endif //_HAVE_TAO_ 
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/convergence.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/convergence.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/convergence.cpp	(revision 12878)
@@ -3,5 +3,5 @@
  */ 
 
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../modules/modules.h"
 #include "../io/io.h"
@@ -19,15 +19,15 @@
 	Vector* KUoldF=NULL;
 	Vector* duf=NULL;
-	double ndu,nduinf,nu;
-	double nKUF;
-	double nKUoldF;
-	double nF;
-	double solver_residue,res;
+	IssmDouble ndu,nduinf,nu;
+	IssmDouble nKUF;
+	IssmDouble nKUoldF;
+	IssmDouble nF;
+	IssmDouble solver_residue,res;
 
 	/*convergence options*/
-	double eps_res;
-	double eps_rel;
-	double eps_abs;
-	double yts;
+	IssmDouble eps_res;
+	IssmDouble eps_rel;
+	IssmDouble eps_abs;
+	IssmDouble yts;
 
 	/*If uf is NULL in input, f-set is nil, model is fully constrained, therefore converged from 
@@ -55,5 +55,5 @@
 		nF=pf->Norm(NORM_TWO);
 		solver_residue=nKUF/nF;
-		_printf_(true,"\n%s%g\n","   solver residue: norm(KU-F)/norm(F)=",solver_residue);
+		_pprintLine_("\n" << "   solver residue: norm(KU-F)/norm(F)=" << solver_residue);
 
 		//clean up
@@ -70,7 +70,7 @@
 	nF=pf->Norm(NORM_TWO);
 	res=nKUoldF/nF;
-	if (isnan(res)){
-		_printf_(true,"norm nf = %lf and norm kuold = %lf\n",nF,nKUoldF);
-		_error_("mechanical equilibrium convergence criterion is NaN!");
+	if (xIsNan<IssmDouble>(res)){
+		_pprintLine_("norm nf = " << nF << "f and norm kuold = " << nKUoldF << "f");
+		_error2_("mechanical equilibrium convergence criterion is NaN!");
 	}
 
@@ -81,14 +81,14 @@
 	//print
 	if(res<eps_res){
-		_printf_(VerboseConvergence(),"%-50s%g%s%g%s\n","   mechanical equilibrium convergence criterion",res*100," < ",eps_res*100," %");
+		if(VerboseConvergence()) _pprintLine_(setw(50) << left << "   mechanical equilibrium convergence criterion" << res*100 << " < " << eps_res*100 << " %");
 		converged=true;
 	}
 	else{ 
-		_printf_(VerboseConvergence(),"%-50s%g%s%g%s\n","   mechanical equilibrium convergence criterion",res*100," > ",eps_res*100," %");
+		if(VerboseConvergence()) _pprintLine_(setw(50) << left << "   mechanical equilibrium convergence criterion" << res*100 << " > " << eps_res*100 << " %");
 		converged=false;
 	}
 
 	/*Relative criterion (optional)*/
-	if (!isnan(eps_rel) || (VerboseConvergence())){
+	if (!xIsNan<IssmDouble>(eps_rel) || (VerboseConvergence())){
 
 		//compute norm(du)/norm(u)
@@ -96,5 +96,5 @@
 		ndu=duf->Norm(NORM_TWO); nu=old_uf->Norm(NORM_TWO);
 
-		if (isnan(ndu) || isnan(nu)) _error_("convergence criterion is NaN!");
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error2_("convergence criterion is NaN!");
 
 		//clean up
@@ -102,24 +102,24 @@
 
 		//print
-		if (!isnan(eps_rel)){
+		if (!xIsNan<IssmDouble>(eps_rel)){
 			if((ndu/nu)<eps_rel){
-				_printf_(VerboseConvergence(),"%-50s%g%s%g%s\n","   Convergence criterion: norm(du)/norm(u)",ndu/nu*100," < ",eps_rel*100," %");
+				if(VerboseConvergence()) _pprintLine_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " < " << eps_rel*100 << " %");
 			}
 			else{ 
-				_printf_(VerboseConvergence(),"%-50s%g%s%g%s\n","   Convergence criterion: norm(du)/norm(u)",ndu/nu*100," > ",eps_rel*100," %");
+				if(VerboseConvergence()) _pprintLine_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " > " << eps_rel*100 << " %");
 				converged=false;
 			}
 		}
-		else _printf_(true,"%-50s%g%s\n","   Convergence criterion: norm(du)/norm(u)",ndu/nu*100," %");
+		else _pprintLine_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " %");
 
 	}
 
 	/*Absolute criterion (Optional) = max(du)*/
-	if (!isnan(eps_abs) || (VerboseConvergence())){
+	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 (isnan(ndu) || isnan(nu)) _error_("convergence criterion is NaN!");
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error2_("convergence criterion is NaN!");
 
 		//clean up
@@ -127,14 +127,14 @@
 
 		//print
-		if (!isnan(eps_abs)){
+		if (!xIsNan<IssmDouble>(eps_abs)){
 			if ((nduinf*yts)<eps_abs){
-				_printf_(VerboseConvergence(),"%-50s%g%s%g%s\n","   Convergence criterion: max(du)",nduinf*yts," < ",eps_abs," m/yr");
+				if(VerboseConvergence()) _pprintLine_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf*yts << " < " << eps_abs << " m/yr");
 			}
 			else{
-				_printf_(VerboseConvergence(),"%-50s%g%s%g%s\n","   Convergence criterion: max(du)",nduinf*yts," > ",eps_abs," m/yr");
+				if(VerboseConvergence()) _pprintLine_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf*yts << " > " << eps_abs << " m/yr");
 				converged=false;
 			}
 		}
-		else  _printf_(true,"%-50s%g%s\n","   Convergence criterion: max(du)",nduinf*yts," m/yr");
+		else  _pprintLine_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf*yts << " m/yr");
 
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/diagnostic_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/diagnostic_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/diagnostic_core.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -59,5 +59,5 @@
 	if(ishutter){
 			
-		_printf_(VerboseSolution(),"%s\n","   computing hutter velocities");
+		if(VerboseSolution()) _pprintLine_("   computing hutter velocities");
 
 		//Take the last velocity into account so that the velocity on the MacAyeal domain is not zero
@@ -72,5 +72,5 @@
 	if (ismacayealpattyn ^ isstokes){ // ^ = xor
 		
-		_printf_(VerboseSolution(),"%s\n","   computing velocities");
+		if(VerboseSolution()) _pprintLine_("   computing velocities");
 		femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
 		if(isnewton)
@@ -82,5 +82,5 @@
 	if (ismacayealpattyn && isstokes){
 
-		_printf_(VerboseSolution(),"%s\n","   computing coupling macayealpattyn and stokes velocities and pressure ");
+		if(VerboseSolution()) _pprintLine_("   computing coupling macayealpattyn and stokes velocities and pressure ");
 		solver_stokescoupling_nonlinear(femmodel,conserve_loads);
 	}
@@ -88,5 +88,5 @@
 	if (dim==3 & (ishutter || ismacayealpattyn)){
 
-		_printf_(VerboseSolution(),"%s\n","   computing vertical velocities");
+		if(VerboseSolution()) _pprintLine_("   computing vertical velocities");
 		femmodel->SetCurrentConfiguration(DiagnosticVertAnalysisEnum);
 		solver_linear(femmodel);
@@ -95,5 +95,5 @@
 
 	if(save_results){
-		_printf_(VerboseSolution(),"   saving results\n");
+		if(VerboseSolution()) _pprintLine_("   saving results");
 		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);
@@ -105,4 +105,4 @@
 
 	/*Free ressources:*/
-	xfree((void**)&requested_outputs);
+	xDelete<int>(requested_outputs);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/enthalpy_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/enthalpy_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/enthalpy_core.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
@@ -21,5 +21,5 @@
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
 
-	_printf_(VerboseSolution(),"   computing enthalpy\n");
+	if(VerboseSolution()) _pprintLine_("   computing enthalpy");
 	femmodel->SetCurrentConfiguration(EnthalpyAnalysisEnum);
 	solver_nonlinear(femmodel,true);
@@ -29,5 +29,5 @@
 
 	if(save_results){
-		_printf_(VerboseSolution(),"   saving results\n");
+		if(VerboseSolution()) _pprintLine_("   saving results");
 		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);
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/gradient_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/gradient_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/gradient_core.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -16,6 +16,6 @@
 
 	/*Intermediaries*/
-	double  norm_inf;
-	double *norm_list    = NULL;
+	IssmDouble  norm_inf;
+	IssmDouble *norm_list    = NULL;
 	Vector*     new_gradient = NULL;
 	Vector*     gradient     = NULL;
@@ -23,9 +23,9 @@
 
 	/*Compute gradient*/
-	_printf_(VerboseControl(),"   compute cost function gradient\n");
+	if(VerboseControl()) _pprintLine_("   compute cost function gradient");
 	Gradjx(&gradient,&norm_list,femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,femmodel->parameters);
 
 	if (orthogonalize){
-		_printf_(VerboseControl(),"   orthogonalization\n");
+		if(VerboseControl()) _pprintLine_("   orthogonalization");
 		ControlInputGetGradientx(&old_gradient,femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,femmodel->parameters);
 		Orthx(&new_gradient,gradient,old_gradient); xdelete(&old_gradient); xdelete(&gradient);
@@ -37,6 +37,6 @@
 	/*Check that gradient is clean*/
 	norm_inf=new_gradient->Norm(NORM_INF);
-	if(norm_inf<=0)    _error_("||∂J/∂α||∞ = 0    gradient norm is zero");
-	if(isnan(norm_inf))_error_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
+	if(norm_inf<=0)    _error2_("||∂J/∂α||∞ = 0    gradient norm is zero");
+	if(xIsNan<IssmDouble>(norm_inf))_error2_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
 
 	/*plug back into inputs: */
@@ -48,4 +48,4 @@
 
 	/*Clean up and return*/
-	xfree((void**)&norm_list);
+	xDelete<IssmDouble>(norm_list);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/hydrology_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/hydrology_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/hydrology_core.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -17,8 +17,8 @@
 
 	/*intermediary*/
-	double time;
+	IssmDouble time;
 	int    nsteps;
-	double starttime,final_time;
-	double dt;
+	IssmDouble starttime,final_time;
+	IssmDouble dt;
 	bool   save_results;
 	int    output_frequency;
@@ -45,5 +45,5 @@
 	for(i=0;i<nsteps;i++){
 		
-		if(nsteps)_printf_(VerboseSolution(),"time step:%i/%i\n",i+1,nsteps);
+		if(nsteps)if(VerboseSolution()) _pprintLine_("time step:" << i+1 << "/" << nsteps);
 		time+=dt;
 		femmodel->parameters->SetParam(time,TimeEnum);
@@ -53,5 +53,5 @@
 
 		if(save_results && ((i+1)%output_frequency==0 || (i+1)==nsteps)){
-			_printf_(VerboseSolution(),"   saving results \n");
+			if(VerboseSolution()) _pprintLine_("   saving results ");
 			//InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,WatercolumnEnum,i+1,time);
 			//InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,HydrologyWaterVxEnum,i+1,time);
@@ -59,5 +59,5 @@
 			
 			/*unload results*/
-			_printf_(VerboseSolution(),"   saving temporary results\n");
+			if(VerboseSolution()) _pprintLine_("   saving temporary results");
 			OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
 		}
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/hydrology_core_step.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/hydrology_core_step.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/hydrology_core_step.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -13,9 +13,9 @@
 #include "../solvers/solvers.h"
 
-void hydrology_core_step(FemModel* femmodel,int step, double time){
+void hydrology_core_step(FemModel* femmodel,int step, IssmDouble time){
 	
 	bool modify_loads=true;
 
-	_printf_(VerboseSolution(),"   computing water column\n");
+	if(VerboseSolution()) _pprintLine_("   computing water column");
 	femmodel->SetCurrentConfiguration(HydrologyAnalysisEnum);
 	solver_nonlinear(femmodel,modify_loads);
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/issm.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/issm.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/issm.cpp	(revision 12878)
@@ -30,8 +30,13 @@
 
 	/*time*/
-	double   start, finish;
-	double   start_core, finish_core;
-	double   start_init, finish_init;
+	IssmPDouble   start, finish;
+	IssmPDouble   start_core, finish_core;
+	IssmPDouble   start_init, finish_init;
 	int      ierr;
+
+	/*profiling*/   
+	bool profiling = false;
+	IssmPDouble Time_start, Flops_start;
+	IssmPDouble Solution_time, Memory_use, Current_flops;
 
 	ISSMBOOT();
@@ -40,5 +45,5 @@
 	#ifdef _HAVE_PETSC_
 	ierr=PetscInitialize(&argc,&argv,(char*)0,"");  
-	if(ierr) _error_("Could not initialize Petsc");
+	if(ierr) _error2_("Could not initialize Petsc");
 	#else
 	#ifdef _HAVE_MPI_
@@ -50,5 +55,5 @@
 	MPI_Barrier(MPI_COMM_WORLD); start=MPI_Wtime();
 	#else
-	start=(double)clock();
+	start=(IssmPDouble)clock();
 	#endif
 
@@ -60,8 +65,8 @@
 
 	/*First process inputs*/
-	_printf_(true,"\n");
-	_printf_(true,"Ice Sheet System Model (%s) version %s\n",PACKAGE_NAME,PACKAGE_VERSION);
-	_printf_(true,"(website: %s contact: %s)\n",PACKAGE_URL,PACKAGE_BUGREPORT);
-	_printf_(true,"\n");
+	_pprintLine_("");
+	_pprintLine_("Ice Sheet System Model (" << PACKAGE_NAME << ") version " << PACKAGE_VERSION);
+	_pprintLine_("(website: " << PACKAGE_URL << " contact: " << PACKAGE_BUGREPORT << ")");
+	_pprintLine_("");
 	ProcessArguments(&solution_type,&binfilename,&outbinfilename,&petscfilename,&lockfilename,argc,argv);
 
@@ -73,5 +78,5 @@
 	MPI_Barrier(MPI_COMM_WORLD); start_init=MPI_Wtime();
 	#else
-	start_init=(double)clock();
+	start_init=(IssmPDouble)clock();
 	#endif
 	femmodel=new FemModel(binfilename,outbinfilename,solution_type,analyses,numanalyses);
@@ -94,22 +99,26 @@
 	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
 	femmodel->parameters->FindParam(&tao_analysis,InversionTaoEnum);
+	femmodel->parameters->FindParam(&profiling,DebugProfilingEnum); 
+
 	#ifdef _HAVE_MPI_
 	MPI_Barrier(MPI_COMM_WORLD); finish_init=MPI_Wtime();
 	#else
-	finish_init=(double)clock();
-	#endif
-
-	_printf_(true,"call computational core:\n");
+	finish_init=(IssmPDouble)clock();
+	#endif
+
+	_pprintLine_("call computational core:");
 	#ifdef _HAVE_MPI_
 	MPI_Barrier(MPI_COMM_WORLD); start_core=MPI_Wtime( );
 	#else
-	start_core=(double)clock();
-	#endif
-	
+	start_core=(IssmPDouble)clock();
+	#endif
+	
+	if(profiling)ProfilingStart(&Time_start,&Flops_start);
+
 	if(dakota_analysis){
 		#ifdef _HAVE_DAKOTA_
 		Dakotax(femmodel);
 		#else
-		_error_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
+		_error2_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
 		#endif
 	}
@@ -121,5 +130,5 @@
 		 control_core(femmodel);
 		#else
-		_error_("ISSM was not compiled with control support, cannot carry out dakota analysis!");
+		_error2_("ISSM was not compiled with control support, cannot carry out dakota analysis!");
 		#endif
 	}
@@ -127,11 +136,20 @@
 		solutioncore(femmodel);
 	}
+
+	if(profiling){
+		ProfilingEnd(&Solution_time,&Memory_use,&Current_flops,Time_start,Flops_start);
+		femmodel->results->AddObject(new DoubleExternalResult(femmodel->results->Size()+1, ProfilingSolutionTimeEnum, Solution_time, 1, 0));
+		femmodel->results->AddObject(new DoubleExternalResult(femmodel->results->Size()+1, ProfilingCurrentMemEnum, Memory_use, 1, 0));
+		femmodel->results->AddObject(new DoubleExternalResult(femmodel->results->Size()+1, ProfilingCurrentFlopsEnum, Current_flops, 1, 0));
+	}
+
+
 	#ifdef _HAVE_MPI_
 	MPI_Barrier(MPI_COMM_WORLD); finish_core=MPI_Wtime( );
 	#else
-	finish_core=(double)clock();
-	#endif
-	
-	_printf_(true,"write results to disk:\n");
+	finish_core=(IssmPDouble)clock();
+	#endif
+
+	_pprintLine_("write results to disk:");
 	OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
 
@@ -139,14 +157,14 @@
 	pfclose(output_fid,lockfilename);
 	if (waitonlock>0){
-		_printf_(true,"write lock file:\n");
+		_pprintLine_("write lock file:");
 		WriteLockFile(lockfilename);
 	}
 
-	/*Free ressources */
-	xfree((void**)&analyses);
-	xfree((void**)&lockfilename);
-	xfree((void**)&binfilename);
-	xfree((void**)&outbinfilename);
-	xfree((void**)&petscfilename);
+	/*Free resources */
+	xDelete<int>(analyses);
+	xDelete<char>(lockfilename);
+	xDelete<char>(binfilename);
+	xDelete<char>(outbinfilename);
+	xDelete<char>(petscfilename);
 	delete femmodel;
 
@@ -154,22 +172,29 @@
 	#ifdef _HAVE_MPI_
 	MPI_Barrier(MPI_COMM_WORLD); finish = MPI_Wtime( );
-	_printf_(true,"\n   %-34s %f seconds  \n","FemModel initialization elapsed time:",finish_init-start_init);
-	_printf_(true,"   %-34s %f seconds  \n","Core solution elapsed time:",finish_core-start_core);
-	_printf_(true,"\n   %s %i hrs %i min %i sec\n\n","Total elapsed time:",int((finish-start)/3600),int(int(finish-start)%3600/60),int(finish-start)%60);
-	#else
-	finish=(double)clock();
-	_printf_(true,"\n   %-34s %f seconds  \n","FemModel initialization elapsed time:",(finish_init-start_init)/CLOCKS_PER_SEC);
-	_printf_(true,"   %-34s %f seconds  \n","Core solution elapsed time:",(finish_core-start_core)/CLOCKS_PER_SEC);
-	_printf_(true,"\n   %s %i hrs %i min %i sec\n\n","Total elapsed time:",int((finish-start)/3600/CLOCKS_PER_SEC),int(int((finish-start)/CLOCKS_PER_SEC)%3600/60),(int(finish-start)/CLOCKS_PER_SEC)%60);
-	#endif
-	
-		
+	_pprintLine_("");
+	_pprintLine_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<finish_init-start_init);
+	_pprintLine_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<finish_core-start_core);
+	_pprintLine_("");
+	_pprintLine_("   Total elapsed time:"<<int((finish-start)/3600)<<" hrs "<<int(int(finish-start)%3600/60)<<" min "<<int(finish-start)%60<<" sec");
+	_pprintLine_("");
+	#else
+	finish=(IssmPDouble)clock();
+	_pprintLine_("");
+	_pprintLine_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<(finish_init-start_init)/CLOCKS_PER_SEC);
+	_pprintLine_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<(finish_core-start_core)/CLOCKS_PER_SEC);
+	_pprintLine_("");
+	_pprintLine_("   Total elapsed time:"
+				<<int((finish-start)/CLOCKS_PER_SEC/3600)<<" hrs "
+				<<int(int(finish-start)/CLOCKS_PER_SEC%3600/60)<<" min "
+				<<int(finish-start)/CLOCKS_PER_SEC%60<<" sec");
+	_pprintLine_("");
+	#endif
 	
 	#ifdef _HAVE_PETSC_
-	_printf_(true,"closing MPI and Petsc\n");
+	_pprintLine_("closing MPI and Petsc");
 	PetscFinalize(); 
 	#else
 	#ifdef _HAVE_MPI_
-	_printf_(true,"closing MPI and Petsc\n");
+	_pprintLine_("closing MPI and Petsc");
 	MPI_Finalize();
 	#endif
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/kriging.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/kriging.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/kriging.cpp	(revision 12878)
@@ -0,0 +1,177 @@
+/*!\file:  kriging.cpp
+ * \brief: kriging main parallel program
+ */ 
+
+#include "../issm.h"
+#include "../include/globals.h"
+
+/*Local prototypes*/
+void ProcessArguments2(char** pbinfilename,char** poutbinfilename,char** plockfilename,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;
+
+	/*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;
+
+	ISSMBOOT();
+
+	/*Initialize environments: Petsc, MPI, etc...: */
+#ifdef _HAVE_PETSC_
+	int ierr=PetscInitialize(&argc,&argv,(char*)0,"");  
+	if(ierr) _error2_("Could not initialize Petsc");
+#else
+#ifdef _HAVE_MPI_
+	MPI_Init(&argc,&argv);
+#endif
+#endif
+
+	/*Size and rank: */
+#ifdef _HAVE_MPI_
+	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);  
+	MPI_Comm_size(MPI_COMM_WORLD,&num_procs); 
+#endif
+
+	/*First process inputs*/
+	_pprintLine_("");
+	_pprintLine_("Ice Sheet System Model (" << PACKAGE_NAME << ") version " << PACKAGE_VERSION);
+	_pprintLine_("(website: " << PACKAGE_URL << " contact: " << PACKAGE_BUGREPORT << ")");
+	_pprintLine_("");
+	ProcessArguments2(&binfilename,&outbinfilename,&lockfilename,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);
+
+	_pprintLine_("call computational core:");
+	pKrigingx(&predictions,&error,x,y,data,nobs,x_interp,y_interp,ninterp,options);
+
+	_pprintLine_("write results to disk:");
+	Results *results = new Results();
+	if(my_rank==0){
+		output_fid=pfopen(outbinfilename,"wb");
+		results->AddObject(new DoubleVecExternalResult(results->Size()+1,0,predictions,ninterp,1,0));
+		results->AddObject(new DoubleVecExternalResult(results->Size()+1,1,error,ninterp,1,0));
+		for(int i=0;i<results->Size();i++){
+			ExternalResult* result=(ExternalResult*)results->GetObjectByOffset(i);
+			result->WriteData(output_fid,1);
+		}
+		pfclose(output_fid,outbinfilename);
+	}
+
+	/*Close output and petsc options file and write lock file if requested*/
+	_pprintLine_("write lock file:");
+	WriteLockFile(lockfilename);
+
+	/*Free ressources */
+	xDelete<char>(lockfilename);
+	xDelete<char>(binfilename);
+	xDelete<char>(outbinfilename);
+	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;
+
+#ifdef _HAVE_PETSC_
+	_pprintLine_("closing MPI and Petsc");
+	PetscFinalize(); 
+#else
+#ifdef _HAVE_MPI_
+	_pprintLine_("closing MPI and Petsc");
+	MPI_Finalize();
+#endif
+#endif
+
+	/*end module: */
+	ISSMEND();
+
+	return 0; //unix success return;
+}
+
+void ProcessArguments2(char** pbinfilename,char** poutbinfilename,char** plockfilename,int argc,char **argv){
+
+	char *modelname      = NULL;
+	char *binfilename    = NULL;
+	char *outbinfilename = NULL;
+	char *lockfilename   = NULL;
+
+	if(argc<2)_error2_("Usage error: missing model name");
+	modelname=argv[2];
+	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;
+}
+
+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 dummy,M,N;
+	IoModel* iomodel = new IoModel();
+	iomodel->fid=fid;
+	iomodel->CheckEnumSync();
+	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/branches/trunk-jpl-damage/src/c/solutions/objectivefunction.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/objectivefunction.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/objectivefunction.cpp	(revision 12878)
@@ -3,5 +3,5 @@
  */ 
 
-/*include files: {{{1*/
+/*include files: {{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -11,5 +11,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
@@ -20,10 +20,10 @@
 /*}}}*/
 
-double objectivefunction(double search_scalar,OptArgs* optargs){
+IssmDouble objectivefunction(IssmDouble search_scalar,OptArgs* optargs){
 
 	int i;  
 	
 	/*output: */
-	double J;
+	IssmDouble J;
 	
 	/*parameters: */
@@ -49,5 +49,5 @@
 	}
 	else{
-		_error_("Solution %s not implemented yet",EnumToStringx(solution_type));
+		_error2_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
 	}
 
@@ -66,5 +66,5 @@
 	}
 	else{
-		_error_("Solution %s not implemented yet",EnumToStringx(solution_type));
+		_error2_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
 	}
 
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/prognostic_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/prognostic_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/prognostic_core.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -16,4 +16,5 @@
 	/*parameters: */
 	bool save_results;
+	bool issmbgradients,ispdd,isdelta18o;
 
 	/*activate formulation: */
@@ -22,10 +23,25 @@
 	/*recover parameters: */
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&issmbgradients,SurfaceforcingsIssmbgradientsEnum);
+	femmodel->parameters->FindParam(&ispdd,SurfaceforcingsIspddEnum);
+	femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
 
-	_printf_(VerboseSolution(),"   call computational core\n");
+	if(issmbgradients){
+	  _printf_(VerboseSolution(),"	call smb gradients module\n");
+	  SmbGradientsx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	}
+	if(ispdd){
+		if(isdelta18o){
+			if(VerboseSolution()) _pprintLine_("   call Delta18oParametrization module");
+			Delta18oParameterizationx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		} 
+		if(VerboseSolution()) _pprintLine_("   call positive degree day module");
+		PositiveDegreeDayx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	}
+	if(VerboseSolution()) _pprintLine_("   call computational core");
 	solver_linear(femmodel);
-		
+	
 	if(save_results){
-		_printf_(VerboseSolution(),"   saving results\n");
+		if(VerboseSolution()) _pprintLine_("   saving results");
 		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ThicknessEnum);
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/solutions.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/solutions.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/solutions.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define SOLUTIONS_H_
 
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../io/io.h"
 
@@ -18,5 +18,5 @@
 void diagnostic_core(FemModel* femmodel);
 void hydrology_core(FemModel* femmodel);
-void hydrology_core_step(FemModel* femmodel,int step, double time);
+void hydrology_core_step(FemModel* femmodel,int step, IssmDouble time);
 void thermal_core(FemModel* femmodel);
 void enthalpy_core(FemModel* femmodel);
@@ -30,18 +30,18 @@
 void steadystate_core(FemModel* femmodel);
 void transient_core(FemModel* femmodel);
-double objectivefunction(double search_scalar,OptArgs* optargs);
+IssmDouble objectivefunction(IssmDouble search_scalar,OptArgs* optargs);
 
 //convergence:
 void convergence(bool* pconverged, Matrix* K_ff,Vector* p_f,Vector* u_f,Vector* u_f_old,Parameters* parameters);
-bool controlconvergence(double J,double tol_cm);
+bool controlconvergence(IssmDouble J,IssmDouble tol_cm);
 bool steadystateconvergence(FemModel* femmodel);
 
 //optimization
-int GradJSearch(double* search_vector,FemModel* femmodel,int step);
+int GradJSearch(IssmDouble* search_vector,FemModel* femmodel,int step);
 
 //diverse
 void ProcessArguments(int* solution,char** pbinname,char** poutbinname,char** ppetscname,char** plockname,int argc,char **argv);
 void WriteLockFile(char* filename);
-void controlrestart(FemModel* femmodel,double* J);
+void controlrestart(FemModel* femmodel,IssmDouble* J);
 void ResetBoundaryConditions(FemModel* femmodel, int analysis_type);
 
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/steadystate_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/steadystate_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/steadystate_core.cpp	(revision 12878)
@@ -9,6 +9,7 @@
 #endif
 
+#include "../include/include.h"
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -16,5 +17,4 @@
 #include "./solutions.h"
 #include "../modules/modules.h"
-#include "../include/include.h"
 #include "../solvers/solvers.h"
 
@@ -43,5 +43,5 @@
 	for(;;){
 	
-		_printf_(VerboseSolution(),"%s%i\n","   computing temperature and velocity for step: ",step);
+		if(VerboseSolution()) _pprintLine_("   computing temperature and velocity for step: " << step);
 		#ifdef _HAVE_THERMAL_
 		if(isenthalpy==0){
@@ -52,20 +52,20 @@
 		}
 		#else
-		_error_("ISSM was not compiled with thermal capabilities. Exiting");
+		_error2_("ISSM was not compiled with thermal capabilities. Exiting");
 		#endif
 
-		_printf_(VerboseSolution(),"%s\n","   computing new velocity");
+		if(VerboseSolution()) _pprintLine_("   computing new velocity");
 		diagnostic_core(femmodel);
 
 		if (step>1){
-			_printf_(VerboseSolution(),"%s\n","   checking velocity, temperature and pressure convergence");
+			if(VerboseSolution()) _pprintLine_("   checking velocity, temperature and pressure convergence");
 			if(steadystateconvergence(femmodel)) break;
 		}
 		if(step>maxiter){
-			_printf_(VerboseSolution(),"%s%i%s\n","   maximum number steadystate iterations ",maxiter," reached");
+			if(VerboseSolution()) _pprintLine_("   maximum number steadystate iterations " << maxiter << " reached");
 			break;
 		}
 		
-		_printf_(VerboseSolution(),"%s\n","   saving velocity, temperature and pressure to check for convergence at next step");
+		if(VerboseSolution()) _pprintLine_("   saving velocity, temperature and pressure to check for convergence at next step");
 		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VxEnum,VxPicardEnum);
 		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VyEnum,VyPicardEnum);
@@ -79,5 +79,5 @@
 	
 	if(save_results){
-		_printf_(VerboseSolution(),"   saving results\n");
+		if(VerboseSolution()) _pprintLine_("   saving results");
 		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);
@@ -93,4 +93,4 @@
 
 	/*Free ressources:*/
-	xfree((void**)&requested_outputs);
+	xDelete<int>(requested_outputs);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/steadystateconvergence.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/steadystateconvergence.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/steadystateconvergence.cpp	(revision 12878)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../Container/Container.h"
@@ -28,5 +28,5 @@
 	int temperatureenums[2]={TemperatureEnum,TemperatureOldEnum};
 	int convergencecriterion[1]={RelativeEnum}; //criterions for convergence, RelativeEnum or AbsoluteEnum 
-	double convergencecriterionvalue[1]; //value of criterion to be respected
+	IssmDouble convergencecriterionvalue[1]; //value of criterion to be respected
 
 	/*retrieve parameters: */
Index: /issm/branches/trunk-jpl-damage/src/c/solutions/surfaceslope_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/surfaceslope_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/surfaceslope_core.cpp	(revision 12878)
@@ -5,5 +5,5 @@
 #include "./solutions.h"
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../io/io.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
@@ -19,5 +19,5 @@
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
 
-	_printf_(VerboseSolution(),"%s\n","computing slope...");
+	if(VerboseSolution()) _pprintLine_("computing slope...");
 
 	/*Call on core computations: */
@@ -28,5 +28,5 @@
 	
 	if(save_results){
-		_printf_(VerboseSolution(),"saving results:\n");
+		if(VerboseSolution()) _pprintLine_("saving results:");
 		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/branches/trunk-jpl-damage/src/c/solutions/thermal_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/thermal_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/thermal_core.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -16,5 +16,5 @@
 
 	/*intermediary*/
-	double melting_offset;
+	IssmDouble melting_offset;
 	bool   save_results;
 	bool   dakota_analysis  = false;
@@ -29,14 +29,14 @@
 	}
 
-	_printf_(VerboseSolution(),"   computing temperatures\n");
+	if(VerboseSolution()) _pprintLine_("   computing temperatures");
 	femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
 	solver_thermal_nonlinear(femmodel);
 
-	_printf_(VerboseSolution(),"   computing melting\n");
+	if(VerboseSolution()) _pprintLine_("   computing melting");
 	femmodel->SetCurrentConfiguration(MeltingAnalysisEnum);
 	solver_linear(femmodel);
 
 	if(save_results){
-		_printf_(VerboseSolution(),"   saving results\n");
+		if(VerboseSolution()) _pprintLine_("   saving results");
 		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/branches/trunk-jpl-damage/src/c/solutions/transient_core.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solutions/transient_core.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solutions/transient_core.cpp	(revision 12878)
@@ -10,5 +10,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -23,5 +23,5 @@
 
 	/*parameters: */
-	double starttime,finaltime,dt,yts;
+	IssmDouble starttime,finaltime,dt,yts;
 	bool   isdiagnostic,isprognostic,isthermal,isgroundingline,isenthalpy;
 	bool   save_results,dakota_analysis;
@@ -34,5 +34,5 @@
 	/*intermediary: */
 	int    step;
-	double time;
+	IssmDouble time;
 
 	//first recover parameters common to all solutions
@@ -86,5 +86,5 @@
 		femmodel->parameters->SetParam(step,StepEnum);
 
-		_printf_(VerboseSolution(),"iteration %i/%g  time [yr]: %-7.3g (time step: %.2g)\n",step,floor((finaltime-time)/dt)+step,time/yts,dt/yts);
+		if(VerboseSolution()) _pprintLine_("iteration " << step << "/" << floor((finaltime-time)/dt)+step << "  time [yr]: " << time/yts << " (time step: " << dt/yts << ")");
 		if(step%output_frequency==0 || time==finaltime)
 		 save_results=true;
@@ -94,5 +94,5 @@
 
 		if(isthermal && dim==3){
-			_printf_(VerboseSolution(),"   computing temperatures\n");
+			if(VerboseSolution()) _pprintLine_("   computing temperatures");
 			#ifdef _HAVE_THERMAL_
 			if(isenthalpy==0){
@@ -103,30 +103,30 @@
 			}
 			#else
-			_error_("ISSM was not compiled with thermal capabilities. Exiting");
+			_error2_("ISSM was not compiled with thermal capabilities. Exiting");
 			#endif
 		}
-
+		
 		if(isdiagnostic){
-			_printf_(VerboseSolution(),"   computing new velocity\n");
+			if(VerboseSolution()) _pprintLine_("   computing new velocity");
 			#ifdef _HAVE_DIAGNOSTIC_
 			diagnostic_core(femmodel);
 			#else
-			_error_("ISSM was not compiled with diagnostic capabilities. Exiting");
+			_error2_("ISSM was not compiled with diagnostic capabilities. Exiting");
 			#endif
 		}
 
 		if(isprognostic){
-			_printf_(VerboseSolution(),"   computing new thickness\n");
+			if(VerboseSolution()) _pprintLine_("   computing new thickness");
 			prognostic_core(femmodel);
-			_printf_(VerboseSolution(),"   updating vertices positions\n");
+			if(VerboseSolution()) _pprintLine_("   updating vertices positions");
 			UpdateVertexPositionsx(femmodel->elements, femmodel->nodes,femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters); 
 		}
 
 		if(isgroundingline){
-			_printf_(VerboseSolution(),"   computing new grounding line position\n");
+			if(VerboseSolution()) _pprintLine_("   computing new grounding line position");
 			#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");
+			_error2_("ISSM was not compiled with grounding line migration capabilities. Exiting");
 			#endif
 		}
@@ -134,5 +134,5 @@
 		/*unload results*/
 		if(save_results){
-			_printf_(VerboseSolution(),"   saving transient results\n");
+			if(VerboseSolution()) _pprintLine_("   saving transient results");
 			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);
@@ -141,5 +141,5 @@
 			RequestedOutputsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,requested_outputs,numoutputs);
 
-			_printf_(VerboseSolution(),"   saving temporary results\n");
+			if(VerboseSolution()) _pprintLine_("   saving temporary results");
 			OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
 		}
@@ -147,4 +147,4 @@
 
 	/*Free ressources:*/
-	xfree((void**)&requested_outputs);
+	xDelete<int>(requested_outputs);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/solvers/solver_adjoint_linear.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solvers/solver_adjoint_linear.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solvers/solver_adjoint_linear.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
 #include "../modules/modules.h"
Index: /issm/branches/trunk-jpl-damage/src/c/solvers/solver_linear.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solvers/solver_linear.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solvers/solver_linear.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
 #include "../modules/modules.h"
Index: /issm/branches/trunk-jpl-damage/src/c/solvers/solver_newton.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solvers/solver_newton.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solvers/solver_newton.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../io/io.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
@@ -17,5 +17,5 @@
 	int    num_unstable_constraints;
 	int    count;
-	double kmax;
+	IssmDouble kmax;
 	Matrix* Kff = NULL;
 	Matrix* Kfs    = NULL;
@@ -70,13 +70,13 @@
 			bool max_iteration_state=false;
 			int tempStep=1;
-			double tempTime=1.0;
+			IssmDouble tempTime=1.0;
 			femmodel->results->AddObject(new BoolExternalResult(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
 			break;
 		}
 		if(count>=max_nonlinear_iterations){
-			_printf_(true,"   maximum number of Newton iterations (%i) exceeded\n",max_nonlinear_iterations); 
+			_pprintLine_("   maximum number of Newton iterations (" << max_nonlinear_iterations << ") exceeded"); 
 			bool max_iteration_state=true;
 			int tempStep=1;
-			double tempTime=1.0;
+			IssmDouble tempTime=1.0;
 			femmodel->results->AddObject(new BoolExternalResult(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
 			break;
@@ -100,5 +100,5 @@
 	}
 
-	_printf_(VerboseConvergence(),"\n   total number of iterations: %i\n",count-1);
+	if(VerboseConvergence()) _pprintLine_("\n   total number of iterations: " << count-1);
 
 	/*clean-up*/
Index: /issm/branches/trunk-jpl-damage/src/c/solvers/solver_nonlinear.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solvers/solver_nonlinear.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solvers/solver_nonlinear.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../io/io.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
@@ -73,5 +73,5 @@
 
 		ConstraintsStatex(&constraints_converged, &num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,loads,femmodel->materials,femmodel->parameters);
-		_printf_(VerboseConvergence(),"   number of unstable constraints: %i\n",num_unstable_constraints);
+		if(VerboseConvergence()) _pprintLine_("   number of unstable constraints: " << num_unstable_constraints);
 
 		//rift convergence
@@ -88,10 +88,10 @@
 			bool max_iteration_state=false;
 			int tempStep=1;
-			double tempTime=1.0;
+			IssmDouble tempTime=1.0;
 			femmodel->results->AddObject(new BoolExternalResult(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
 			break;
 		}
 		if(count>=max_nonlinear_iterations){
-			_printf_(true,"   maximum number of nonlinear iterations (%i) exceeded\n",max_nonlinear_iterations); 
+			_pprintLine_("   maximum number of nonlinear iterations (" << max_nonlinear_iterations << ") exceeded"); 
 			converged=true;
 			InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
@@ -99,5 +99,5 @@
 			bool max_iteration_state=true;
 			int tempStep=1;
-			double tempTime=1.0;
+			IssmDouble tempTime=1.0;
 			femmodel->results->AddObject(new BoolExternalResult(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
 			break;
@@ -105,5 +105,5 @@
 	}
 
-	_printf_(VerboseConvergence(),"\n   total number of iterations: %i\n",count-1);
+	if(VerboseConvergence()) _pprintLine_("\n   total number of iterations: " << count-1);
 
 	/*clean-up*/
Index: /issm/branches/trunk-jpl-damage/src/c/solvers/solver_stokescoupling_nonlinear.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solvers/solver_stokescoupling_nonlinear.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solvers/solver_stokescoupling_nonlinear.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
 #include "../io/io.h"
@@ -91,5 +91,5 @@
 		if(converged==true)break;
 		if(count>=max_nonlinear_iterations){
-			_printf_(true,"   maximum number of iterations (%i) exceeded\n",max_nonlinear_iterations); 
+			_pprintLine_("   maximum number of iterations (" << max_nonlinear_iterations << ") exceeded"); 
 			break;
 		}
Index: /issm/branches/trunk-jpl-damage/src/c/solvers/solver_thermal_nonlinear.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solvers/solver_thermal_nonlinear.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solvers/solver_thermal_nonlinear.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 #include "../toolkits/toolkits.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../io/io.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
@@ -16,5 +16,5 @@
 	Vector* tf_old=NULL; 
 	Vector* ys=NULL; 
-	double melting_offset;
+	IssmDouble melting_offset;
 
 	/*intermediary: */
@@ -47,5 +47,5 @@
 	converged=false;
 
-	_printf_(VerboseSolution(),"%s\n","starting direct shooting method");
+	if(VerboseSolution()) _pprintLine_("starting direct shooting method");
 	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);
@@ -66,9 +66,9 @@
 
 		if (!converged){
-			_printf_(VerboseConvergence(),"%s%i\n","   #unstable constraints = ",num_unstable_constraints);
+			if(VerboseConvergence()) _pprintLine_("   #unstable constraints = " << num_unstable_constraints);
 			if (num_unstable_constraints <= thermal_penalty_threshold)converged=true;
 			if (count>=thermal_maxiter){
 				converged=true;
-				_printf_(true,"   maximum number of iterations (%i) exceeded\n",thermal_maxiter); 
+				_pprintLine_("   maximum number of iterations (" << thermal_maxiter << ") exceeded"); 
 			}
 		}
Index: /issm/branches/trunk-jpl-damage/src/c/solvers/solvers.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/solvers/solvers.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/solvers/solvers.h	(revision 12878)
@@ -6,5 +6,5 @@
 #define SOLVERS_H_
 
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../io/io.h"
 
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqMat.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqMat.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqMat.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 /*Headers:*/
-/*{{{1*/
+/*{{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -19,5 +19,5 @@
 
 /*SeqMat constructors and destructor*/
-/*FUNCTION SeqMat::SeqMat(){{{1*/
+/*FUNCTION SeqMat::SeqMat(){{{*/
 SeqMat::SeqMat(){
 
@@ -27,5 +27,5 @@
 }
 /*}}}*/
-/*FUNCTION SeqMat::SeqMat(int M,int N){{{1*/
+/*FUNCTION SeqMat::SeqMat(int M,int N){{{*/
 SeqMat::SeqMat(int pM,int pN){
 
@@ -33,18 +33,18 @@
 	this->N=pN;
 	this->matrix=NULL;
-	if(M*N) this->matrix=(double*)xcalloc(pM*pN,sizeof(double));
-}
-/*}}}*/
-/*FUNCTION SeqMat::SeqMat(int M,int N, double sparsity){{{1*/
-SeqMat::SeqMat(int pM,int pN, double sparsity){
-
-	this->M=pM;
-	this->N=pN;
-	this->matrix=NULL;
-	if(M*N) this->matrix=(double*)xcalloc(pM*pN,sizeof(double));
-}
-/*}}}*/
-/*FUNCTION SeqMat(double* serial_mat,int M,int N,double sparsity){{{1*/
-SeqMat::SeqMat(double* serial_mat,int pM,int pN,double sparsity){
+	if(M*N) this->matrix=xNewZeroInit<IssmDouble>(pM*pN);
+}
+/*}}}*/
+/*FUNCTION SeqMat::SeqMat(int M,int N, IssmDouble sparsity){{{*/
+SeqMat::SeqMat(int pM,int pN, IssmDouble sparsity){
+
+	this->M=pM;
+	this->N=pN;
+	this->matrix=NULL;
+	if(M*N) this->matrix=xNewZeroInit<IssmDouble>(pM*pN);
+}
+/*}}}*/
+/*FUNCTION SeqMat::SeqMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){{{*/
+SeqMat::SeqMat(IssmDouble* serial_mat,int pM,int pN,IssmDouble sparsity){
 
 	int i,j;
@@ -54,11 +54,11 @@
 	this->matrix=NULL;
 	if(M*N){
-		this->matrix=(double*)xcalloc(pM*pN,sizeof(double));
-		memcpy(this->matrix,serial_mat,pM*pN*sizeof(double));
-	}
-
-}
-/*}}}*/
-/*FUNCTION SeqMat::SeqMat(int M,int N, int connectivity, int numberofdofspernode){{{1*/
+		this->matrix=xNewZeroInit<IssmDouble>(pM*pN);
+		xMemCpy<IssmDouble>(this->matrix,serial_mat,pM*pN);
+	}
+
+}
+/*}}}*/
+/*FUNCTION SeqMat::SeqMat(int M,int N, int connectivity, int numberofdofspernode){{{*/
 SeqMat::SeqMat(int pM,int pN, int connectivity,int numberofdofspernode){
 
@@ -66,11 +66,11 @@
 	this->N=pN;
 	this->matrix=NULL;
-	if(M*N)this->matrix=(double*)xcalloc(pM*pN,sizeof(double));
-}
-/*}}}*/
-/*FUNCTION SeqMat::~SeqMat(){{{1*/
+	if(M*N) this->matrix=xNewZeroInit<IssmDouble>(pM*pN);
+}
+/*}}}*/
+/*FUNCTION SeqMat::~SeqMat(){{{*/
 SeqMat::~SeqMat(){
 
-	xfree((void**)&this->matrix);
+	xDelete<IssmDouble>(this->matrix);
 	M=0;
 	N=0;
@@ -79,18 +79,18 @@
 
 /*SeqMat specific routines: */
-/*FUNCTION SeqMat::Echo{{{1*/
+/*FUNCTION SeqMat::Echo{{{*/
 void SeqMat::Echo(void){
 
 	int i,j;
-	printf("SeqMat size %i-%i\n",this->M,this->N);
+	_printLine_("SeqMat size " << this->M << "-" << this->N);
 	for(i=0;i<M;i++){
 		for(j=0;j<N;j++){
-			printf("%g ",this->matrix[N*i+j]);
+			_printString_(this->matrix[N*i+j] << " ");
 		}
-		printf("\n");
-	}
-}
-/*}}}*/
-/*FUNCTION SeqMat::Assemble{{{1*/
+		_printLine_("");
+	}
+}
+/*}}}*/
+/*FUNCTION SeqMat::Assemble{{{*/
 void SeqMat::Assemble(void){
 		
@@ -99,9 +99,9 @@
 }
 /*}}}*/
-/*FUNCTION SeqMat::Norm{{{1*/
-double SeqMat::Norm(NormMode mode){
-
-	double norm;
-	double absolute;
+/*FUNCTION SeqMat::Norm{{{*/
+IssmDouble SeqMat::Norm(NormMode mode){
+
+	IssmDouble norm;
+	IssmDouble absolute;
 	int i,j;
 
@@ -119,10 +119,10 @@
 			break;
 		default:
-			_error_("unknown norm !");
-			break;
-	}
-}
-/*}}}*/
-/*FUNCTION SeqMat::GetSize{{{1*/
+			_error2_("unknown norm !");
+			break;
+	}
+}
+/*}}}*/
+/*FUNCTION SeqMat::GetSize{{{*/
 void SeqMat::GetSize(int* pM,int* pN){
 
@@ -132,5 +132,5 @@
 }
 /*}}}*/
-/*FUNCTION SeqMat::GetLocalSize{{{1*/
+/*FUNCTION SeqMat::GetLocalSize{{{*/
 void SeqMat::GetLocalSize(int* pM,int* pN){
 	
@@ -140,16 +140,16 @@
 }
 /*}}}*/
-/*FUNCTION SeqMat::MatMult{{{1*/
+/*FUNCTION SeqMat::MatMult{{{*/
 void SeqMat::MatMult(SeqVec* X,SeqVec* AX){
 
 	int i,j;
 	int XM,AXM;
-	double dummy;
+	IssmDouble 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!");
+	if(M!=AXM)_error2_("A and AX should have the same number of rows!");
+	if(N!=XM)_error2_("A and X should have the same number of columns!");
 
 	for(i=0;i<M;i++){
@@ -163,8 +163,8 @@
 }
 /*}}}*/
-/*FUNCTION SeqMat::Duplicate{{{1*/
+/*FUNCTION SeqMat::Duplicate{{{*/
 SeqMat* SeqMat::Duplicate(void){
 
-	double dummy=0;
+	IssmDouble dummy=0;
 
 	return new SeqMat(this->matrix,this->M,this->N,dummy);
@@ -172,12 +172,12 @@
 }
 /*}}}*/
-/*FUNCTION SeqMat::ToSerial{{{1*/
-double* SeqMat::ToSerial(void){
-
-	double* buffer=NULL;
+/*FUNCTION SeqMat::ToSerial{{{*/
+IssmDouble* SeqMat::ToSerial(void){
+
+	IssmDouble* buffer=NULL;
 
 	if(this->M*this->N){
-		buffer=(double*)xmalloc(this->M*this->N*sizeof(double));
-		memcpy(buffer,this->matrix,this->M*this->N*sizeof(double));
+		buffer=xNew<IssmDouble>(this->M*this->N);
+		xMemCpy<IssmDouble>(buffer,this->matrix,this->M*this->N);
 	}
 	return buffer;
@@ -185,6 +185,6 @@
 }
 /*}}}*/
-/*FUNCTION SeqMat::SetValues{{{1*/
-void SeqMat::SetValues(int m,int* idxm,int n,int* idxn,double* values,InsMode mode){
+/*FUNCTION SeqMat::SetValues{{{*/
+void SeqMat::SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode){
 	
 	int i,j;
@@ -197,11 +197,11 @@
 			break;
 		default:
-			_error_("unknown insert mode!");
-			break;
-	}
-
-}
-/*}}}*/
-/*FUNCTION SeqMat::Convert{{{1*/
+			_error2_("unknown insert mode!");
+			break;
+	}
+
+}
+/*}}}*/
+/*FUNCTION SeqMat::Convert{{{*/
 void SeqMat::Convert(MatrixType type){
 
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqMat.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqMat.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqMat.h	(revision 12878)
@@ -1,4 +1,4 @@
 /*!\file:  SeqMat.h
- * \brief wrapper to SeqMat objects, which are just wrappers to a simple double* buffer.
+ * \brief wrapper to SeqMat objects, which are just wrappers to a simple IssmDouble* buffer.
  */ 
 
@@ -7,5 +7,5 @@
 
 /*Headers:*/
-/*{{{1*/
+/*{{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -24,24 +24,24 @@
 	
 		int M,N; 
-		double* matrix; 
+		IssmDouble* matrix; 
 
-		/*SeqMat constructors, destructors {{{1*/
+		/*SeqMat constructors, destructors {{{*/
 		SeqMat();
 		SeqMat(int M,int N);
-		SeqMat(int M,int N,double sparsity);
-		SeqMat(double* serial_mat,int M,int N,double sparsity);
+		SeqMat(int M,int N,IssmDouble sparsity);
+		SeqMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity);
 		SeqMat(int M,int N,int connectivity,int numberofdofspernode);
 		~SeqMat();
 		/*}}}*/
-		/*SeqMat specific routines {{{1*/
+		/*SeqMat specific routines {{{*/
 		void Echo(void);
 		void Assemble(void);
-		double Norm(NormMode norm_type);
+		IssmDouble Norm(NormMode norm_type);
 		void GetSize(int* pM,int* pN);
 		void GetLocalSize(int* pM,int* pN);
 		void MatMult(SeqVec* X,SeqVec* AX);
 		SeqMat* Duplicate(void);
-		double* ToSerial(void);
-		void SetValues(int m,int* idxm,int n,int* idxn,double* values,InsMode mode);
+		IssmDouble* ToSerial(void);
+		void SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode);
 		void Convert(MatrixType type);
 		/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqVec.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqVec.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqVec.cpp	(revision 12878)
@@ -4,5 +4,5 @@
 
 /*Headers:*/
-/*{{{1*/
+/*{{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -19,5 +19,5 @@
 
 /*SeqVec constructors and destructor*/
-/*FUNCTION SeqVec::SeqVec(){{{1*/
+/*FUNCTION SeqVec::SeqVec(){{{*/
 SeqVec::SeqVec(){
 
@@ -26,14 +26,14 @@
 }
 /*}}}*/
-/*FUNCTION SeqVec::SeqVec(int M,bool fromlocalsize){{{1*/
+/*FUNCTION SeqVec::SeqVec(int M,bool fromlocalsize){{{*/
 SeqVec::SeqVec(int pM,bool fromlocalsize){
 
 	this->M=pM;
 	this->vector=NULL;
-	if(this->M) this->vector=(double*)xcalloc(pM,sizeof(double));
-}
-/*}}}*/
-/*FUNCTION SeqVec::SeqVec(double* serial_vec,int M){{{1*/
-SeqVec::SeqVec(double* buffer,int pM){
+	if(this->M) this->vector=xNewZeroInit<IssmDouble>(pM);
+}
+/*}}}*/
+/*FUNCTION SeqVec::SeqVec(IssmDouble* serial_vec,int M){{{*/
+SeqVec::SeqVec(IssmDouble* buffer,int pM){
 
 	int i,j;
@@ -42,12 +42,12 @@
 	this->vector=NULL;
 	if(this->M){
-		this->vector=(double*)xcalloc(pM,sizeof(double));
-		memcpy(this->vector,buffer,pM*sizeof(double));
-	}
-}
-/*}}}*/
-		/*FUNCTION SeqVec::~SeqVec(){{{1*/
+		this->vector=xNew<IssmDouble>(pM);
+		xMemCpy<IssmDouble>(this->vector,buffer,pM);
+	}
+}
+/*}}}*/
+		/*FUNCTION SeqVec::~SeqVec(){{{*/
 SeqVec::~SeqVec(){
-	xfree((void**)&this->vector);
+	xDelete<IssmDouble>(this->vector);
 	M=0;
 }
@@ -55,16 +55,16 @@
 
 /*SeqVec specific routines: */
-/*FUNCTION SeqVec::Echo{{{1*/
+/*FUNCTION SeqVec::Echo{{{*/
 void SeqVec::Echo(void){
 
 	int i;
-	printf("SeqVec size %i\n",this->M);
+	_printLine_("SeqVec size " << this->M);
 	for(i=0;i<M;i++){
-		printf("%g\n ",vector[i]);
-	}
-}
-/*}}}*/
-
-/*FUNCTION SeqVec::Assemble{{{1*/
+		_printString_(vector[i] << "\n ");
+	}
+}
+/*}}}*/
+
+/*FUNCTION SeqVec::Assemble{{{*/
 void SeqVec::Assemble(void){
 		
@@ -73,6 +73,6 @@
 }
 /*}}}*/
-/*FUNCTION SeqVec::SetValues{{{1*/
-void SeqVec::SetValues(int ssize, int* list, double* values, InsMode mode){
+/*FUNCTION SeqVec::SetValues{{{*/
+void SeqVec::SetValues(int ssize, int* list, IssmDouble* values, InsMode mode){
 	
 	int i;
@@ -85,12 +85,12 @@
 			break;
 		default:
-			_error_("unknown insert mode!");
-			break;
-	}
-
-}
-/*}}}*/
-/*FUNCTION SeqVec::SetValue{{{1*/
-void SeqVec::SetValue(int dof, double value, InsMode mode){
+			_error2_("unknown insert mode!");
+			break;
+	}
+
+}
+/*}}}*/
+/*FUNCTION SeqVec::SetValue{{{*/
+void SeqVec::SetValue(int dof, IssmDouble value, InsMode mode){
 
 	switch(mode){
@@ -102,11 +102,11 @@
 			break;
 		default:
-			_error_("unknown insert mode!");
-			break;
-	}
-}
-/*}}}*/
-/*FUNCTION SeqVec::GetValue{{{1*/
-void SeqVec::GetValue(double* pvalue,int dof){
+			_error2_("unknown insert mode!");
+			break;
+	}
+}
+/*}}}*/
+/*FUNCTION SeqVec::GetValue{{{*/
+void SeqVec::GetValue(IssmDouble* pvalue,int dof){
 
 	*pvalue=this->vector[dof];
@@ -115,5 +115,5 @@
 /*}}}*/
 		
-/*FUNCTION SeqVec::GetSize{{{1*/
+/*FUNCTION SeqVec::GetSize{{{*/
 void SeqVec::GetSize(int* pM){
 
@@ -122,5 +122,5 @@
 }
 /*}}}*/
-/*FUNCTION SeqVec::GetLocalSize{{{1*/
+/*FUNCTION SeqVec::GetLocalSize{{{*/
 void SeqVec::GetLocalSize(int* pM){
 	
@@ -129,5 +129,5 @@
 }
 /*}}}*/
-/*FUNCTION SeqVec::Duplicate{{{1*/
+/*FUNCTION SeqVec::Duplicate{{{*/
 SeqVec* SeqVec::Duplicate(void){
 	
@@ -136,6 +136,6 @@
 }
 /*}}}*/
-/*FUNCTION SeqVec::Set{{{1*/
-void SeqVec::Set(double value){
+/*FUNCTION SeqVec::Set{{{*/
+void SeqVec::Set(IssmDouble value){
 
 	int i;
@@ -144,6 +144,6 @@
 }
 /*}}}*/
-/*FUNCTION SeqVec::AXPY{{{1*/
-void SeqVec::AXPY(SeqVec* X, double a){
+/*FUNCTION SeqVec::AXPY{{{*/
+void SeqVec::AXPY(SeqVec* X, IssmDouble a){
 
 	int i;
@@ -154,6 +154,6 @@
 }
 /*}}}*/
-/*FUNCTION SeqVec::AYPX{{{1*/
-void SeqVec::AYPX(SeqVec* X, double a){
+/*FUNCTION SeqVec::AYPX{{{*/
+void SeqVec::AYPX(SeqVec* X, IssmDouble a){
 	
 	int i;
@@ -164,12 +164,12 @@
 }
 /*}}}*/
-/*FUNCTION SeqVec::ToMPISerial{{{1*/
-double* SeqVec::ToMPISerial(void){
-
-	double* buffer=NULL;
+/*FUNCTION SeqVec::ToMPISerial{{{*/
+IssmDouble* SeqVec::ToMPISerial(void){
+
+	IssmDouble* buffer=NULL;
 
 	if(this->M){
-		buffer=(double*)xmalloc(this->M*sizeof(double));
-		memcpy(buffer,this->vector,this->M*sizeof(double));
+		buffer=xNew<IssmDouble>(this->M);
+		xMemCpy<IssmDouble>(buffer,this->vector,this->M);
 	}
 	return buffer;
@@ -177,5 +177,5 @@
 }
 /*}}}*/
-/*FUNCTION SeqVec::Copy{{{1*/
+/*FUNCTION SeqVec::Copy{{{*/
 void SeqVec::Copy(SeqVec* to){
 
@@ -187,8 +187,8 @@
 }
 /*}}}*/
-/*FUNCTION SeqVec::Norm{{{1*/
-double SeqVec::Norm(NormMode mode){
-
-	double norm;
+/*FUNCTION SeqVec::Norm{{{*/
+IssmDouble SeqVec::Norm(NormMode mode){
+
+	IssmDouble norm;
 	int i;
 
@@ -204,11 +204,11 @@
 			break;
 		default:
-			_error_("unknown norm !");
-			break;
-	}
-}
-/*}}}*/
-/*FUNCTION SeqVec::Scale{{{1*/
-void SeqVec::Scale(double scale_factor){
+			_error2_("unknown norm !");
+			break;
+	}
+}
+/*}}}*/
+/*FUNCTION SeqVec::Scale{{{*/
+void SeqVec::Scale(IssmDouble scale_factor){
 
 	int i;
@@ -217,10 +217,10 @@
 }
 /*}}}*/
-/*FUNCTION SeqVec::Dot{{{1*/
-double SeqVec::Dot(SeqVec* input){
-
-	int i;
-
-	double dot=0;
+/*FUNCTION SeqVec::Dot{{{*/
+IssmDouble SeqVec::Dot(SeqVec* input){
+
+	int i;
+
+	IssmDouble dot=0;
 	for(i=0;i<this->M;i++)dot+=this->vector[i]*input->vector[i];
 	return dot;
@@ -228,5 +228,5 @@
 }
 /*}}}*/
-/*FUNCTION SeqVec::PointwiseDivide{{{1*/
+/*FUNCTION SeqVec::PointwiseDivide{{{*/
 void SeqVec::PointwiseDivide(SeqVec* x,SeqVec* y){
 
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqVec.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqVec.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/SeqVec.h	(revision 12878)
@@ -1,4 +1,4 @@
 /*!\file:  SeqVec.h
- * \brief wrapper to our SeqVec object, which is just a wrapper to a double* 
+ * \brief wrapper to our SeqVec object, which is just a wrapper to a IssmDouble* 
  */ 
 
@@ -7,5 +7,5 @@
 
 /*Headers:*/
-/*{{{1*/
+/*{{{*/
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -22,31 +22,31 @@
 	public:
 	
-		double* vector;
+		IssmDouble* vector;
 		int M;
 
-		/*SeqVec constructors, destructors {{{1*/
+		/*SeqVec constructors, destructors {{{*/
 		SeqVec();
 		SeqVec(int M,bool fromlocalsize=false);
-		SeqVec(double* buffer, int M);
+		SeqVec(IssmDouble* buffer, int M);
 		~SeqVec();
 		/*}}}*/
-		/*SeqVec specific routines {{{1*/
+		/*SeqVec specific routines {{{*/
 		void Echo(void);
 		void Assemble(void);
-		void SetValues(int ssize, int* list, double* values, InsMode mode);
-		void SetValue(int dof, double value, InsMode  mode);
-		void GetValue(double* pvalue, int dof);
+		void SetValues(int ssize, int* list, IssmDouble* values, InsMode mode);
+		void SetValue(int dof, IssmDouble value, InsMode  mode);
+		void GetValue(IssmDouble* pvalue, int dof);
 		void GetSize(int* pM);
 		void GetLocalSize(int* pM);
 		SeqVec* Duplicate(void);
-		void Set(double value);
-		void AXPY(SeqVec* X, double a);
-		void AYPX(SeqVec* X, double a);
-		double* ToMPISerial(void);
+		void Set(IssmDouble value);
+		void AXPY(SeqVec* X, IssmDouble a);
+		void AYPX(SeqVec* X, IssmDouble a);
+		IssmDouble* ToMPISerial(void);
 		void Copy(SeqVec* to);
-		double Norm(NormMode norm_type);
-		void Scale(double scale_factor);
+		IssmDouble Norm(NormMode norm_type);
+		void Scale(IssmDouble scale_factor);
 		void PointwiseDivide(SeqVec* x,SeqVec* y);
-		double Dot(SeqVec* vector);
+		IssmDouble Dot(SeqVec* vector);
 		/*}}}*/
 };
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/issmtoolkit.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/issmtoolkit.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/issm/issmtoolkit.h	(revision 12878)
@@ -6,4 +6,6 @@
 #define _ISSM_TOOLKIT_H_
 
+#include "../../include/include.h"
+
 #include "./SeqMat.h"
 #include "./SeqVec.h"
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp	(revision 12878)
@@ -13,5 +13,5 @@
 	METIS_PartMeshNodal(pnumberofelements,pnumberofnodes, index, petype, pnumflag, pnum_procs, pedgecut, epart, npart); 
 	#elif _METIS_VERSION_ == 5
-	/*This interface is heavily changed. More options, different way of meshing, etc ...: */ 
+	/*This interface is heavily changed. More options, different ways of meshing, etc ...: */ 
 	int i;
 
@@ -21,6 +21,4 @@
 	idx_t  k=0;
 	real_t* tpwgts=NULL;
-
-
 
 	/*setup options: */
@@ -40,7 +38,6 @@
 	options[METIS_OPTION_NCUTS]   = 1;
 
-
 	/*create eptr: */
-	eptr=(idx_t*)xmalloc((*pnumberofelements+1)*sizeof(idx_t));
+	eptr=xNew<idx_t>((*pnumberofelements+1));
 	eptr[0]=0;
 	for(i=0;i<*pnumberofelements;i++){
@@ -49,19 +46,19 @@
 	}
 
-
 	/*create tpwgts: */
-	tpwgts=(real_t*)xmalloc(*pnum_procs*sizeof(real_t));
+	tpwgts=xNew<real_t>(*pnum_procs);
 	for(i=0;i<*pnum_procs;i++){
 		tpwgts[i]=1.0/(*pnum_procs);
 	}
 
+	METIS_PartMeshNodal(pnumberofelements,pnumberofnodes, eptr, index,
+			NULL, NULL, pnum_procs, tpwgts, options, &objval,epart, npart);
 
-	METIS_PartMeshNodal(pnumberofelements,pnumberofnodes, eptr, index,
-			NULL, NULL, pnum_procs, tpwgts, options, &objval,
-			epart, npart);
-	
+	/*clean-up*/
+	xDelete<idx_t>(eptr);
+	xDelete<real_t>(tpwgts);
 
 	#else
-	_error_("METIS version not supported yet");
+	_error2_("METIS version not supported yet");
 	#endif
 }
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/mpi/patches/DetermineLocalSize.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/mpi/patches/DetermineLocalSize.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/mpi/patches/DetermineLocalSize.cpp	(revision 12878)
@@ -5,6 +5,4 @@
 #include <stdio.h>
 #include <math.h>
-
-
 #include "../../../shared/shared.h"
 
@@ -24,8 +22,7 @@
 	
 	/*We are  not bound by any library, just use what seems most logical*/
-	num_local_rows=(int*)xmalloc(num_procs*sizeof(int));    
+	num_local_rows=xNew<int>(num_procs);    
 
 	for (i=0;i<num_procs;i++){
-
 		/*Here, we use floor. We under distribute rows. The rows 
 		  left  are then redistributed, therefore resulting in a 
@@ -39,9 +36,8 @@
 		num_local_rows[i]++;
 	}
-
 	local_size=num_local_rows[my_rank];
 	
 	/*free ressources: */
-	xfree((void**)&num_local_rows);
+	xDelete<int>(num_local_rows);
 
 	/*return size: */
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/mpi/patches/MPI_Boundariesfromrange.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/mpi/patches/MPI_Boundariesfromrange.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/mpi/patches/MPI_Boundariesfromrange.cpp	(revision 12878)
@@ -20,7 +20,6 @@
 
 	/*Gather all range values into allranges, for all nodes*/
-	allranges=(int*)xmalloc(num_procs*sizeof(int));
+	allranges=xNew<int>(num_procs);
 	MPI_Allgather(&range,1,MPI_INT,allranges,1,MPI_INT,MPI_COMM_WORLD);
-
 
 	/*From all ranges, get lower row and upper row*/
@@ -31,12 +30,9 @@
 		upper_row=upper_row+allranges[i];
 	}
-	
-	/*free: */
-	xfree((void**)&allranges);
 
 	/*Assign output pointers: */
+	xDelete<int>(allranges);
 	*plower_row=lower_row;
 	*pupper_row=upper_row;
-
 	return 1;
 }
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/PetscMat.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/PetscMat.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/PetscMat.cpp	(revision 12878)
@@ -0,0 +1,170 @@
+/*!\file PetscMat.cpp
+ * \brief: implementation of the PetscMat 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 "../petscincludes.h"
+#include "../../../shared/shared.h"
+
+/*}}}*/
+
+/*PetscMat constructors and destructor*/
+/*FUNCTION PetscMat::PetscMat(){{{*/
+PetscMat::PetscMat(){
+	this->matrix=NULL;
+	#ifdef _HAVE_ADOLC_
+	this->amatrix=NULL;
+	#endif
+
+}
+/*}}}*/
+/*FUNCTION PetscMat::PetscMat(int M,int N){{{*/
+PetscMat::PetscMat(int M,int N){
+
+	this->matrix=NewMat(M,N);
+}
+/*}}}*/
+/*FUNCTION PetscMat::PetscMat(int M,int N, IssmDouble sparsity){{{*/
+PetscMat::PetscMat(int M,int N, IssmDouble sparsity){
+
+	this->matrix=NewMat(M,N,sparsity);
+}
+/*}}}*/
+/*FUNCTION PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){{{*/
+PetscMat::PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){
+
+	int     i;
+	int* idxm=NULL;
+	int* idxn=NULL;
+	
+	if(M)idxm=xNew<int>(M);
+	if(N)idxn=xNew<int>(N);
+
+	for(i=0;i<M;i++)idxm[i]=i;
+	for(i=0;i<N;i++)idxn[i]=i;
+
+
+	this->matrix=NewMat(M,N,sparsity);
+	MatSetValues(this->matrix,M,idxm,N,idxn,serial_mat,INSERT_VALUES);
+	MatAssemblyBegin(this->matrix,MAT_FINAL_ASSEMBLY);
+	MatAssemblyEnd(this->matrix,MAT_FINAL_ASSEMBLY);
+
+	xDelete<int>(idxm);
+	xDelete<int>(idxn);
+
+}
+/*}}}*/
+/*FUNCTION PetscMat::PetscMat(int M,int N, int connectivity, int numberofdofspernode){{{*/
+PetscMat::PetscMat(int M,int N, int connectivity,int numberofdofspernode){
+	
+	this->matrix=NewMat(M,N,connectivity,numberofdofspernode);
+
+}
+/*}}}*/
+/*FUNCTION PetscMat::~PetscMat(){{{*/
+PetscMat::~PetscMat(){
+	MatFree(&this->matrix);
+}
+/*}}}*/
+
+/*PetscMat specific routines: */
+/*FUNCTION PetscMat::Echo{{{*/
+void PetscMat::Echo(void){
+
+	MatView(this->matrix,PETSC_VIEWER_STDOUT_WORLD);
+}
+/*}}}*/
+/*FUNCTION PetscMat::Assemble{{{*/
+void PetscMat::Assemble(void){
+
+	_assert_(this->matrix);
+	MatAssemblyBegin(this->matrix,MAT_FINAL_ASSEMBLY);
+	MatAssemblyEnd(this->matrix,MAT_FINAL_ASSEMBLY);
+	#if _PETSC_MAJOR_ == 2 
+		MatCompress(this->matrix);
+	#endif
+
+}
+/*}}}*/
+/*FUNCTION PetscMat::Norm{{{*/
+IssmDouble PetscMat::Norm(NormMode mode){
+
+
+	IssmDouble norm=0;
+	_assert_(this->matrix);
+	MatNorm(this->matrix,ISSMToPetscNormMode(mode),&norm);
+	
+	return norm;
+
+}
+/*}}}*/
+/*FUNCTION PetscMat::GetSize{{{*/
+void PetscMat::GetSize(int* pM,int* pN){
+
+	_assert_(this->matrix);
+	MatGetSize(this->matrix,pM,pN);
+}
+/*}}}*/
+/*FUNCTION PetscMat::GetLocalSize{{{*/
+void PetscMat::GetLocalSize(int* pM,int* pN){
+
+	_assert_(this->matrix);
+	MatGetLocalSize(this->matrix,pM,pN);
+
+}
+/*}}}*/
+/*FUNCTION PetscMat::MatMult{{{*/
+void PetscMat::MatMult(PetscVec* X,PetscVec* AX){
+
+	_assert_(this->matrix);
+	_assert_(X->vector);
+	MatMultPatch(this->matrix,X->vector,AX->vector);
+
+}
+/*}}}*/
+/*FUNCTION PetscMat::Duplicate{{{*/
+PetscMat* PetscMat::Duplicate(void){
+
+	PetscMat* output=NULL;
+
+	output=new PetscMat();
+	_assert_(this->matrix);
+	MatDuplicate(this->matrix,MAT_COPY_VALUES,&output->matrix);
+
+	return output;
+
+}
+/*}}}*/
+/*FUNCTION PetscMat::ToSerial{{{*/
+IssmDouble* PetscMat::ToSerial(void){
+
+	 IssmDouble* output=NULL;
+
+	 MatToSerial(&output,this->matrix);
+	 return output;
+
+}
+/*}}}*/
+/*FUNCTION PetscMat::SetValues{{{*/
+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));
+
+}
+/*}}}*/
+/*FUNCTION PetscMat::Convert{{{*/
+void PetscMat::Convert(MatrixType type){
+
+	MatConvert(this->matrix,ISSMToPetscMatrixType(type),MAT_REUSE_MATRIX,&this->matrix);
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/PetscMat.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/PetscMat.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/PetscMat.h	(revision 12878)
@@ -0,0 +1,56 @@
+/*!\file:  PetscMat.h
+ * \brief wrapper to our own PetscMat object, which is needed to add AD capabilities (using ADOLC) 
+ * to a C-coded Petsc API. We are just wrapping the Petsc objects into C++ equivalent, so that 
+ * later, we can map all of the Petsc routines into Adolc equivalents.
+ */ 
+
+#ifndef _PETSCMAT_H_
+#define _PETSCMAT_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"
+#include "../../../include/include.h"
+
+/*}}}*/
+class PetscVec;
+
+class PetscMat{
+
+	public:
+		Mat matrix;
+
+		#ifdef _HAVE_ADOLC_
+		IssmDouble* amatrix;
+		#endif
+
+		/*PetscMat constructors, destructors {{{*/
+		PetscMat();
+		PetscMat(int M,int N);
+		PetscMat(int M,int N,IssmDouble sparsity);
+		PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity);
+		PetscMat(int M,int N,int connectivity,int numberofdofspernode);
+		~PetscMat();
+		/*}}}*/
+		/*PetscMat specific routines {{{*/
+		void Echo(void);
+		void Assemble(void);
+		IssmDouble Norm(NormMode norm_type);
+		void GetSize(int* pM,int* pN);
+		void GetLocalSize(int* pM,int* pN);
+		void MatMult(PetscVec* X,PetscVec* AX);
+		PetscMat* Duplicate(void);
+		IssmDouble* ToSerial(void);
+		void SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode);
+		void Convert(MatrixType type);
+		/*}}}*/
+
+};
+		
+#endif //#ifndef _PETSCMAT_H_
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/PetscVec.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/PetscVec.cpp	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/PetscVec.cpp	(revision 12878)
@@ -0,0 +1,216 @@
+/*!\file PetscVec.cpp
+ * \brief: implementation of the PetscVec 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 "../petscincludes.h"
+#include "../../../shared/shared.h"
+
+/*}}}*/
+
+/*PetscVec constructors and destructor*/
+/*FUNCTION PetscVec::PetscVec(){{{*/
+PetscVec::PetscVec(){
+	this->vector=NULL;
+	#ifdef _HAVE_ADOLC_
+	this->avector=NULL;
+	#endif
+}
+/*}}}*/
+/*FUNCTION PetscVec::PetscVec(int M,bool fromlocalsize){{{*/
+PetscVec::PetscVec(int M,bool fromlocalsize){
+	
+	this->vector=NewVec(M,fromlocalsize);
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::PetscVec(Vec petsc_vec){{{*/
+PetscVec::PetscVec(Vec petsc_vec){
+
+	if(petsc_vec==NULL){
+		this->vector=NewVec(0);
+	}
+	else{
+		/*copy vector*/
+		VecDuplicate(petsc_vec,&this->vector);
+		VecCopy(petsc_vec,this->vector);
+	}
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::PetscVec(IssmDouble* serial_vec,int M){{{*/
+PetscVec::PetscVec(IssmDouble* serial_vec,int M){
+
+	int* idxm=NULL;
+	if(M)idxm=xNew<int>(M);
+	for(int i=0;i<M;i++) idxm[i]=i;
+
+	this->vector=NewVec(M);
+	VecSetValues(this->vector,M,idxm,serial_vec,INSERT_VALUES);
+	VecAssemblyBegin(this->vector);
+	VecAssemblyEnd(this->vector);
+
+	xDelete<int>(idxm);
+}
+/*}}}*/
+/*FUNCTION PetscVec::~PetscVec(){{{*/
+PetscVec::~PetscVec(){
+    VecFree(&this->vector);
+}
+/*}}}*/
+
+/*PetscVec specific routines: */
+/*FUNCTION PetscVec::Echo{{{*/
+void PetscVec::Echo(void){
+
+	_assert_(this->vector);
+	VecView(this->vector,PETSC_VIEWER_STDOUT_WORLD);
+}
+/*}}}*/
+/*FUNCTION PetscVec::Assemble{{{*/
+void PetscVec::Assemble(void){
+		
+	_assert_(this->vector);
+	VecAssemblyBegin(this->vector); 
+	VecAssemblyEnd(this->vector);
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::SetValues{{{*/
+void PetscVec::SetValues(int ssize, int* list, IssmDouble* values, InsMode mode){
+	
+	_assert_(this->vector);
+	VecSetValues(this->vector,ssize,list,values,ISSMToPetscInsertMode(mode));
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::SetValue{{{*/
+void PetscVec::SetValue(int dof, IssmDouble value, InsMode mode){
+
+	_assert_(this->vector);
+	VecSetValues(this->vector,1,&dof,&value,ISSMToPetscInsertMode(mode));
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::GetValue{{{*/
+void PetscVec::GetValue(IssmDouble* pvalue,int dof){
+
+	_assert_(this->vector);
+	VecGetValues(this->vector,1,&dof,pvalue);
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::GetSize{{{*/
+void PetscVec::GetSize(int* pM){
+
+	_assert_(this->vector);
+	VecGetSize(this->vector,pM);
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::GetLocalSize{{{*/
+void PetscVec::GetLocalSize(int* pM){
+
+	_assert_(this->vector);
+	VecGetLocalSize(this->vector,pM);
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::Duplicate{{{*/
+PetscVec* PetscVec::Duplicate(void){
+	
+	PetscVec* output=NULL;
+	_assert_(this->vector);
+	Vec vec_output=NULL;
+	VecDuplicate(this->vector,&vec_output);
+	output=new PetscVec(vec_output);
+	VecFree(&vec_output);
+
+	return output;
+}
+/*}}}*/
+/*FUNCTION PetscVec::Set{{{*/
+void PetscVec::Set(IssmDouble value){
+
+	_assert_(this->vector);
+	VecSet(this->vector,value);
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::AXPY{{{*/
+void PetscVec::AXPY(PetscVec* X, IssmDouble a){
+
+	_assert_(this->vector);
+	VecAXPY(this->vector,a,X->vector);
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::AYPX{{{*/
+void PetscVec::AYPX(PetscVec* X, IssmDouble a){
+
+	_assert_(this->vector);
+	VecAYPX(this->vector,a,X->vector);
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::ToMPISerial{{{*/
+IssmDouble* PetscVec::ToMPISerial(void){
+	
+	IssmDouble* vec_serial=NULL;
+	VecToMPISerial(&vec_serial, this->vector);
+	return vec_serial;
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::Copy{{{*/
+void PetscVec::Copy(PetscVec* to){
+
+	if(this->vector) VecCopy(this->vector,to->vector);
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::Norm{{{*/
+IssmDouble PetscVec::Norm(NormMode mode){
+
+	IssmDouble norm=0;
+	_assert_(this->vector);
+	VecNorm(this->vector,ISSMToPetscNormMode(mode),&norm);
+	return norm;
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::Scale{{{*/
+void PetscVec::Scale(IssmDouble scale_factor){
+
+	_assert_(this->vector);
+	VecScale(this->vector,scale_factor); 
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::Dot{{{*/
+IssmDouble PetscVec::Dot(PetscVec* input){
+
+	IssmDouble dot;
+	_assert_(this->vector);
+	VecDot(this->vector,input->vector,&dot);
+	return dot;
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::PointwiseDivide{{{*/
+void PetscVec::PointwiseDivide(PetscVec* x,PetscVec* y){
+
+	_assert_(this->vector);
+	VecPointwiseDivide(this->vector,x->vector,y->vector);
+
+}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/PetscVec.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/PetscVec.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/PetscVec.h	(revision 12878)
@@ -0,0 +1,62 @@
+/*!\file:  PetscVec.h
+ * \brief wrapper to our own PetscVec object, which is needed to add AD capabilities (using ADOLC) 
+ * to a C-coded Petsc API. We are just wrapping the Petsc objects into C++ equivalent, so that 
+ * later, we can map all of the Petsc routines into Adolc equivalents.
+ */ 
+
+#ifndef _PETSCVEC_H_
+#define _PETSCVEC_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"
+#include "../../../include/include.h"
+
+
+/*}}}*/
+
+class PetscVec{
+
+	public:
+		Vec vector;
+
+		#ifdef _HAVE_ADOLC_
+		IssmDouble* avector;
+		#endif
+
+
+		/*PetscVec constructors, destructors {{{*/
+		PetscVec();
+		PetscVec(int M,bool fromlocalsize=false);
+		PetscVec(IssmDouble* buffer, int M);
+		PetscVec(Vec petsc_vec);
+		~PetscVec();
+		/*}}}*/
+		/*PetscVec specific routines {{{*/
+		void Echo(void);
+		void Assemble(void);
+		void SetValues(int ssize, int* list, IssmDouble* values, InsMode mode);
+		void SetValue(int dof, IssmDouble value, InsMode  mode);
+		void GetValue(IssmDouble* pvalue, int dof);
+		void GetSize(int* pM);
+		void GetLocalSize(int* pM);
+		PetscVec* Duplicate(void);
+		void Set(IssmDouble value);
+		void AXPY(PetscVec* X, IssmDouble a);
+		void AYPX(PetscVec* X, IssmDouble a);
+		IssmDouble* ToMPISerial(void);
+		void Copy(PetscVec* to);
+		IssmDouble Norm(NormMode norm_type);
+		void Scale(IssmDouble scale_factor);
+		void PointwiseDivide(PetscVec* x,PetscVec* y);
+		IssmDouble Dot(PetscVec* vector);
+		/*}}}*/
+};
+
+#endif //#ifndef _PETSCVEC_H_
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/petscobjects.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/petscobjects.h	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/objects/petscobjects.h	(revision 12878)
@@ -0,0 +1,11 @@
+/* \file petscobjects.h
+ * \brief all includes for our own petsc object implementation
+ */
+
+#ifndef _PETSC_OBJECTS_H_
+#define _PETSC_OBJECTS_H_
+
+#include "./PetscMat.h"
+#include "./PetscVec.h"
+
+#endif
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp	(revision 12878)
@@ -28,5 +28,5 @@
 
 	/*Gather all range values into allranges, for all nodes*/
-	allranges=(int*)xmalloc(num_procs*sizeof(int));
+	allranges=xNew<int>(num_procs);
 	MPI_Allgather(&range,1,MPI_INT,allranges,1,MPI_INT,MPI_COMM_WORLD);
 
@@ -42,7 +42,4 @@
 	*plower_row=lower_row;
 	*pupper_row=upper_row;
-
-	/*Free ressources:*/
-	xfree((void**)&allranges);
-
+	xDelete<int>(allranges);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp	(revision 12878)
@@ -30,5 +30,5 @@
 			break;
 		default: 
-			_error_("unknown insert mode!");
+			_error2_("unknown insert mode!");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 12878)
@@ -30,5 +30,5 @@
 			break;
 		default: 
-			_error_("unknown matrix type !");
+			_error2_("unknown matrix type !");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp	(revision 12878)
@@ -30,5 +30,5 @@
 			break;
 		default: 
-			_error_("unknown norm !");
+			_error2_("unknown norm !");
 			break;
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatInvert.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatInvert.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatInvert.cpp	(revision 12878)
@@ -29,5 +29,5 @@
 	/*Some checks: */
 	MatGetSize(matrix,&M,&N);
-	if(M!=N) _error_("trying to invert a non square matrix!");
+	if(M!=N) _error2_("trying to invert a non square matrix!");
 
 	/*Create identitiy matrix: */
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatMultPatch.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatMultPatch.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatMultPatch.cpp	(revision 12878)
@@ -64,5 +64,5 @@
 	}
 	else{
-		result=1;\
+		result=1;
 	}
 	return result;
@@ -89,6 +89,6 @@
 	range=upper_row-lower_row+1;
 	if (range){
-		index=(int*)xmalloc(range*sizeof(int));
-		values=(double*)xmalloc(range*sizeof(double));
+		index=xNew<int>(range);
+		values=xNew<double>(range);
 		for (int i=0;i<range;i++){
 			*(index+i)=lower_row+i;
@@ -103,6 +103,6 @@
 
 	/*Free ressources:*/
-	xfree((void**)&index);
-	xfree((void**)&values);	
+	xDelete<int>(index);
+	xDelete<double>(values);	
 
 	/*Assign output pointers:*/
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatPartition.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatPartition.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatPartition.cpp	(revision 12878)
@@ -48,5 +48,5 @@
 			d_nz=0;
 			o_nz=0;
-			#ifdef _HAVE_PETSCDEV_
+			#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
 			MatCreateAIJ(MPI_COMM_WORLD,PETSC_DETERMINE,PETSC_DETERMINE, 0,0,d_nz,PETSC_NULL,o_nz,PETSC_NULL,&outmatrix);
 			#else
@@ -55,5 +55,5 @@
 		}
 		else if (strcmp(type,"mpidense")==0){
-			#ifdef _HAVE_PETSCDEV_
+			#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
 			MatCreateDense(MPI_COMM_WORLD,PETSC_DETERMINE,PETSC_DETERMINE, 0,0,PETSC_NULL,&outmatrix);
 			#else
@@ -62,5 +62,5 @@
 		}
 		else{
-			_error_("MatType %s not supported yet",type);
+			_error2_("MatType " << type << " not supported yet");
 		}
 		/*Assemble*/
@@ -77,5 +77,5 @@
 		count=0;
 		if (range){
-			node_rows=(int*)xmalloc(range*sizeof(int)); //this is the maximum number of rows one node can extract.
+			node_rows=xNew<int>(range); //this is the maximum number of rows one node can extract.
 		
 			for (i=0;i<row_partition_vector_size;i++){
@@ -98,5 +98,5 @@
 		
 		/*Same deal for columns*/
-		node_cols=(int*)xmalloc(col_partition_vector_size*sizeof(int));
+		node_cols=xNew<int>(col_partition_vector_size);
 		for (i=0;i<col_partition_vector_size;i++){
 			*(node_cols+i)=(int)*(col_partition_vector+i)-1;
@@ -128,6 +128,6 @@
 
 	/*Free ressources:*/
-	xfree((void**)&node_rows);
-	xfree((void**)&node_cols);
+	xDelete<int>(node_rows);
+	xDelete<int>(node_cols);
 	ISFree(&col_index);
 	ISFree(&row_index);
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatToSerial.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatToSerial.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/MatToSerial.cpp	(revision 12878)
@@ -32,5 +32,4 @@
 	double* outmatrix=NULL;
 	
-	
 	/*get matrix size: */
 	MatGetSize(matrix,&M,&N);
@@ -42,10 +41,10 @@
 	
 	/*Local and global allocation*/
-	if (my_rank==0)outmatrix=(double*)xmalloc(M*N*sizeof(double));
+	if (my_rank==0)outmatrix=xNew<double>(M*N);
 	
 	if (range){
-		local_matrix=(double*)xmalloc(N*range*sizeof(double));
-		idxm=(int*)xmalloc(range*sizeof(int));  
-		idxn=(int*)xmalloc(N*sizeof(int));  
+		local_matrix=xNew<double>(N*range);
+		idxm=xNew<int>(range);  
+		idxn=xNew<int>(N);  
 	 
 		for (i=0;i<N;i++){
@@ -78,13 +77,10 @@
 		//Still have the local_matrix on node 0 to take care of.
 		memcpy(outmatrix,local_matrix,N*range*sizeof(double));
-
 	} 
 	
 	/*Assign output pointer: */
 	*poutmatrix=outmatrix;
-	
-	xfree((void**)&idxm);
-	xfree((void**)&idxn);
-	xfree((void**)&local_matrix);
-
+	xDelete<int>(idxm);
+	xDelete<int>(idxn);
+	xDelete<double>(local_matrix);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/NewMat.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 12878)
@@ -20,5 +20,5 @@
 #include "../../mpi/patches/mpipatches.h"
 
-/*NewMat(int M,int N){{{1*/
+/*NewMat(int M,int N){{{*/
 Mat NewMat(int M,int N){
 
@@ -39,5 +39,5 @@
 	o_nz=(int)((double)nnz/(double)M/2.0); //number of non zeros per row/2
 
-	#ifdef _HAVE_PETSCDEV_
+	#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
 	MatCreateAIJ(MPI_COMM_WORLD,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
 	#else
@@ -48,5 +48,5 @@
 }
 /*}}}*/
-/*NewMat(int M,int N,double sparsity){{{1*/
+/*NewMat(int M,int N,double sparsity){{{*/
 Mat NewMat(int M,int N,double sparsity){
 
@@ -67,5 +67,5 @@
 	o_nz=(int)((double)nnz/(double)M/2.0); //number of non zeros per row/2
 
-	#ifdef _HAVE_PETSCDEV_
+	#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
 	if(sparsity==1){
 		MatCreateDense(MPI_COMM_WORLD,m,n,M,N,NULL,&outmatrix); 
@@ -81,5 +81,5 @@
 }
 /*}}}*/
-/*NewMat(int M,int N,int connectivity,int numberofdofspernode){{{1*/
+/*NewMat(int M,int N,int connectivity,int numberofdofspernode){{{*/
 Mat NewMat(int M,int N,int connectivity,int numberofdofspernode){
 
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp	(revision 12878)
@@ -36,12 +36,15 @@
 	MatGetSize(petsc_matrix,&rows,&cols);
 
-	idxm=(int*)xmalloc(rows*sizeof(int));
-	idxn=(int*)xmalloc(cols*sizeof(int));
+	idxm=xNew<int>(rows);
+	idxn=xNew<int>(cols);
 
 	for(i=0;i<rows;i++)idxm[i]=i;
 	for(i=0;i<cols;i++)idxn[i]=i;
 
-	matrix=(double*)xmalloc(rows*cols*sizeof(double));
+	matrix=xNew<double>(rows*cols);
 	MatGetValues(petsc_matrix,rows,idxm,cols,idxn,matrix);
+
+	xDelete<int>(idxm);
+	xDelete<int>(idxn);
 
 	/*Assign output pointers: */
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 12878)
@@ -55,5 +55,5 @@
 			if(first[0]!='-'){
 				/*This is not good, the option does not have '-'! Get out*/
-				_error_("%s%s%s","Option ",first," should be preceded by '-'!");
+				_error2_("Option " << first << " should be preceded by '-'!");
 			}
 			/*Reduce first to bare option value*/
@@ -90,5 +90,5 @@
 	}
 
-#ifdef _HAVE_PETSCDEV_
+#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
 	PetscTokenDestroy(&token);
 #else
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscVectorToDoubleVector.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscVectorToDoubleVector.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/PetscVectorToDoubleVector.cpp	(revision 12878)
@@ -28,9 +28,9 @@
 		VecGetSize(petsc_vector,&rows);
 		if(rows){
-			idxm=(int*)xmalloc(rows*sizeof(int));
-			vector=(double*)xmalloc(rows*sizeof(double));
+			idxm=xNew<int>(rows);
+			vector=xNew<double>(rows);
 			for(i=0;i<rows;i++)idxm[i]=i;
-
 			VecGetValues(petsc_vector,rows,idxm,vector);
+			xDelete<int>(idxm);
 		}
 	}
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/SerialToVec.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/SerialToVec.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/SerialToVec.cpp	(revision 12878)
@@ -38,6 +38,6 @@
 
 	if (range){
-		idxn=(int*)xmalloc(range*sizeof(int)); 
-		values=(double*)xmalloc(range*sizeof(double));
+		idxn=xNew<int>(range); 
+		values=xNew<double>(range);
 		for (i=0;i<range;i++){
 			idxn[i]=lower_row+i;
@@ -54,6 +54,6 @@
 
 	/*Free ressources:*/
-	xfree((void**)&idxn);
-	xfree((void**)&values);
+	xDelete<int>(idxn);
+	xDelete<double>(values);
 
 	return outvector;
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecMerge.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 12878)
@@ -35,5 +35,5 @@
 	/*If the dimension of the partitioning vector is not the same as that of vector B, we have a problem: */
 	if ( (row_partition_size !=MB) ){
-		_error_("Dimensions of partitioning vector incompatible with dimensions of input vector\n");
+		_error2_("Dimensions of partitioning vector incompatible with dimensions of input vector\n");
 	}
 
@@ -45,6 +45,6 @@
 	if (range){
 		/*This node owns rows of vector B, get them*/
-		idxm=(int*)xmalloc(range*sizeof(int));
-		values=(double*)xmalloc(range*sizeof(double));
+		idxm=xNew<int>(range);
+		values=xNew<double>(range);
 		for (i=0;i<range;i++){
 			*(idxm+i)=lower_row+i;
@@ -63,6 +63,5 @@
 
 	/*Free ressources:*/
-	xfree((void**)&idxm);
-	xfree((void**)&values);
-
+	xDelete<int>(idxm);
+	xDelete<double>(values);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecPartition.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecPartition.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecPartition.cpp	(revision 12878)
@@ -56,5 +56,5 @@
 
 		if (range){
-			node_rows=(int*)xmalloc(range*sizeof(int)); //this is the maximum number of rows one node can extract.
+			node_rows=xNew<int>(range); //this is the maximum number of rows one node can extract.
 		
 			count=0;
@@ -71,8 +71,8 @@
 					
      	if (count){
-			values=(double*)xmalloc(count*sizeof(double)); //holder for the values to be extracted from vectorA
+			values=xNew<double>(count); //holder for the values to be extracted from vectorA
 		}
 		else{
-			xfree((void**)&node_rows); //count=0 means no values was condensed out for this node. null node_rows for use in VecGetValues.
+			xDelete<int>(node_rows); //count=0 means no values was condensed out for this node. null node_rows for use in VecGetValues.
 			values=NULL;
 		}
@@ -110,13 +110,9 @@
 		VecAssemblyBegin(outvector);
 		VecAssemblyEnd(outvector);
-		
 	}
 	
 	/*Assign output pointers:*/
 	*poutvector=outvector;
-
-	/*Free ressources:*/
-	xfree((void**)&node_rows);
-	xfree((void**)&values);
-
+	xDelete<int>(node_rows);
+	xDelete<double>(values);
 }
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecToMPISerial.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecToMPISerial.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecToMPISerial.cpp	(revision 12878)
@@ -42,5 +42,5 @@
 
 	/*Allocate gathered vector on all nodes .*/
-	gathered_vector=(double*)xmalloc(vector_size*sizeof(double));
+	gathered_vector=xNew<double>(vector_size);
 	
 	/*Allocate local vectors*/
@@ -50,9 +50,9 @@
 
 	if (range){
-		idxn=(int*)xmalloc(range*sizeof(int)); 
+		idxn=xNew<int>(range); 
 		for (i=0;i<range;i++){
 			*(idxn+i)=lower_row+i;
 		} 
-		local_vector=(double*)xmalloc(range*sizeof(double));
+		local_vector=xNew<double>(range);
 		/*Extract values from MPI vector to serial local_vector on each node*/
 		VecGetValues(vector,range,idxn,local_vector); 
@@ -87,6 +87,6 @@
 	
 	/*free ressources: */
-	xfree((void**)&idxn);
-	xfree((void**)&local_vector);
+	xDelete<int>(idxn);
+	xDelete<double>(local_vector);
 	
 	return 1;
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecTranspose.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecTranspose.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/patches/VecTranspose.cpp	(revision 12878)
@@ -33,11 +33,11 @@
 
 	if (range){
-		idxm=(int*)xmalloc(range*sizeof(int)); 
-		tidxm=(int*)xmalloc(range*sizeof(int)); 
+		idxm=xNew<int>(range); 
+		tidxm=xNew<int>(range); 
 		for (i=0;i<range;i++){
 			*(idxm+i)=lower_row+i;
 		} 
-		values=(double*)xmalloc(range*sizeof(double));
-		tvalues=(double*)xmalloc(range*sizeof(double));
+		values=xNew<double>(range);
+		tvalues=xNew<double>(range);
 		
 		VecGetValues(vector,range,idxm,values);
@@ -56,8 +56,8 @@
 
 	/*Free ressources: */
-	xfree((void**)&idxm);
-	xfree((void**)&values);
-	xfree((void**)&tidxm);
-	xfree((void**)&tvalues);
+	xDelete<int>(idxm);
+	xDelete<double>(values);
+	xDelete<int>(tidxm);
+	xDelete<double>(tvalues);
 
 	/*Assign output pointers: */
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/petscincludes.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/petscincludes.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/petsc/petscincludes.h	(revision 12878)
@@ -16,4 +16,5 @@
 /*our own patches: */
 #include "patches/petscpatches.h"
+#include "objects/petscobjects.h"
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp	(revision 12878)
@@ -44,5 +44,5 @@
 	int i;
 
-	decomp=xmalloc(input*sizeof(int));
+	decomp=xNew<int>(input);
 	*decomp=input;
 	for (i=0;i<input;i++){
@@ -57,5 +57,4 @@
 		}
 	}
-
 	*pdecomp=decomp;
 }
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 12878)
@@ -13,13 +13,11 @@
 #include "../../scalapack/FortranMapping.h"
 
-void PlapackInvertMatrixLocalCleanup(PLA_Obj* pa,PLA_Template* ptempl,double** parrayA,
-		int** pidxnA,MPI_Comm* pcomm_2d);
+void PlapackInvertMatrixLocalCleanup(PLA_Obj* pa,PLA_Template* ptempl,double** parrayA,int** pidxnA,MPI_Comm* pcomm_2d);
 	
 int PlapackInvertMatrix(Mat* A,Mat* inv_A,int status,int con){ 
-	/*inv_A does not yet exist, inv_A was just xmalloced, that's all*/
+	/*inv_A does not yet exist, inv_A was just allocated, that's all*/
 
 	/*Error management*/
 	int i,j;
-	
 
 	/*input*/
@@ -53,5 +51,5 @@
 
 	/*Some dimensions checks: */
-	if (mA!=nA) _error_(" trying to take the invert of a non-square matrix!");
+	if (mA!=nA) _error2_("trying to take the invert of a non-square matrix!");
 
 	/* Set default Plapack parameters */
@@ -94,5 +92,4 @@
 	/* Set the datatype */
 	datatype = MPI_DOUBLE;
-
 	
 	/* Copy A into a*/
@@ -104,6 +101,6 @@
 	upper_row--; 
 	range=upper_row-lower_row+1;
-	arrayA=xmalloc(nA*sizeof(double));
-	idxnA=xmalloc(nA*sizeof(int));
+	arrayA = xNew<double>(nA);
+	idxnA  = xNew<int>(nA);
 	for (i=0;i<nA;i++){
 		*(idxnA+i)=i;
@@ -128,10 +125,9 @@
 	PLA_Obj_free(&a);
 	PLA_Temp_free(&templ);
-	xfree((void**)&arrayA);
-	xfree((void**)&idxnA);
+	xDelete<double>(arrayA);
+	xDelete<int>(idxnA);
 	
 	/*Finalize PLAPACK*/
 	PLA_Finalize();
 	MPI_Comm_free(&comm_2d);
-
 }
Index: /issm/branches/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp	(revision 12878)
@@ -45,6 +45,6 @@
 	
 	/*Vector physically based block cyclic distribution: */
-	row_nodes=xmalloc(mA*sizeof(int));
-	col_nodes=xmalloc(nA*sizeof(int));
+	row_nodes=xNew<int>(mA);
+	col_nodes=xNew<int>(nA);
 	for (i=0;i<mA;i++){
 		i0=i/nb;
@@ -60,5 +60,5 @@
 	PLA_Temp_comm_col_rank(templ,&myrow);
 
-	idxm=xmalloc(mA*sizeof(int));
+	idxm=xNew<int>(mA);
 	count=0;
 	for (i=0;i<mA;i++){
@@ -70,5 +70,5 @@
 	idxm_count=count;
 
-	idxn=xmalloc(nA*sizeof(int));
+	idxn=xNew<int>(nA);
 	count=0;
 	for (i=0;i<nA;i++){
@@ -92,7 +92,7 @@
 
 	/*Free ressources:*/
-	xfree((void**)&row_nodes);
-	xfree((void**)&col_nodes);
-	xfree((void**)&idxm);
-	xfree((void**)&idxn);
+	xDelete<int>(row_nodes);
+	xDelete<int>(col_nodes);
+	xDelete<int>(idxm);
+	xDelete<int>(idxn);
 }
Index: /issm/branches/trunk-jpl-damage/src/dox/issm.dox
===================================================================
--- /issm/branches/trunk-jpl-damage/src/dox/issm.dox	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/dox/issm.dox	(revision 12878)
@@ -46,17 +46,17 @@
 </th>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">499</td><td  bgcolor=#FFFFFF style="text-align:right;">14338</td><td  bgcolor=#FFFFFF style="text-align:right;">16340</td><td  bgcolor=#FFFFFF style="text-align:right;">54651</td><td  bgcolor=#FFFFFF style="text-align:right;">85329</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">508</td><td  bgcolor=#FFFFFF style="text-align:right;">14595</td><td  bgcolor=#FFFFFF style="text-align:right;">16762</td><td  bgcolor=#FFFFFF style="text-align:right;">56036</td><td  bgcolor=#FFFFFF style="text-align:right;">87393</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">919</td><td  bgcolor=#C6E2FF style="text-align:right;">6875</td><td  bgcolor=#C6E2FF style="text-align:right;">13184</td><td  bgcolor=#C6E2FF style="text-align:right;">30350</td><td  bgcolor=#C6E2FF style="text-align:right;">50409</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">925</td><td  bgcolor=#C6E2FF style="text-align:right;">6851</td><td  bgcolor=#C6E2FF style="text-align:right;">13228</td><td  bgcolor=#C6E2FF style="text-align:right;">30468</td><td  bgcolor=#C6E2FF style="text-align:right;">50547</td>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">366</td><td  bgcolor=#FFFFFF style="text-align:right;">2665</td><td  bgcolor=#FFFFFF style="text-align:right;">2529</td><td  bgcolor=#FFFFFF style="text-align:right;">9400</td><td  bgcolor=#FFFFFF style="text-align:right;">14594</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">378</td><td  bgcolor=#FFFFFF style="text-align:right;">2758</td><td  bgcolor=#FFFFFF style="text-align:right;">2612</td><td  bgcolor=#FFFFFF style="text-align:right;">9818</td><td  bgcolor=#FFFFFF style="text-align:right;">15188</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> m4 </th><td  bgcolor=#C6E2FF style="text-align:right;">7</td><td  bgcolor=#C6E2FF style="text-align:right;">993</td><td  bgcolor=#C6E2FF style="text-align:right;">80</td><td  bgcolor=#C6E2FF style="text-align:right;">8237</td><td  bgcolor=#C6E2FF style="text-align:right;">9310</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> m4 </th><td  bgcolor=#C6E2FF style="text-align:right;">7</td><td  bgcolor=#C6E2FF style="text-align:right;">997</td><td  bgcolor=#C6E2FF style="text-align:right;">80</td><td  bgcolor=#C6E2FF style="text-align:right;">8259</td><td  bgcolor=#C6E2FF style="text-align:right;">9336</td>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> Python </th><td  bgcolor=#FFFFFF style="text-align:right;">47</td><td  bgcolor=#FFFFFF style="text-align:right;">183</td><td  bgcolor=#FFFFFF style="text-align:right;">518</td><td  bgcolor=#FFFFFF style="text-align:right;">1099</td><td  bgcolor=#FFFFFF style="text-align:right;">1800</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Python </th><td  bgcolor=#FFFFFF style="text-align:right;">53</td><td  bgcolor=#FFFFFF style="text-align:right;">400</td><td  bgcolor=#FFFFFF style="text-align:right;">610</td><td  bgcolor=#FFFFFF style="text-align:right;">1424</td><td  bgcolor=#FFFFFF style="text-align:right;">2434</td>
 </tr>
 <tr>
@@ -67,5 +67,5 @@
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#C6E2FF style="text-align:right;">5</td><td  bgcolor=#C6E2FF style="text-align:right;">46</td><td  bgcolor=#C6E2FF style="text-align:right;">71</td><td  bgcolor=#C6E2FF style="text-align:right;">226</td><td  bgcolor=#C6E2FF style="text-align:right;">343</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#C6E2FF style="text-align:right;">5</td><td  bgcolor=#C6E2FF style="text-align:right;">47</td><td  bgcolor=#C6E2FF style="text-align:right;">75</td><td  bgcolor=#C6E2FF style="text-align:right;">239</td><td  bgcolor=#C6E2FF style="text-align:right;">361</td>
 </tr>
 <tr>
@@ -73,8 +73,8 @@
 </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;">3</td><td  bgcolor=#C6E2FF style="text-align:right;">3</td><td  bgcolor=#C6E2FF style="text-align:right;">24</td><td  bgcolor=#C6E2FF style="text-align:right;">30</td>
+<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>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">1858</td><td  bgcolor=#FFFFFF style="text-align:right;">25240</td><td  bgcolor=#FFFFFF style="text-align:right;">32752</td><td  bgcolor=#FFFFFF style="text-align:right;">104721</td><td  bgcolor=#FFFFFF style="text-align:right;">162713</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">1890</td><td  bgcolor=#FFFFFF style="text-align:right;">25787</td><td  bgcolor=#FFFFFF style="text-align:right;">33397</td><td  bgcolor=#FFFFFF style="text-align:right;">106984</td><td  bgcolor=#FFFFFF style="text-align:right;">166168</td>
 </tr>
 </table>
Index: /issm/branches/trunk-jpl-damage/src/m/classes/autodiff.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/autodiff.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/autodiff.m	(revision 12878)
@@ -22,5 +22,5 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/balancethickness.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/balancethickness.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/balancethickness.m	(revision 12878)
@@ -25,11 +25,11 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 			%Early return
 			if solution~=BalancethicknessSolutionEnum, return; end
 
-			checkfield(md,'balancethickness.spcthickness','forcing',1);
-			checkfield(md,'balancethickness.thickening_rate','size',[md.mesh.numberofvertices 1],'NaN',1);
-			checkfield(md,'balancethickness.stabilization','size',[1 1],'values',[0 1 2 3]);
+			md = checkfield(md,'balancethickness.spcthickness','forcing',1);
+			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]);
 		end % }}}
 		function disp(obj) % {{{
Index: /issm/branches/trunk-jpl-damage/src/m/classes/bamggeom.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/bamggeom.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/bamggeom.m	(revision 12878)
@@ -6,5 +6,5 @@
 classdef bamggeom
 	properties (SetAccess=public) 
-		% {{{1
+		% {{{
 		Vertices=[];
 		Edges=[];
@@ -18,5 +18,5 @@
 	end
 	methods
-		function bg = bamggeom(varargin)% {{{1
+		function bg = bamggeom(varargin)% {{{
 		%BAMGGEOM - constructor for bamggeom object
 		%
@@ -44,5 +44,5 @@
 			end
 		end%}}}
-		function display(bg)% {{{1
+		function display(bg)% {{{
 			disp(sprintf('\n%s = \n',inputname(1)));
 			disp(struct(bg))
Index: /issm/branches/trunk-jpl-damage/src/m/classes/bamgmesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/bamgmesh.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/bamgmesh.m	(revision 12878)
@@ -6,5 +6,5 @@
 classdef bamgmesh
 	properties (SetAccess=public) 
-		% {{{1
+		% {{{
 		Vertices=[];
 		Edges=[];
@@ -26,5 +26,5 @@
 	end
 	methods
-		function bg = bamgmesh(varargin)% {{{1
+		function bg = bamgmesh(varargin)% {{{
 
 		switch nargin
@@ -48,5 +48,5 @@
 			end
 		end%}}}
-		function display(bm)% {{{1
+		function display(bm)% {{{
 			disp(sprintf('\n%s = \n',inputname(1)));
 			disp(struct(bm))
Index: /issm/branches/trunk-jpl-damage/src/m/classes/basalforcings.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/basalforcings.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/basalforcings.m	(revision 12878)
@@ -22,15 +22,15 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			if ismember(PrognosticAnalysisEnum,analyses) & ~(solution==TransientSolutionEnum & md.transient.isprognostic==0),
-				checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1);
 			end
 			if ismember(BalancethicknessAnalysisEnum,analyses),
-				checkfield(md,'basalforcings.melting_rate','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'basalforcings.melting_rate','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
 			if ismember(ThermalAnalysisEnum,analyses) & ~(solution==TransientSolutionEnum & md.transient.isthermal==0),
-				checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1);
-				checkfield(md,'basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0);
+				md = checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0);
 			end
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/clusters/acenet.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/acenet.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/clusters/acenet.m	(revision 12878)
@@ -0,0 +1,109 @@
+%ACENET class definition
+%
+%   Usage:
+%      cluster=acenet();
+%      cluster=acenet('np',3);
+%      cluster=acenet('np',3,'login','username');
+
+classdef acenet
+    properties (SetAccess=public) 
+		 % {{{
+		 name='glacdyn.ace-net.ca'
+		 %name='placentia.ace-net.ca'
+		 %name='brasdor.ace-net.ca'
+		 login='klemorza';
+		 np=10;
+		 port=0;
+		 queue='shortq';
+		 time=10;
+		 % codepath='/usr/local/issm-r11321/bin'; % this one is for issm on acenet global
+		 codepath='/home/klemorza/issm/bin'; % this one is for issm on my acenet directory
+		 executionpath='/home/klemorza/issm/execution';
+		 %}}}
+	 end
+	 methods
+		 function cluster=acenet(varargin) % {{{
+			 %use provided options to change fields
+			 options=pairoptions(varargin{:});
+
+			 %initialize cluster using user settings if provided
+			 if (exist([cluster.name '_settings'])==2), eval([cluster.name '_settings']); end
+
+			 %OK get other fields
+			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		 end
+		 %}}}
+		 function disp(cluster) % {{{
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    np: %i',cluster.np));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+		 end
+		 %}}}
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			 available_queues={'debug','shortq','longq'};
+			 queue_requirements_time=[60*1 60*3 60*17];
+			 queue_requirements_np=[32 128 256];
+
+			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#!/bin/bash\n');
+			 fprintf(fid,'#$ -cwd\n');
+          fprintf(fid,'#$ -N issm\n');
+          fprintf(fid,'#$ -l h_rt=10:0:0\n');
+          fprintf(fid,'#$ -pe ompi* %i\n',cluster.np);
+          fprintf(fid,'#$ -j y\n');
+          fprintf(fid,'module purge\n');
+          fprintf(fid,'module load gcc openmpi/gcc\n');
+          fprintf(fid,'module load issm\n');
+          fprintf(fid,'\n');
+          fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+                   cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
+			 fclose(fid);
+
+		 end
+		 %}}}
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			 %compress the files into one zip.
+			 compressstring=['tar -zcf ' dirname '.tar.gz '];
+			 for i=1:numel(filelist),
+				 compressstring = [compressstring ' ' filelist{i}];
+			 end
+			 if cluster.interactive,
+				 compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
+			 end
+			 system(compressstring);
+
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+			 disp('launching solution sequence on remote cluster');
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
+
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+
+		 end %}}}
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/clusters/castor.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/castor.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/clusters/castor.m	(revision 12878)
@@ -8,5 +8,5 @@
 classdef castor
     properties (SetAccess=public) 
-		 % {{{1
+		 % {{{
 		 name='castor'
 		 login='username';
@@ -20,9 +20,9 @@
 	 end
 	 methods
-		 function cluster=castor(varargin) % {{{1
+		 function cluster=castor(varargin) % {{{
 			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
 		 end
 		 %}}}
-		 function disp(cluster) % {{{1
+		 function disp(cluster) % {{{
 			 %  display the object
 			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
@@ -37,5 +37,5 @@
 		 end
 		 %}}}
-		 function checkconsistency(cluster,md,solution,analyses) % {{{1
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
 
 			 available_queues={'shortc','longc'};
@@ -46,13 +46,11 @@
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,md) % {{{1
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
-			 %retrieve parameters 
-			 modelname=md.miscellaneous.name; 
-			 solution=md.private.solution;
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
 
-			 %open file for writing: 
+			 %write queuing script 
 			 fid=fopen([modelname '.queue'],'w');
-
 			 fprintf(fid,'#!/bin/sh\n');
 			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60); %walltime is in seconds.
@@ -64,70 +62,39 @@
 			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
 			 fprintf(fid,'#PBS -e %s.errlog \n',modelname);
-
 			 fprintf(fid,'export PBS_O_WORKDIR=%s\n',cluster.executionpath);
 			 fprintf(fid,'cd $PBS_O_WORKDIR\n');
 			 fprintf(fid,'export OMP_NUM_THREADS=1\n');
 			 fprintf(fid,'dplace -s1 -c0-%i mpiexec -np %i %s/issm.exe %s %s %s',cluster.np-1,cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
-
-			 %close file
 			 fclose(fid);
 
 		 end
 		 %}}}
-		 function LaunchQueueJob(cluster,md,options)% {{{1
-			 
-			 %lauch command, to be executed via ssh
-			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
-			                ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && qsub ' modelname '.queue '];
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
 
-			if ~strcmpi(options.batch,'yes'),
-				
-				%compress the files into one zip.
-				compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
-				if md.qmu.isdakota,
-					compressstring=[compressstring md.miscellaneous.name '.qmu.in'];
-				end
-				system(compressstring);
-				
-				disp('uploading input file and queueing script');
-				issmscpout(md.cluster.name,md.cluster.executionpath,md.cluster.login,md.cluster.port,{[md.private.runtimename '.tar.gz']});
-				
-				disp('launching solution sequence on remote cluster');
-				issmssh(md.cluster.name,md.cluster.login,md.cluster.port,launchcommand);
+			 %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);
 
-			else
-				disp('batch mode requested: not launching job interactively');
-				disp('launch solution sequence on remote cluster by hand');
-			end
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
 
-		 end
-		 %}}}
-		 function Download(cluster,md)% {{{1
+			 disp('launching solution sequence on remote cluster');
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
 
-			%some check
-			if isempty(md.private.runtimename),
-				error('pfe Download error message: supply runtime name for results to be loaded!');
-			end
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
 
-			%Figure out the  directory where all the files are in: 
-			directory=[cluster.executionpath '/' md.private.runtimename '/'];
-
-			%What packages are we picking up from remote cluster
-			packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
-			if md.qmu.isdakota,
-				packages{end+1}=[md.miscellaneous.name '.qmu.err'];
-				packages{end+1}=[md.miscellaneous.name '.qmu.out'];
-				if isfield(md.qmu.params,'tabular_graphics_data'),
-					if md.qmu.params.tabular_graphics_data==true,
-						packages{end+1}='dakota_tabular.dat'; 
-					end
-				end
-			else
-				packages{end+1}=[md.miscellaneous.name '.outbin'];
-			end
-
-			%copy files from cluster to present directory
-			issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
-		end %}}}
+		 end %}}}
 	end
 end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/clusters/cosmos.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/cosmos.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/clusters/cosmos.m	(revision 12878)
@@ -8,5 +8,5 @@
 classdef cosmos
     properties (SetAccess=public) 
-		 % {{{1
+		 % {{{
 		 name='cosmos'
 		 login='username';
@@ -20,9 +20,9 @@
 	 end
 	 methods
-		 function cluster=cosmos(varargin) % {{{1
+		 function cluster=cosmos(varargin) % {{{
 			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
 		 end
 		 %}}}
-		 function disp(cluster) % {{{1
+		 function disp(cluster) % {{{
 			 %  display the object
 			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
@@ -37,5 +37,5 @@
 		 end
 		 %}}}
-		 function checkconsistency(cluster,md,solution,analyses) % {{{1
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
 
 			 available_queues={'debug','shortq','longq'};
@@ -46,13 +46,11 @@
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,md) % {{{1
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
-			 %retrieve parameters 
-			 modelname=md.miscellaneous.name; 
-			 solution=md.private.solution;
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
 
-			 %open file for writing: 
+			 %write queuing script 
 			 fid=fopen([modelname '.queue'],'w');
-
 			 fprintf(fid,'#!/bin/bash\n');
 			 fprintf(fid,'#PBS -l select=%i:ncpus=1\n',cluster.np);
@@ -68,65 +66,35 @@
 			 fprintf(fid,'ulimit -c 0\n');
 			 fprintf(fid,'/opt/mpich/gm/intel10.1/bin/mpiexec -np %i %s/issm.exe %s %s %s',cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
-
-			 %close file
 			 fclose(fid);
 
 		 end
 		 %}}}
-		 function LaunchQueueJob(cluster,md,options)% {{{1
-			 
-			 %lauch command, to be executed via ssh
-			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
-			                ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && qsub -S/bin/sh ' modelname '.queue '];
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
 
-			if ~strcmpi(options.batch,'yes'),
-				
-				%compress the files into one zip.
-				compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
-				if md.qmu.isdakota,
-					compressstring=[compressstring md.miscellaneous.name '.qmu.in'];
-				end
-				system(compressstring);
-				
-				disp('uploading input file and queueing script');
-				issmscpout(md.cluster.name,md.cluster.executionpath,md.cluster.login,md.cluster.port,{[md.private.runtimename '.tar.gz']});
-				
-				disp('launching solution sequence on remote cluster');
-				issmssh(md.cluster.name,md.cluster.login,md.cluster.port,launchcommand);
+			 %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);
 
-			else
-				disp('batch mode requested: not launching job interactively');
-				disp('launch solution sequence on remote cluster by hand');
-			end
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
 
-		 end
-		 %}}}
-		 function Download(cluster,md)% {{{1
+			 disp('launching solution sequence on remote cluster');
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
 
-			%some check
-			if isempty(md.private.runtimename),
-				error('pfe Download error message: supply runtime name for results to be loaded!');
-			end
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
 
-			%Figure out the  directory where all the files are in: 
-			directory=[cluster.executionpath '/' md.private.runtimename '/'];
-
-			%What packages are we picking up from remote cluster
-			packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
-			if md.qmu.isdakota,
-				packages{end+1}=[md.miscellaneous.name '.qmu.err'];
-				packages{end+1}=[md.miscellaneous.name '.qmu.out'];
-				if isfield(md.qmu.params,'tabular_graphics_data'),
-					if md.qmu.params.tabular_graphics_data==true,
-						packages{end+1}='dakota_tabular.dat'; 
-					end
-				end
-			else
-				packages{end+1}=[md.miscellaneous.name '.outbin'];
-			end
-
-			%copy files from cluster to present directory
-			issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
-		end %}}}
+		 end %}}}
 	end
 end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/clusters/discover.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/discover.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/clusters/discover.m	(revision 12878)
@@ -0,0 +1,192 @@
+%PFE class definition
+%
+%   Usage:
+%      cluster=discover();
+%      cluster=discover('np',3);
+%      cluster=discover('np',3,'login','username');
+
+classdef discover 
+    properties (SetAccess=public)  
+		 % {{{
+		 name=oshostname();
+		 login='';
+		 numnodes=20;
+		 cpuspernode=8; 
+		 port=1025;
+		 queue='general';
+		 time=12*60;
+		 processor='west';
+		 codepath='';
+		 executionpath='';
+		 interactive=0;
+		 bbftp=0;
+		 numstreams=8;
+		 hyperthreading=0;
+	 end
+	 properties (SetAccess=private) 
+		 np=20*8;
+		 % }}}
+	 end
+	 methods
+		 function cluster=discover(varargin) % {{{
+
+			 %initialize cluster using default settings if provided
+			 if (exist('discover_settings')==2), discover_settings; end
+
+			 %use provided options to change fields
+			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		 end
+		 %}}}
+		 function disp(cluster) % {{{
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    numnodes: %i',cluster.numnodes));
+			 disp(sprintf('    cpuspernode: %i',cluster.cpuspernode));
+			 disp(sprintf('    np: %i',cluster.cpuspernode*cluster.numnodes));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    time: %i',cluster.time));
+			 disp(sprintf('    processor: %s',cluster.processor));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+			 disp(sprintf('    interactive: %i',cluster.interactive));
+			 disp(sprintf('    hyperthreading: %i',cluster.hyperthreading));
+		 end
+		 %}}}
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			 available_queues={'general_long','general','general_small','debug'};
+			 queue_requirements_time=[24*60 12*60 12*60 60];
+			 queue_requirements_np=[516 1024 16 32];
+
+			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
+
+			 if ( strcmpi(cluster.queue,'general') & cluster.cpuspernode*cluster.numnodes < 17)
+				 md = checkmessage(md,'cpus must be great than 17 for general queue');
+			 end
+			 %now, check cluster.cpuspernode according to processor type
+			 if ( strcmpi(cluster.processor,'neha')),
+				 if ((cluster.cpuspernode>8 ) | (cluster.cpuspernode<1)),
+					 md = checkmessage(md,'cpuspernode should be between 1 and 8 for ''neha'' processors');
+				 end
+			 elseif strcmpi(cluster.processor,'west'),
+				 if ((cluster.cpuspernode>12 ) | (cluster.cpuspernode<1)),
+					 md = checkmessage(md,'cpuspernode should be between 1 and 12 for ''west'' processors');
+				 end
+			 else
+				 md = checkmessage(md,'unknown processor type, should be ''neha'' or ''west'' ');
+			 end
+
+			 %Miscelaneous
+			 if isempty(cluster.login), md = checkmessage(md,'login empty'); end
+			 if isempty(cluster.codepath), md = checkmessage(md,'codepath empty'); end
+			 if isempty(cluster.executionpath), md = checkmessage(md,'executionpath empty'); end
+
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 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 -l select=%i:ncpus=%i:proc=%s\n',cluster.numnodes,cluster.cpuspernode,cluster.processor);
+			 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 -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-10.1.023\n');
+			 fprintf(fid,'module load mpi/impi-3.2.2.006\n');
+			 fprintf(fid,'module load lib/mkl-10.1.2.024\n\n');
+			 fprintf(fid,'export PATH="$PATH:."\n\n');
+			 fprintf(fid,'export MPI_GROUP_MAX=64\n\n');
+			 fprintf(fid,'cd $PBS_O_WORKDIR\n\n');
+			 fprintf(fid,'mpirun -np %i %s/issm.exe %s $PBS_O_WORKDIR %s\n',cluster.np,cluster.codepath,EnumToString(solution),modelname);
+			 if ~io_gather, %concatenate the output files:
+				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			 end
+			 fclose(fid);
+
+			 %in interactive mode, create a run file, and errlog and outlog file
+			 if cluster.interactive,
+				 fid=fopen([modelname '.run'],'w');
+				 if ~isvalgrind,
+					 fprintf(fid,'mpirun -np %i %s/issm.exe %s $PBS_O_WORKDIR %s\n',cluster.np,cluster.codepath,EnumToString(solution),modelname);
+				 else
+					 fprintf(fid,'mpirun -np %i valgrind --leak-check=full %s/issm.exe %s $PBS_O_WORKDIR %s\n',cluster.np,cluster.codepath,EnumToString(solution),modelname);
+				 end
+				 if ~io_gather, %concatenate the output files:
+					 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+				 end
+				 fclose(fid);
+				 fid=fopen([modelname '.errlog'],'w');
+				 fclose(fid);
+				 fid=fopen([modelname '.outlog'],'w');
+				 fclose(fid);
+			 end
+		 end %}}}
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			 %compress the files into one zip.
+			 compressstring=['tar -zcf ' dirname '.tar.gz '];
+			 for i=1:numel(filelist),
+				 compressstring = [compressstring ' ' filelist{i}];
+			 end
+			 if cluster.interactive,
+				 compressstring = [compressstring ' ' modelname '.run '  modelname '.errlog ' modelname '.outlog '];
+			 end
+			 system(compressstring);
+
+			 disp('uploading input file and queueing script');
+			 if cluster.interactive,
+				 directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive)];
+			 else 
+				 directory=cluster.executionpath;
+			 end
+
+			 if ~cluster.bbftp,
+				 issmscpout(cluster.name,directory,cluster.login,cluster.port,{[dirname '.tar.gz']});
+			 else
+				 issmbbftpout(cluster.name,directory,cluster.login,cluster.port,cluster.numstreams,{[dirname '.tar.gz']});
+			 end
+
+			 %lauch command, to be executed via ssh
+			 if ~cluster.interactive, 
+				 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+					 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 else
+				 launchcommand=['cd ' cluster.executionpath '/Interactive' num2str(cluster.interactive) ' && tar -zxf ' dirname '.tar.gz'];
+			 end
+
+			 disp('launching solution sequence on remote cluster');
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end
+		 %}}}
+		 function Download(cluster,dirname,filelist)% {{{
+
+			 %copy files from cluster to current directory
+			 if ~cluster.interactive,
+				 directory=[cluster.executionpath '/' dirname '/'];
+			 else
+				 directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive) '/'];
+			 end
+
+			 if ~cluster.bbftp,
+				 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+			 else
+				 issmbbftpin(cluster.name, cluster.login, cluster.port, cluster.numstreams, directory, filelist);
+			 end
+
+		 end %}}}
+	end
+end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/clusters/gemini.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/gemini.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/clusters/gemini.m	(revision 12878)
@@ -8,5 +8,5 @@
 classdef gemini
     properties (SetAccess=public) 
-	% {{{1
+	% {{{
 		name='gemini'
 		login='username';
@@ -20,9 +20,9 @@
     end
     methods
-		 function cluster=gemini(varargin) % {{{1
+		 function cluster=gemini(varargin) % {{{
 			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
 		 end
 		 %}}}
-		 function disp(cluster) % {{{1
+		 function disp(cluster) % {{{
 			 %  display the object
 			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
@@ -37,5 +37,5 @@
 		 end
 		 %}}}
-		 function checkconsistency(cluster,md,solution,analyses) % {{{1
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
 
 			 available_queues={'debug','shortg','longg'};
@@ -46,13 +46,11 @@
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,md) % {{{1
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
-			 %retrieve parameters 
-			 modelname=md.miscellaneous.name; 
-			 solution=md.private.solution;
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
 
-			 %open file for writing: 
+			 %write queuing script 
 			 fid=fopen([modelname '.queue'],'w');
-
 			 fprintf(fid,'#!/bin/sh\n');
 			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60); %walltime is in seconds.
@@ -69,65 +67,35 @@
 			 fprintf(fid,'export OMP_NUM_THREADS=1\n');
 			 fprintf(fid,'dplace -s1 -c0-%i mpiexec -np %i %s/issm.exe %s %s %s',cluster.np-1,cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
-
-			 %close file
 			 fclose(fid);
 
 		 end
 		 %}}}
-		 function LaunchQueueJob(cluster,md,options)% {{{1
-			 
-			 %lauch command, to be executed via ssh
-			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
-			                ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && qsub ' modelname '.queue '];
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
 
-			if ~strcmpi(options.batch,'yes'),
-				
-				%compress the files into one zip.
-				compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
-				if md.qmu.isdakota,
-					compressstring=[compressstring md.miscellaneous.name '.qmu.in'];
-				end
-				system(compressstring);
-				
-				disp('uploading input file and queueing script');
-				issmscpout(md.cluster.name,md.cluster.executionpath,md.cluster.login,md.cluster.port,{[md.private.runtimename '.tar.gz']});
-				
-				disp('launching solution sequence on remote cluster');
-				issmssh(md.cluster.name,md.cluster.login,md.cluster.port,launchcommand);
+			 %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);
 
-			else
-				disp('batch mode requested: not launching job interactively');
-				disp('launch solution sequence on remote cluster by hand');
-			end
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
 
-		 end
-		 %}}}
-		 function Download(cluster,md)% {{{1
+			 disp('launching solution sequence on remote cluster');
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
 
-			%some check
-			if isempty(md.private.runtimename),
-				error('pfe Download error message: supply runtime name for results to be loaded!');
-			end
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
 
-			%Figure out the  directory where all the files are in: 
-			directory=[cluster.executionpath '/' md.private.runtimename '/'];
-
-			%What packages are we picking up from remote cluster
-			packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
-			if md.qmu.isdakota,
-				packages{end+1}=[md.miscellaneous.name '.qmu.err'];
-				packages{end+1}=[md.miscellaneous.name '.qmu.out'];
-				if isfield(md.qmu.params,'tabular_graphics_data'),
-					if md.qmu.params.tabular_graphics_data==true,
-						packages{end+1}='dakota_tabular.dat'; 
-					end
-				end
-			else
-				packages{end+1}=[md.miscellaneous.name '.outbin'];
-			end
-
-			%copy files from cluster to present directory
-			issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
-		end %}}}
+		 end %}}}
 	end
 end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/clusters/generic.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/generic.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/clusters/generic.m	(revision 12878)
@@ -6,199 +6,179 @@
 
 classdef generic
-    properties (SetAccess=public) 
-		 % {{{1
-		 name='';
-		 login='';
-		 np=1;
-		 port=0;
-		 interactive=1;
-		 codepath=[issmdir() '/bin'];
-		 executionpath=[issmdir() '/execution'];
-		 valgrind=[issmdir() '/externalpackages/valgrind/install/bin/valgrind'];
-		 valgrindlib=[issmdir() '/externalpackages/valgrind/install/lib/libmpidebug.so'];
-		 valgrindsup=[issmdir() '/externalpackages/valgrind/issm.supp'];
-		 %}}}
-	 end
-	 methods
-		 function cluster=generic(varargin) % {{{1
+	properties (SetAccess=public) 
+		% {{{
+		name='';
+		login='';
+		np=1;
+		port=0;
+		interactive=1;
+		codepath=[issmdir() '/bin'];
+		executionpath=[issmdir() '/execution'];
+		valgrind=[issmdir() '/externalpackages/valgrind/install/bin/valgrind'];
+		valgrindlib=[issmdir() '/externalpackages/valgrind/install/lib/libmpidebug.so'];
+		valgrindsup=[issmdir() '/externalpackages/valgrind/issm.supp'];
+		%}}}
+	end
+	methods
+		function cluster=generic(varargin) % {{{
 
-			 %use provided options to change fields
-			 options=pairoptions(varargin{:});
+			%use provided options to change fields
+			options=pairoptions(varargin{:});
 
-			 %get name
-			 cluster.name=getfieldvalue(options,'name',oshostname());
+			%get name
+			cluster.name=getfieldvalue(options,'name',oshostname());
 
-			 %initialize cluster using user settings if provided
-			 if (exist([cluster.name '_settings'])==2), eval([cluster.name '_settings']); end
+			%initialize cluster using user settings if provided
+			if (exist([cluster.name '_settings'])==2), eval([cluster.name '_settings']); end
 
-			 %OK get other fields
-			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
-		 end
-		 %}}}
-		 function disp(cluster) % {{{1
-			 %  display the object
-			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
-			 disp(sprintf('    name: %s',cluster.name));
-			 disp(sprintf('    login: %s',cluster.login));
-			 disp(sprintf('    np: %i',cluster.np));
-			 disp(sprintf('    port: %i',cluster.port));
-			 disp(sprintf('    codepath: %s',cluster.codepath));
-			 disp(sprintf('    executionpath: %s',cluster.executionpath));
-			 disp(sprintf('    valgrind: %s',cluster.valgrind));
-			 disp(sprintf('    valgrindlib: %s',cluster.valgrindlib));
-			 disp(sprintf('    valgrindsup: %s',cluster.valgrindsup));
-		 end
-		 %}}}
-		 function checkconsistency(cluster,md,solution,analyses) % {{{1
-			 if cluster.np<1
-				 checkmessage(['number of processors should be at least 1']);
-			 end
-			 if isnan(cluster.np),
-				 checkessage('number of processors should not be NaN!');
-			 end
-		 end
-		 %}}}
-		 function BuildQueueScript(cluster,md) % {{{1
-		 
-			 %retrieve parameters
-			 modelname=md.miscellaneous.name;
-			 solution=md.private.solution;
-			 isvalgrind=md.debug.valgrind;
-			 isgprof=md.debug.gprof;
+			%OK get other fields
+			cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		end
+		%}}}
+		function disp(cluster) % {{{
+			%  display the object
+			disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			disp(sprintf('    name: %s',cluster.name));
+			disp(sprintf('    login: %s',cluster.login));
+			disp(sprintf('    np: %i',cluster.np));
+			disp(sprintf('    port: %i',cluster.port));
+			disp(sprintf('    codepath: %s',cluster.codepath));
+			disp(sprintf('    executionpath: %s',cluster.executionpath));
+			disp(sprintf('    valgrind: %s',cluster.valgrind));
+			disp(sprintf('    valgrindlib: %s',cluster.valgrindlib));
+			disp(sprintf('    valgrindsup: %s',cluster.valgrindsup));
+		end
+		%}}}
+		function md = checkconsistency(cluster,md,solution,analyses) % {{{
+			if cluster.np<1
+				md = checkmessage(md,['number of processors should be at least 1']);
+			end
+			if isnan(cluster.np),
+				md = checkmessage(md,'number of processors should not be NaN!');
+			end
+		end
+		%}}}
+		function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
-			 %open file for writing: 
-			 if ~ispc,
-				 fid=fopen([modelname '.queue'],'w');
-			 else
-				 fid=fopen([modelname '.bat'],'w');
-			 end
+			%write queuing script 
+			if ~ispc,
 
-			 %write instructions for launching a job on the cluster
-			 if ~ispc,
-				 fprintf(fid,'#!/bin/sh\n');
-			 else
-				 fprintf(fid,'@echo off\n');
-			 end
-			 
-			 if ~isvalgrind,
-				 if cluster.interactive
-					 if ~ispc,
-						 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s ',cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
-					 else
-						 fprintf(fid,'"%s/issm.exe" %s "%s" %s ',cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
-					 end
-				 else
-					 if ~ispc,
-						 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
-					 else
-						 fprintf(fid,'"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog ',cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
-					 end
-				 end
-			 else
-				 if ~ispc,
-					 %Add --gen-suppressions=all to get suppression lines
-					 fprintf(fid,'LD_PRELOAD=%s \\\n',cluster.valgrindlib);
-					 fprintf(fid,'mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
-					 cluster.np,cluster.valgrind,cluster.valgrindsup, cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
-				 else
-					 error('valgrind not supported on windows platforms');
-				 end
-			 end
+				fid=fopen([modelname '.queue'],'w');
+				fprintf(fid,'#!/bin/sh\n');
+				if ~isvalgrind,
+					if cluster.interactive
+						fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s ',cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
+					else
+						fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
+					end
+				elseif isgprof,
+					fprintf(fid,'\n gprof %s/issm.exe gmon.out > %s.performance',cluster.codepath,modelname);
+				else
+					%Add --gen-suppressions=all to get suppression lines
+					fprintf(fid,'LD_PRELOAD=%s \\\n',cluster.valgrindlib);
+					fprintf(fid,'mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+						cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
+				end
+				if ~io_gather, %concatenate the output files:
+					fprintf(fid,'\ncat %s.outbin.* > %s.outbin',modelname,modelname);
+				end
+				fclose(fid);
 
-			 if isgprof,
-				 if ~ispc,
-					 fprintf(fid,'\n gprof %s/issm.exe gmon.out > %s.performance',cluster.codepath,modelname);
-				 else
-					 error('gprof not supported on windows platforms');
-				 end
+			else % Windows
 
-			 end
-
-			 if ~md.settings.io_gather,
-				 if ~ispc,
-					 %concatenate the output files:
-					 fprintf(fid,'\ncat %s.outbin.* > %s.outbin',modelname,modelname);
-				 else
-					 error('iogather not supported on windows platforms');
-				 end
-
-			 end
-			 
-			 %close file: 
-			 fclose(fid);
-
-			 %in interactive mode, create a run file, and errlog and outlog file
-			 if cluster.interactive,
-				 fid=fopen([modelname '.errlog'],'w'); fclose(fid);
-				 fid=fopen([modelname '.outlog'],'w'); fclose(fid);
-			 end
-
-
-		 end
-		 %}}}
-		 function LaunchQueueJob(cluster,md,options)% {{{1
-			 
-			 if ~ispc,
-					 %lauch command, to be executed via ssh
-					 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
-					 ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && source  ' md.miscellaneous.name '.queue '];
-
-					 if ~strcmpi(options.batch,'yes'),
-
-						 %compress the files into one zip.
-						 compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
-						 if md.qmu.isdakota,
-							 compressstring=[compressstring md.miscellaneous.name '.qmu.in'];
-					end
-					if cluster.interactive,
-						compressstring=[compressstring ' ' md.miscellaneous.name '.errlog ' md.miscellaneous.name '.outlog '];
-					end
-					system(compressstring);
-
-					disp('uploading input file and queueing script');
-					issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[md.private.runtimename '.tar.gz']});
-
-					disp('launching solution sequence on remote cluster');
-					issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+				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,modelname);
 				else
-					disp('batch mode requested: not launching job interactively');
-					disp('launch solution sequence on remote cluster by hand');
+					fprintf(fid,'"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog',...
+						cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
 				end
-			else
-				%launch right here, do not compress or archive.
-				system([md.miscellaneous.name '.bat']);
+				fclose(fid);
 			end
 
+			%in interactive mode, create a run file, and errlog and outlog file
+			if cluster.interactive,
+				fid=fopen([modelname '.errlog'],'w'); fclose(fid);
+				fid=fopen([modelname '.outlog'],'w'); fclose(fid);
+			end
+		end
+		%}}}
+		function BuildKrigingQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			%write queuing script 
+			if ~ispc,
+
+				fid=fopen([modelname '.queue'],'w');
+				fprintf(fid,'#!/bin/sh\n');
+				if ~isvalgrind,
+					if cluster.interactive
+						fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s ',cluster.np,cluster.codepath,cluster.executionpath,modelname);
+					else
+						fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s 2> %s.errlog >%s.outlog ',cluster.np,cluster.codepath,cluster.executionpath,modelname,modelname,modelname);
+					end
+				elseif isgprof,
+					fprintf(fid,'\n gprof %s/kriging.exe gmon.out > %s.performance',cluster.codepath,modelname);
+				else
+					%Add --gen-suppressions=all to get suppression lines
+					fprintf(fid,'LD_PRELOAD=%s \\\n',cluster.valgrindlib);
+					fprintf(fid,'mpiexec -np %i %s --leak-check=full --suppressions=%s %s/kriging.exe %s %s 2> %s.errlog >%s.outlog ',...
+						cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,cluster.executionpath,modelname,modelname,modelname);
+				end
+				if ~io_gather, %concatenate the output files:
+					fprintf(fid,'\ncat %s.outbin.* > %s.outbin',modelname,modelname);
+				end
+				fclose(fid);
+
+			else % Windows
+
+				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,modelname);
+				else
+					fprintf(fid,'"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog',...
+						cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
+				end
+				fclose(fid);
+			end
+
+			%in interactive mode, create a run file, and errlog and outlog file
+			if cluster.interactive,
+				fid=fopen([modelname '.errlog'],'w'); fclose(fid);
+				fid=fopen([modelname '.outlog'],'w'); fclose(fid);
+			end
+		end
+		%}}}
+		function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			%compress the files into one zip.
+			compressstring=['tar -zcf ' dirname '.tar.gz '];
+			for i=1:numel(filelist),
+				compressstring = [compressstring ' ' filelist{i}];
+			end
+			if cluster.interactive,
+				compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
+			end
+			system(compressstring);
+
+			disp('uploading input file and queueing script');
+			issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+			disp('launching solution sequence on remote cluster');
+			launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && source  ' modelname '.queue '];
+			issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
 		end %}}}
-		 function Download(cluster,md)% {{{1
+		function Download(cluster,dirname,filelist)% {{{
 
-			if ~ispc,
-				%some check
-				if isempty(md.private.runtimename),
-					error('supply runtime name for results to be loaded!');
-				end
+			if ispc,
+				%do nothing
+				return;
+			end
 
-				%Figure out the  directory where all the files are in: 
-				directory=[cluster.executionpath '/' md.private.runtimename '/'];
-
-				%What packages are we picking up from remote cluster
-				packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
-				if md.qmu.isdakota,
-					packages{end+1}=[md.miscellaneous.name '.qmu.err'];
-					packages{end+1}=[md.miscellaneous.name '.qmu.out'];
-					if isfield(md.qmu.params,'tabular_graphics_data'),
-						if md.qmu.params.tabular_graphics_data==true,
-							packages{end+1}='dakota_tabular.dat'; 
-						end
-					end
-				else
-					packages{end+1}=[md.miscellaneous.name '.outbin'];
-				end
-
-				%copy files from cluster to present directory
-				issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
-			else
-				%do nothing!
-			end
+			%copy files from cluster to current directory
+			directory=[cluster.executionpath '/' dirname '/'];
+			issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
 		end %}}}
 	end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/clusters/generic.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/generic.py	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/clusters/generic.py	(revision 12878)
@@ -1,14 +1,24 @@
-#GENERIC cluster class definition
-#
-#   Usage:
-#      cluster=generic('name','astrid',);
-#      cluster=generic('name','astrid','np',3);
-#      cluster=generic('name',oshostname(),'np',3,'login','username');
+import socket
+import os
+import math
+import platform
+import subprocess
+from issmdir import *
+from pairoptions import *
+from issmssh import *
+from issmscpin import *
+from issmscpout import *
 
+class generic(object):
+	"""
+	GENERIC cluster class definition
+ 
+	    Usage:
+	       cluster=generic('name','astrid','np',3);
+	       cluster=generic('name',oshostname(),'np',3,'login','username');
+	"""
 
-class generic:
-	#properties
-	def __init__(self):
-		# {{{ Properties
+	def __init__(self,*args):    # {{{
+
 		self.name=''
 		self.login=''
@@ -16,202 +26,160 @@
 		self.port=0
 		self.interactive=1
-		self.codepath=issmdir() + '/bin'
-		self.executionpath=issmdir() + '/execution'
-		self.valgrind=issmdir() + '/externalpackages/valgrind/install/bin/valgrind'
-		self.valgrindlib=issmdir() + '/externalpackages/valgrind/install/lib/libmpidebug.so'
-		self.valgrindsup=issmdir() + '/externalpackages/valgrind/issm.supp'
-		#}}}
-	def __repr__(obj):
-		# {{{ Display
-		
-		string="class 'generic' object:"
-		string="%s\n\n%s"%(string,"%s%s"%('    name: ',obj.name))
-		string="%s\n%s"%(string,"%s%i"%('    np: ',obj.np))
-		string="%s\n%s"%(string,"%s%i"%('    port: ',obj.port))
-		string="%s\n%s"%(string,"%s%s"%('    codepath: ',obj.codepath))
-		string="%s\n%s"%(string,"%s%s"%('    executionpath: ',obj.executionpath))
-		string="%s\n%s"%(string,"%s%s"%('    valgrind: ',obj.valgrind))
-		string="%s\n%s"%(string,"%s%s"%('    valgrindlib: ',obj.valgrindlib))
-		string="%s\n%s"%(string,"%s%s"%('    valgrindsup: ',obj.valgrindsup))
-		return string
-		#}}}
-		
+		self.codepath=issmdir()+'/bin'
+		self.executionpath=issmdir()+'/execution'
+		self.valgrind=issmdir()+'/externalpackages/valgrind/install/bin/valgrind'
+		self.valgrindlib=issmdir()+'/externalpackages/valgrind/install/lib/libmpidebug.so'
+		self.valgrindsup=issmdir()+'/externalpackages/valgrind/issm.supp'
 
-#old matlab
-#		function cluster=generic(varargin) % {{{1
-#
-#			 %use provided options to change fields
-#			 options=pairoptions(varargin{:});
-#
-#			 %get name
-#			 if ~exist(options,'name'), error('option ''name'' has not been provided'); end
-#			 cluster.name=getfieldvalue(options,'name');
-#
-#			 %initialize cluster using user settings if provided
-#			 if (exist([cluster.name '_settings'])==2), eval([cluster.name '_settings']); end
-#
-#			 %OK get other fields
-#			 for i=1:size(options.list,1),
-#				 fieldname=options.list{i,1};
-#				 fieldvalue=options.list{i,2};
-#				 if ismember(fieldname,properties('generic')),
-#					 cluster.(fieldname)=fieldvalue;
-#				 else
-#					 disp(['''' fieldname ''' is not a property of cluster generic']);
-#				 end
-#			 end
-#		 end
-#		 %}}}
-#		 function checkconsistency(cluster,md,solution,analyses) % {{{1
-#			 if cluster.np<1
-#				 checkmessage(['number of processors should be at least 1']);
-#			 end
-#			 if isnan(cluster.np),
-#				 checkessage('number of processors should not be NaN!');
-#			 end
-#		 end
-#		 %}}}
-#		 function BuildQueueScript(cluster,md) % {{{1
-#		 
-#			 %retrieve parameters
-#			 modelname=md.miscellaneous.name;
-#			 solution=md.private.solution;
-#			 isvalgrind=md.debug.valgrind;
-#			 isgprof=md.debug.gprof;
-#
-#			 %open file for writing: 
-#			 if ~ispc,
-#				 fid=fopen([modelname '.queue'],'w');
-#			 else
-#				 fid=fopen([modelname '.bat'],'w');
-#			 end
-#
-#			 %write instructions for launching a job on the cluster
-#			 if ~ispc,
-#				 fprintf(fid,'#!/bin/sh\n');
-#			 else
-#				 fprintf(fid,'@echo off\n');
-#			 end
-#			 
-#			 if ~isvalgrind,
-#				 if cluster.interactive
-#					 if ~ispc,
-#						 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s ',cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
-#					 else
-#						 fprintf(fid,'"%s/issm.exe" %s "%s" %s ',cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
-#					 end
-#				 else
-#					 if ~ispc,
-#						 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
-#					 else
-#						 fprintf(fid,'"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog ',cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
-#					 end
-#				 end
-#			 else
-#				 if ~ispc,
-#					 %Add --gen-suppressions=all to get suppression lines
-#					 fprintf(fid,'LD_PRELOAD=%s \\\n',cluster.valgrindlib);
-#					 fprintf(fid,'mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
-#					 cluster.np,cluster.valgrind,cluster.valgrindsup, cluster.codepath,EnumToString(solution),cluster.executionpath,modelname,modelname,modelname);
-#				 else
-#					 error('valgrind not supported on windows platforms');
-#				 end
-#			 end
-#
-#			 if isgprof,
-#				 if ~ispc,
-#					 fprintf(fid,'\n gprof %s/issm.exe gmon.out > %s.performance',cluster.codepath,modelname);
-#				 else
-#					 error('gprof not supported on windows platforms');
-#				 end
-#
-#			 end
-#
-#			 if ~md.settings.io_gather,
-#				 if ~ispc,
-#					 %concatenate the output files:
-#					 fprintf(fid,'\ncat %s.outbin.* > %s.outbin',modelname,modelname);
-#				 else
-#					 error('iogather not supported on windows platforms');
-#				 end
-#
-#			 end
-#			 
-#			 %close file: 
-#			 fclose(fid);
-#
-#			 %in interactive mode, create a run file, and errlog and outlog file
-#			 if cluster.interactive,
-#				 fid=fopen([modelname '.errlog'],'w'); fclose(fid);
-#				 fid=fopen([modelname '.outlog'],'w'); fclose(fid);
-#			 end
-#
-#
-#		 end
-#		 %}}}
-#		 function LaunchQueueJob(cluster,md,options)% {{{1
-#			 
-#			 if ~ispc,
-#					 %lauch command, to be executed via ssh
-#					 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
-#					 ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && source  ' md.miscellaneous.name '.queue '];
-#
-#					 if ~strcmpi(options.batch,'yes'),
-#
-#						 %compress the files into one zip.
-#						 compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
-#						 if md.qmu.isdakota,
-#							 compressstring=[compressstring md.miscellaneous.name '.qmu.in'];
-#					end
-#					if cluster.interactive,
-#						compressstring=[compressstring ' ' md.miscellaneous.name '.errlog ' md.miscellaneous.name '.outlog '];
-#					end
-#					system(compressstring);
-#
-#					disp('uploading input file and queueing script');
-#					issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[md.private.runtimename '.tar.gz']});
-#
-#					disp('launching solution sequence on remote cluster');
-#					issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
-#				else
-#					disp('batch mode requested: not launching job interactively');
-#					disp('launch solution sequence on remote cluster by hand');
-#				end
-#			else
-#				%launch right here, do not compress or archive.
-#				system([md.miscellaneous.name '.bat']);
-#			end
-#
-#		end %}}}
-#		 function Download(cluster,md)% {{{1
-#
-#			if ~ispc,
-#				%some check
-#				if isempty(md.private.runtimename),
-#					error('supply runtime name for results to be loaded!');
-#				end
-#
-#				%Figure out the  directory where all the files are in: 
-#				directory=[cluster.executionpath '/' md.private.runtimename '/'];
-#
-#				%What packages are we picking up from remote cluster
-#				packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
-#				if md.qmu.isdakota,
-#					packages{end+1}=[md.miscellaneous.name '.qmu.err'];
-#					packages{end+1}=[md.miscellaneous.name '.qmu.out'];
-#					if isfield(md.qmu.params,'tabular_graphics_data'),
-#						if md.qmu.params.tabular_graphics_data==true,
-#							packages{end+1}='dakota_tabular.dat'; 
-#						end
-#					end
-#				else
-#					packages{end+1}=[md.miscellaneous.name '.outbin'];
-#				end
-#
-#				%copy files from cluster to present directory
-#				issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
-#			else
-#				%do nothing!
-#			end
-#		end %}}}
-#
+		#use provided options to change fields
+		options=pairoptions(*args)
+
+		#get name
+		self.name=options.getfieldvalue('name',socket.gethostname().lower().split('.')[0])
+
+		#initialize cluster using user settings if provided
+		if os.path.exists(self.name+'_settings.py'):
+			execfile(self.name+'_settings.py',globals())
+
+		#OK get other fields
+		self=options.AssignObjectFields(self)
+	# }}}
+
+	def __repr__(self):    # {{{
+		#  display the object
+		s ="class '%s' object '%s' = \n" % (type(self),'self')
+		s+="    name: %s\n" % self.name
+		s+="    login: %s\n" % self.login
+		s+="    np: %i\n" % self.np
+		s+="    port: %i\n" % self.port
+		s+="    codepath: %s\n" % self.codepath
+		s+="    executionpath: %s\n" % self.executionpath
+		s+="    valgrind: %s\n" % self.valgrind
+		s+="    valgrindlib: %s\n" % self.valgrindlib
+		s+="    valgrindsup: %s\n" % self.valgrindsup
+		return s
+	# }}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		if self.np<1:
+			md = checkmessage(md,'number of processors should be at least 1')
+		if math.isnan(self.np):
+			md = checkmessage(md,'number of processors should not be NaN!')
+
+		return md
+	# }}}
+
+	def BuildQueueScript(self,dirname,modelname,solution,io_gather,isvalgrind,isgprof):    # {{{
+
+		#write queuing script 
+		if not 'Windows' in platform.system():
+
+			fid=open(modelname+'.queue','w')
+			fid.write('#!/bin/sh\n')
+			if not isvalgrind:
+				if self.interactive:
+					fid.write('mpiexec -np %i %s/issm.exe %s %s %s ' % (self.np,self.codepath,EnumToString(solution),self.executionpath,modelname))
+				else:
+					fid.write('mpiexec -np %i %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,EnumToString(solution),self.executionpath,modelname,modelname,modelname))
+			elif isgprof:
+				fid.write('\n gprof %s/issm.exe gmon.out > %s.performance' % (self.codepath,modelname))
+			else:
+				#Add --gen-suppressions=all to get suppression lines
+				fid.write('LD_PRELOAD=%s \\\n' % self.valgrindlib)
+				fid.write('mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ' % \
+					(self.np,self.valgrind,self.valgrindsup,self.codepath,EnumToString(solution),self.executionpath,modelname,modelname,modelname))
+			if not io_gather:    #concatenate the output files:
+				fid.write('\ncat %s.outbin.* > %s.outbin' % (modelname,modelname))
+			fid.close()
+
+		else:    # Windows
+
+			fid=open(modelname+'.bat','w')
+			fid.write('@echo off\n')
+			if self.interactive:
+				fid.write('"%s/issm.exe" %s "%s" %s ' % (self.codepath,EnumToString(solution),self.executionpath,modelname))
+			else:
+				fid.write('"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog' % \
+					(self.codepath,EnumToString(solution),self.executionpath,modelname,modelname,modelname))
+			fid.close()
+
+		#in interactive mode, create a run file, and errlog and outlog file
+		if self.interactive:
+			fid=open(modelname+'.errlog','w')
+			fid.close()
+			fid=open(modelname+'.outlog','w')
+			fid.close()
+	# }}}
+
+	def BuildKrigingQueueScript(self,modelname,solution,io_gather,isvalgrind,isgprof):    # {{{
+
+		#write queuing script 
+		if not 'Windows' in platform.system():
+
+			fid=open(modelname+'.queue','w')
+			fid.write('#!/bin/sh\n')
+			if not isvalgrind:
+				if self.interactive:
+					fid.write('mpiexec -np %i %s/kriging.exe %s %s ' % (self.np,self.codepath,self.executionpath,modelname))
+				else:
+					fid.write('mpiexec -np %i %s/kriging.exe %s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,self.executionpath,modelname,modelname,modelname))
+			elif isgprof:
+				fid.write('\n gprof %s/kriging.exe gmon.out > %s.performance' & (self.codepath,modelname))
+			else:
+				#Add --gen-suppressions=all to get suppression lines
+				fid.write('LD_PRELOAD=%s \\\n' % self.valgrindlib)
+				fid.write('mpiexec -np %i %s --leak-check=full --suppressions=%s %s/kriging.exe %s %s 2> %s.errlog >%s.outlog ' % \
+					(self.np,self.valgrind,self.valgrindsup,self.codepath,self.executionpath,modelname,modelname,modelname))
+			if not io_gather:    #concatenate the output files:
+				fid.write('\ncat %s.outbin.* > %s.outbin' % (modelname,modelname))
+			fid.close()
+
+		else:    # Windows
+
+			fid=open(modelname+'.bat','w')
+			fid.write('@echo off\n')
+			if self.interactive:
+				fid.write('"%s/issm.exe" %s "%s" %s ' % (self.codepath,EnumToString(solution),self.executionpath,modelname))
+			else:
+				fid.write('"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog' % \
+					(self.codepath,EnumToString(solution),self.executionpath,modelname,modelname,modelname))
+			fid.close()
+
+		#in interactive mode, create a run file, and errlog and outlog file
+		if self.interactive:
+			fid=open(modelname+'.errlog','w')
+			fid.close()
+			fid=open(modelname+'.outlog','w')
+			fid.close()
+	# }}}
+
+	def LaunchQueueJob(self,modelname,dirname,filelist):    # {{{
+
+		#compress the files into one zip.
+		compressstring='tar -zcf %s.tar.gz ' % dirname
+		for file in filelist:
+			compressstring += ' %s' % file
+		if self.interactive:
+			compressstring += ' %s.errlog %s.outlog ' % (modelname,modelname)
+		subprocess.call(compressstring,shell=True)
+
+		print 'uploading input file and queueing script'
+		issmscpout(self.name,self.executionpath,self.login,self.port,[dirname+'.tar.gz'])
+
+		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)
+		issmssh(self.name,self.login,self.port,launchcommand)
+	# }}}
+
+	def Download(self,dirname,filelist):     # {{{
+
+		if 'Windows' in platform.system():
+			#do nothing
+			return
+
+		#copy files from cluster to current directory
+		directory='%s/%s/' % (self.executionpath,dirname)
+		issmscpin(self.name,self.login,self.port,directory,filelist)
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/clusters/greenplanet.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/greenplanet.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/clusters/greenplanet.m	(revision 12878)
@@ -8,5 +8,5 @@
 classdef greenplanet
     properties (SetAccess=public)  
-		 % {{{1
+		 % {{{
 		 name='greenplanet'
 		 login='';
@@ -24,5 +24,5 @@
 	 end
 	 methods
-		 function cluster=greenplanet(varargin) % {{{1
+		 function cluster=greenplanet(varargin) % {{{
 
 			 %initialize cluster using default settings if provided
@@ -33,5 +33,5 @@
 		 end
 		 %}}}
-		 function disp(cluster) % {{{1
+		 function disp(cluster) % {{{
 			 %  display the object
 			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
@@ -48,5 +48,5 @@
 		 end
 		 %}}}
-		 function checkconsistency(cluster,md,solution,analyses) % {{{1
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
 
 			 available_queues={'rignot','default'};
@@ -57,23 +57,20 @@
 
 			 %Miscelaneous
-			 if isempty(cluster.login), checkmessage('login empty'); end
-			 if isempty(cluster.codepath), checkmessage('codepath empty'); end
-			 if isempty(cluster.executionpath), checkmessage('executionpath empty'); end
+			 if isempty(cluster.login), md = checkmessage(md,'login empty'); end
+			 if isempty(cluster.codepath), md = checkmessage(md,'codepath empty'); end
+			 if isempty(cluster.executionpath), md = checkmessage(md,'executionpath empty'); end
 
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,md) % {{{1
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
-			 %retrieve parameters 
-			 modelname=md.miscellaneous.name; 
-			 solution=md.private.solution;
-			 isvalgrind=md.debug.valgrind;
+			 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;
 
-			 %open file for writing: 
+			 %write queuing script 
 			 fid=fopen([modelname '.queue'],'w');
-
 			 fprintf(fid,'#PBS -S /bin/bash\n');
 			 fprintf(fid,'#PBS -N %s\n',modelname);
@@ -84,14 +81,9 @@
 			 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,md.private.runtimename);
+			 fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,dirname);
 			 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
-
-			 if ~md.settings.io_gather,
-				 %concatenate the output files:
+			 if ~io_gather, %concatenate the output files:
 				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
 			 end
-
-			 %close file
 			 fclose(fid);
 
@@ -100,7 +92,5 @@
 				 fid=fopen([modelname '.run'],'w');
 				 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
-
-				 if ~md.settings.io_gather,
-					 %concatenate the output files:
+				 if ~io_gather, %concatenate the output files:
 					 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
 				 end
@@ -112,82 +102,31 @@
 			 end
 		 end %}}}
-		 function LaunchQueueJob(cluster,md,options)% {{{1
-			 
-			 %lauch command, to be executed via ssh
-			 if ~cluster.interactive, 
-				launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
-			                ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && qsub ' md.miscellaneous.name '.queue '];
-			else
-				launchcommand=['cd ' cluster.executionpath '/Interactive' num2str(cluster.interactive) ' && tar -zxf ' md.private.runtimename '.tar.gz'];
-			end
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
 
-			if ~strcmpi(options.batch,'yes'),
-				
-				%compress the files into one zip.
-				compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
-				if md.qmu.isdakota,
-					compressstring=[compressstring md.miscellaneous.name '.qmu.in '];
-				end
-				if cluster.interactive,
-					compressstring=[compressstring md.miscellaneous.name '.run ' md.miscellaneous.name '.errlog ' md.miscellaneous.name '.outlog '];
-				end
-				system(compressstring);
-				
-				disp('uploading input file and queueing script');
-				if cluster.interactive,
-					directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive)];
-				else 
-					directory=cluster.executionpath;
-				end
-				
-				issmscpout(cluster.name,directory,cluster.login,cluster.port,{[md.private.runtimename '.tar.gz']});
-				
-				disp('launching solution sequence on remote cluster');
-				issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+			 %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);
 
-			else
-				disp('batch mode requested: not launching job interactively');
-				disp('launch solution sequence on remote cluster by hand');
-			end
-		 end
-		 %}}}
-		 function Download(cluster,md)% {{{1
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
 
-			%some check
-			if isempty(md.private.runtimename),
-				if ~cluster.interactive,
-					error('greenplanet Download error message: supply runtime name for results to be loaded!');
-				end
-			end
+			 disp('launching solution sequence on remote cluster');
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
 
-			%Figure out the  directory where all the files are in: 
-			if ~cluster.interactive,
-				directory=[cluster.executionpath '/' md.private.runtimename '/'];
-			else
-				directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive) '/'];
-			end
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
 
-			%What packages are we picking up from remote cluster
-			if ~cluster.interactive,
-				packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
-			else
-				packages={};
-			end
-			if md.qmu.isdakota,
-				packages{end+1}=[md.miscellaneous.name '.qmu.err'];
-				packages{end+1}=[md.miscellaneous.name '.qmu.out'];
-				if isfield(md.qmu.params,'tabular_graphics_data'),
-					if md.qmu.params.tabular_graphics_data==true,
-						packages{end+1}='dakota_tabular.dat'; 
-					end
-				end
-			else
-				packages{end+1}=[md.miscellaneous.name '.outbin'];
-			end
-
-			%copy files from cluster to present directory
-			issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
-
-		end %}}}
+		 end %}}}
 	end
 end
Index: sm/branches/trunk-jpl-damage/src/m/classes/clusters/none.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/none.m	(revision 12877)
+++ 	(revision )
@@ -1,18 +1,0 @@
-%NONE class definition
-%
-%   Usage:
-%      cluster=none();
-%      cluster=none('np',3);
-%      cluster=none('np',3,'login','username');
-
-classdef none
-    properties (SetAccess=public)
-		name='none'
-    end
-    methods
-		 function cluster=none(varargin) % {{{1
-			 error('Cannot assign md.cluster to ''none'': ISSM is not available in serial model anymore');
-		 end
-		 %}}}
-	end
-end
Index: sm/branches/trunk-jpl-damage/src/m/classes/clusters/none.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/none.py	(revision 12877)
+++ 	(revision )
@@ -1,24 +1,0 @@
-#NONE cluster class definition
-#
-#   Usage:
-#      cluster=none();
-#      cluster=none('np',3);
-#      cluster=none('np',3,'login','username');
-
-class none:
-	#properties
-	def __init__(self):
-		# {{{ Properties
-		self.name='none'
-		#}}}
-	def __repr__(obj):
-		# {{{ Display
-		
-		string="class 'none' object:"
-		string="%s\n\n%s"%(string,"%s%s"%('    name: ',obj.name))
-		return string
-		#}}}
-	def checkconsistency(cluster,md,solution,analyses):
-		pass
-	def BuildQueueScript(cluster,md):
-			 raise RuntimeError('none.BuildQueueScript error message: serial cluster cannot build queue script')
Index: /issm/branches/trunk-jpl-damage/src/m/classes/clusters/pfe.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/pfe.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/clusters/pfe.m	(revision 12878)
@@ -8,5 +8,5 @@
 classdef pfe
     properties (SetAccess=public)  
-		 % {{{1
+		 % {{{
 		 name='pfe'
 		 login='';
@@ -29,5 +29,5 @@
 	 end
 	 methods
-		 function cluster=pfe(varargin) % {{{1
+		 function cluster=pfe(varargin) % {{{
 
 			 %initialize cluster using default settings if provided
@@ -38,5 +38,5 @@
 		 end
 		 %}}}
-		 function disp(cluster) % {{{1
+		 function disp(cluster) % {{{
 			 %  display the object
 			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
@@ -56,5 +56,5 @@
 		 end
 		 %}}}
-		 function checkconsistency(cluster,md,solution,analyses) % {{{1
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
 
 			 available_queues={'long','normal','debug'};
@@ -68,9 +68,9 @@
 				 if cluster.hyperthreading,
 					 if ((cluster.cpuspernode>16 ) | (cluster.cpuspernode<1)),
-						 checkmessage('cpuspernode should be between 1 and 16 for ''neh'' and ''har'' processors in hyperthreading mode');
+						 md = checkmessage(md,'cpuspernode should be between 1 and 16 for ''neh'' and ''har'' processors in hyperthreading mode');
 					 end
 				 else
 					 if ((cluster.cpuspernode>8 ) | (cluster.cpuspernode<1)),
-						 checkmessage('cpuspernode should be between 1 and 8 for ''neh'' and ''har'' processors');
+						 md = checkmessage(md,'cpuspernode should be between 1 and 8 for ''neh'' and ''har'' processors');
 					 end
 				 end
@@ -78,35 +78,31 @@
 				 if cluster.hyperthreading,
 					 if ((cluster.cpuspernode>24 ) | (cluster.cpuspernode<1)),
-						 checkmessage('cpuspernode should be between 1 and 24 for ''wes'' processors in hyperthreading mode');
+						 md = checkmessage(md,'cpuspernode should be between 1 and 24 for ''wes'' processors in hyperthreading mode');
 					 end
 				 else
 					 if ((cluster.cpuspernode>12 ) | (cluster.cpuspernode<1)),
-						 checkmessage('cpuspernode should be between 1 and 12 for ''wes'' processors');
-					 end
-				 end
-			 else
-				 checkmessage('unknown processor type, should be ''neh'',''wes'' or ''har''');
+						 md = checkmessage(md,'cpuspernode should be between 1 and 12 for ''wes'' processors');
+					 end
+				 end
+			 else
+				 md = checkmessage(md,'unknown processor type, should be ''neh'',''wes'' or ''har''');
 			 end
 
 			 %Miscelaneous
-			 if isempty(cluster.login), checkmessage('login empty'); end
-			 if isempty(cluster.codepath), checkmessage('codepath empty'); end
-			 if isempty(cluster.executionpath), checkmessage('executionpath empty'); end
-
-		 end
-		 %}}}
-		 function BuildQueueScript(cluster,md) % {{{1
-
-			 %retrieve parameters 
-			 modelname=md.miscellaneous.name; 
-			 solution=md.private.solution;
-			 isvalgrind=md.debug.valgrind;
+			 if isempty(cluster.login), md = checkmessage(md,'login empty'); end
+			 if isempty(cluster.codepath), md = checkmessage(md,'codepath empty'); end
+			 if isempty(cluster.executionpath), md = checkmessage(md,'executionpath empty'); end
+
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
 
 			 %compute number of processors
 			 cluster.np=cluster.numnodes*cluster.cpuspernode;
 
-			 %open file for writing: 
+			 %write queuing script 
 			 fid=fopen([modelname '.queue'],'w');
-
 			 fprintf(fid,'#PBS -S /bin/bash\n');
 %			 fprintf(fid,'#PBS -N %s\n',modelname);
@@ -118,24 +114,15 @@
 			 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 math/intel_mkl_64_10.0.011\n\n');
-
 			 fprintf(fid,'export PATH="$PATH:."\n\n');
 			 fprintf(fid,'export MPI_GROUP_MAX=64\n\n');
-
 			 fprintf(fid,'cd $PBS_O_WORKDIR\n\n');
-
 			 fprintf(fid,'mpiexec -np %i %s/issm.exe %s $PBS_O_WORKDIR %s\n',cluster.np,cluster.codepath,EnumToString(solution),modelname);
-
-			 if ~md.settings.io_gather,
-				 %concatenate the output files:
+			 if ~io_gather, %concatenate the output files:
 				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
 			 end
-
-			 %close file
 			 fclose(fid);
 
@@ -148,7 +135,5 @@
 					 fprintf(fid,'mpiexec -np %i valgrind --leak-check=full %s/issm.exe %s $PBS_O_WORKDIR %s\n',cluster.np,cluster.codepath,EnumToString(solution),modelname);
 				 end
-
-				 if ~md.settings.io_gather,
-					 %concatenate the output files:
+				 if ~io_gather, %concatenate the output files:
 					 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
 				 end
@@ -160,90 +145,57 @@
 			 end
 		 end %}}}
-		 function LaunchQueueJob(cluster,md,options)% {{{1
-			 
+		 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 '.run '  modelname '.errlog ' modelname '.outlog '];
+			 end
+			 system(compressstring);
+
+			 disp('uploading input file and queueing script');
+			 if cluster.interactive,
+				 directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive)];
+			 else 
+				 directory=cluster.executionpath;
+			 end
+
+			 if ~cluster.bbftp,
+				 issmscpout(cluster.name,directory,cluster.login,cluster.port,{[dirname '.tar.gz']});
+			 else
+				 issmbbftpout(cluster.name,directory,cluster.login,cluster.port,cluster.numstreams,{[dirname '.tar.gz']});
+			 end
+
 			 %lauch command, to be executed via ssh
 			 if ~cluster.interactive, 
-				launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
-			                ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && qsub ' md.miscellaneous.name '.queue '];
-			else
-				launchcommand=['cd ' cluster.executionpath '/Interactive' num2str(cluster.interactive) ' && tar -zxf ' md.private.runtimename '.tar.gz'];
-			end
-
-			if ~strcmpi(options.batch,'yes'),
-				
-				%compress the files into one zip.
-				compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
-				if md.qmu.isdakota,
-					compressstring=[compressstring md.miscellaneous.name '.qmu.in '];
-				end
-				if cluster.interactive,
-					compressstring=[compressstring md.miscellaneous.name '.run ' md.miscellaneous.name '.errlog ' md.miscellaneous.name '.outlog '];
-				end
-				system(compressstring);
-				
-				disp('uploading input file and queueing script');
-				if cluster.interactive,
-					directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive)];
-				else 
-					directory=cluster.executionpath;
-				end
-				
-				if ~cluster.bbftp,
-					issmscpout(cluster.name,directory,cluster.login,cluster.port,{[md.private.runtimename '.tar.gz']});
-				else
-					issmbbftpout(cluster.name,directory,cluster.login,cluster.port,cluster.numstreams,{[md.private.runtimename '.tar.gz']});
-				end
-				
-				disp('launching solution sequence on remote cluster');
-				issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
-
-			else
-				disp('batch mode requested: not launching job interactively');
-				disp('launch solution sequence on remote cluster by hand');
-			end
-		 end
-		 %}}}
-		 function Download(cluster,md)% {{{1
-
-			%some check
-			if isempty(md.private.runtimename),
-				if ~cluster.interactive,
-					error('pfe Download error message: supply runtime name for results to be loaded!');
-				end
-			end
-
-			%Figure out the  directory where all the files are in: 
-			if ~cluster.interactive,
-				directory=[cluster.executionpath '/' md.private.runtimename '/'];
-			else
-				directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive) '/'];
-			end
-
-			%What packages are we picking up from remote cluster
-			if ~cluster.interactive,
-				packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
-			else
-				packages={};
-			end
-			if md.qmu.isdakota,
-				packages{end+1}=[md.miscellaneous.name '.qmu.err'];
-				packages{end+1}=[md.miscellaneous.name '.qmu.out'];
-				if isfield(md.qmu.params,'tabular_graphics_data'),
-					if md.qmu.params.tabular_graphics_data==true,
-						packages{end+1}='dakota_tabular.dat'; 
-					end
-				end
-			else
-				packages{end+1}=[md.miscellaneous.name '.outbin'];
-			end
-
-			%copy files from cluster to present directory
-			if ~cluster.bbftp,
-				issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
-			else
-				issmbbftpin(cluster.name, cluster.login, cluster.port, cluster.numstreams, directory, packages);
-			end
-
-		end %}}}
+				 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+					 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 else
+				 launchcommand=['cd ' cluster.executionpath '/Interactive' num2str(cluster.interactive) ' && tar -zxf ' dirname '.tar.gz'];
+			 end
+
+			 disp('launching solution sequence on remote cluster');
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end
+		 %}}}
+		 function Download(cluster,dirname,filelist)% {{{
+
+			 %copy files from cluster to current directory
+			 if ~cluster.interactive,
+				 directory=[cluster.executionpath '/' dirname '/'];
+			 else
+				 directory=[cluster.executionpath '/Interactive' num2str(cluster.interactive) '/'];
+			 end
+
+			 if ~cluster.bbftp,
+				 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+			 else
+				 issmbbftpin(cluster.name, cluster.login, cluster.port, cluster.numstreams, directory, filelist);
+			 end
+
+		 end %}}}
 	end
 end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/clusters/pollux.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/clusters/pollux.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/clusters/pollux.m	(revision 12878)
@@ -8,5 +8,5 @@
 classdef pollux
     properties (SetAccess=public) 
-		 % {{{1
+		 % {{{
 		 name='pollux'
 		 login='username';
@@ -20,9 +20,9 @@
 	 end
 	 methods
-		 function cluster=pollux(varargin) % {{{1
+		 function cluster=pollux(varargin) % {{{
 			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
 		 end
 		 %}}}
-		 function disp(cluster) % {{{1
+		 function disp(cluster) % {{{
 			 %  display the object
 			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
@@ -37,5 +37,5 @@
 		 end
 		 %}}}
-		 function checkconsistency(cluster,md,solution,analyses) % {{{1
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
 
 			 available_queues={'shortp','longp'};
@@ -46,13 +46,11 @@
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,md) % {{{1
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
-			 %retrieve parameters 
-			 modelname=md.miscellaneous.name; 
-			 solution=md.private.solution;
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
 
-			 %open file for writing: 
+			 %write queuing script 
 			 fid=fopen([modelname '.queue'],'w');
-
 			 fprintf(fid,'#!/bin/sh\n');
 			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60); %walltime is in seconds.
@@ -64,70 +62,39 @@
 			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
 			 fprintf(fid,'#PBS -e %s.errlog \n',modelname);
-
 			 fprintf(fid,'export PBS_O_WORKDIR=%s\n',cluster.executionpath);
 			 fprintf(fid,'cd $PBS_O_WORKDIR\n');
 			 fprintf(fid,'export OMP_NUM_THREADS=1\n');
 			 fprintf(fid,'dplace -s1 -c0-%i mpiexec -np %i %s/issm.exe %s %s %s',cluster.np-1,cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
-
-			 %close file
 			 fclose(fid);
 
 		 end
 		 %}}}
-		 function LaunchQueueJob(cluster,md,options)% {{{1
-			 
-			 %lauch command, to be executed via ssh
-			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' md.private.runtimename ' && mkdir ' md.private.runtimename ...
-			                ' && cd ' md.private.runtimename ' && mv ../' md.private.runtimename '.tar.gz ./ && tar -zxf ' md.private.runtimename '.tar.gz  && qsub ' modelname '.queue '];
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
 
-			if ~strcmpi(options.batch,'yes'),
-				
-				%compress the files into one zip.
-				compressstring=['tar -zcf ' md.private.runtimename '.tar.gz ' md.miscellaneous.name '.bin ' md.miscellaneous.name '.queue '  md.miscellaneous.name '.petsc '];
-				if md.qmu.isdakota,
-					compressstring=[compressstring md.miscellaneous.name '.qmu.in'];
-				end
-				system(compressstring);
-				
-				disp('uploading input file and queueing script');
-				issmscpout(md.cluster.name,md.cluster.executionpath,md.cluster.login,md.cluster.port,{[md.private.runtimename '.tar.gz']});
-				
-				disp('launching solution sequence on remote cluster');
-				issmssh(md.cluster.name,md.cluster.login,md.cluster.port,launchcommand);
+			 %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);
 
-			else
-				disp('batch mode requested: not launching job interactively');
-				disp('launch solution sequence on remote cluster by hand');
-			end
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
 
-		 end
-		 %}}}
-		 function Download(cluster,md)% {{{1
+			 disp('launching solution sequence on remote cluster');
+			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
 
-			%some check
-			if isempty(md.private.runtimename),
-				error('pfe Download error message: supply runtime name for results to be loaded!');
-			end
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
 
-			%Figure out the  directory where all the files are in: 
-			directory=[cluster.executionpath '/' md.private.runtimename '/'];
-
-			%What packages are we picking up from remote cluster
-			packages={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
-			if md.qmu.isdakota,
-				packages{end+1}=[md.miscellaneous.name '.qmu.err'];
-				packages{end+1}=[md.miscellaneous.name '.qmu.out'];
-				if isfield(md.qmu.params,'tabular_graphics_data'),
-					if md.qmu.params.tabular_graphics_data==true,
-						packages{end+1}='dakota_tabular.dat'; 
-					end
-				end
-			else
-				packages{end+1}=[md.miscellaneous.name '.outbin'];
-			end
-
-			%copy files from cluster to present directory
-			issmscpin(cluster.name, cluster.login, cluster.port, directory, packages);
-		end %}}}
+		 end %}}}
 	end
 end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/constants.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/constants.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/constants.m	(revision 12878)
@@ -31,9 +31,9 @@
 
 		end % }}}
-		function flag = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			checkfield(md,'constants.g','>',0,'size',[1 1]);
-			checkfield(md,'constants.yts','>',0,'size',[1 1]);
-			checkfield(md,'constants.referencetemperature','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]);
 
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/debug.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/debug.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/debug.m	(revision 12878)
@@ -8,5 +8,5 @@
 		valgrind = false;
 		gprof    = false;
-		petsc_profiling = false;
+		profiling = false;
 	end
 	methods
@@ -27,9 +27,9 @@
 			fielddisplay(obj,'valgrind','use Valgrind to debug (0 or 1)');
 			fielddisplay(obj,'gprof','use gnu-profiler to find out where the time is spent');
-			fielddisplay(obj,'petsc_profiling','enables PETSc profiling (memory, flops, time)');
+			fielddisplay(obj,'profiling','enables profiling (memory, flops, time)');
 
 		end % }}}
 		function marshall(obj,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','petsc_profiling','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','profiling','format','Boolean');
 		end % }}}
 	end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/diagnostic.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/diagnostic.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/diagnostic.m	(revision 12878)
@@ -64,5 +64,5 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			%Early return
@@ -70,32 +70,32 @@
 			%if ~ismember(DiagnosticHorizAnalysisEnum,analyses) |  (solution==TransientSolutionEnum & md.transient.isdiagnostic==0), return; end
 
-			checkfield(md,'diagnostic.spcvx','forcing',1);
-			checkfield(md,'diagnostic.spcvy','forcing',1);
-			if md.mesh.dimension==3, checkfield(md,'diagnostic.spcvz','forcing',1); end
-			checkfield(md,'diagnostic.restol','size',[1 1],'>',0);
-			checkfield(md,'diagnostic.reltol','size',[1 1]);
-			checkfield(md,'diagnostic.abstol','size',[1 1]);
-			checkfield(md,'diagnostic.isnewton','numel',1,'values',[0 1]);
-			checkfield(md,'diagnostic.stokesreconditioning','size',[1 1],'NaN',1);
-			checkfield(md,'diagnostic.viscosity_overshoot','size',[1 1],'NaN',1);
+			md = checkfield(md,'diagnostic.spcvx','forcing',1);
+			md = checkfield(md,'diagnostic.spcvy','forcing',1);
+			if md.mesh.dimension==3, md = checkfield(md,'diagnostic.spcvz','forcing',1); end
+			md = checkfield(md,'diagnostic.restol','size',[1 1],'>',0);
+			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.stokesreconditioning','size',[1 1],'NaN',1);
+			md = checkfield(md,'diagnostic.viscosity_overshoot','size',[1 1],'NaN',1);
 			if md.mesh.dimension==2,
-				checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
+				md = checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
 			else
-				checkfield(md,'diagnostic.icefront','size',[NaN 6],'NaN',1);
+				md = checkfield(md,'diagnostic.icefront','size',[NaN 6],'NaN',1);
 			end
-			checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
-			checkfield(md,'diagnostic.maxiter','size',[1 1],'>=',1);
-			checkfield(md,'diagnostic.referential','size',[md.mesh.numberofvertices 6]);
+			md = checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
+			md = checkfield(md,'diagnostic.maxiter','size',[1 1],'>=',1);
+			md = checkfield(md,'diagnostic.referential','size',[md.mesh.numberofvertices 6]);
 			if ~isempty(md.diagnostic.requested_outputs),
-				checkfield(md,'diagnostic.requested_outputs','size',[NaN 1]);
+				md = checkfield(md,'diagnostic.requested_outputs','size',[NaN 1]);
 			end
 
 			%singular solution
 			if ~any((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy))==2),
-				checkmessage(['model ' md.miscellaneous.name ' is not well posed (singular). You need at least one node with fixed velocity!'])
+				md = checkmessage(md,['model is not well posed (singular). You need at least one node with fixed velocity!']);
 			end
 			%CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES
 			if any(sum(isnan(md.diagnostic.referential),2)~=0 & sum(isnan(md.diagnostic.referential),2)~=6),
-				checkmessage(['model ' md.miscellaneous.name ' has problem with rotated spc. Each line of diagnostic.referential should contain either only NaN values or no NaN values']);
+				md = checkmessage(md,['Each line of diagnostic.referential should contain either only NaN values or no NaN values']);
 			end
 			%CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL
@@ -103,5 +103,5 @@
 				pos=find(sum(isnan(md.diagnostic.referential),2)==0);
 				if any(abs(dot(md.diagnostic.referential(pos,1:3)',md.diagnostic.referential(pos,4:6)'))>eps),
-					checkmessage(['model ' md.miscellaneous.name ' has problem with referential. Vectors in diagnostic.referential (colums 1 to 3 and 4 to 6) must be orthogonal']);
+					md = checkmessage(md,['Vectors in diagnostic.referential (colums 1 to 3 and 4 to 6) must be orthogonal']);
 				end
 			end
@@ -110,5 +110,5 @@
 				pos=find(md.mask.vertexongroundedice & md.mesh.vertexonbed);
 				if any(~isnan(md.diagnostic.referential(pos,:))),
-					checkmessage(['no referential should be specified for basal vertices of grounded ice']);
+					md = checkmessage(md,['no referential should be specified for basal vertices of grounded ice']);
 				end
 			end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/flaim.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/flaim.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/flaim.m	(revision 12878)
@@ -32,14 +32,14 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			%Early return
 			if solution~=FlaimSolutionEnum, return; end
 
-			checkfield(md,'flaim.tracks','file',1);
+			md = checkfield(md,'flaim.tracks','file',1);
 			if any(isnan(md.flaim.criterion)) || isempty(md.flaim.criterion)
-				checkfield(md,'flaim.targets','file',1);
+				md = checkfield(md,'flaim.targets','file',1);
 			else
-				checkfield(md,'flaim.criterion','numel',[md.mesh.numberofvertices md.mesh.numberofelements]);
+				md = checkfield(md,'flaim.criterion','numel',[md.mesh.numberofvertices md.mesh.numberofelements]);
 			end
 
Index: /issm/branches/trunk-jpl-damage/src/m/classes/flowequation.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/flowequation.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/flowequation.m	(revision 12878)
@@ -27,28 +27,30 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			if ismember(DiagnosticHorizAnalysisEnum,analyses),
 
-				checkfield(md,'flowequation.ismacayealpattyn','numel',1,'values',[0 1]);
-				checkfield(md,'flowequation.ishutter','numel',1,'values',[0 1]);
-				checkfield(md,'flowequation.isstokes','numel',1,'values',[0 1]);
-				checkfield(md,'flowequation.bordermacayeal','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-				checkfield(md,'flowequation.borderpattyn','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-				checkfield(md,'flowequation.borderstokes','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				md = checkfield(md,'flowequation.ismacayealpattyn','numel',1,'values',[0 1]);
+				md = checkfield(md,'flowequation.ishutter','numel',1,'values',[0 1]);
+				md = checkfield(md,'flowequation.isstokes','numel',1,'values',[0 1]);
+				md = checkfield(md,'flowequation.bordermacayeal','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				md = checkfield(md,'flowequation.borderpattyn','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				md = checkfield(md,'flowequation.borderstokes','size',[md.mesh.numberofvertices 1],'values',[0 1]);
 				if (md.mesh.dimension==2),
-					checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[1:2]);
-					checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[1:2]);
+					md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[1:2]);
+					md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[1:2]);
 				else
-					checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[0:7]);
-					checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[0:7]);
+					md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[0:7]);
+					md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[0:7]);
 				end
 				if (md.flowequation.ismacayealpattyn==0 && md.flowequation.ishutter==0 && md.flowequation.isstokes==0),
-					checkmessage(['no element types set for this model. At least one of ismacayealpattyn, ishutter or isstokes need to be =1']);
+					md = checkmessage(md,['no element types set for this model. At least one of ismacayealpattyn, ishutter or isstokes need to be =1']);
 				end
 			end
 			if ismember(DiagnosticHutterAnalysisEnum,analyses),
-				if any(md.flowequation.element_equation==1 & md.mask.elementonfloatingice),
-					disp(sprintf('\n !!! Warning: Hutter''s model is not consistent on ice shelves !!!\n'));
+				if any(md.flowequation.element_equation==1),
+					if(md.flowequation.element_equation & md.mask.elementonfloatingice),
+						disp(sprintf('\n !!! Warning: Hutter''s model is not consistent on ice shelves !!!\n'));
+					end
 				end
 			end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/friction.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/friction.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/friction.m	(revision 12878)
@@ -22,12 +22,12 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			%Early return
 			if ~ismember(DiagnosticHorizAnalysisEnum,analyses) & ~ismember(ThermalAnalysisEnum,analyses), return; end
 
-			checkfield(md,'friction.coefficient','NaN',1,'size',[md.mesh.numberofvertices 1]);
-			checkfield(md,'friction.q','NaN',1,'size',[md.mesh.numberofelements 1]);
-			checkfield(md,'friction.p','NaN',1,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'friction.coefficient','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'friction.q','NaN',1,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'friction.p','NaN',1,'size',[md.mesh.numberofelements 1]);
 		end % }}}
 		function disp(obj) % {{{
Index: /issm/branches/trunk-jpl-damage/src/m/classes/geometry.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/geometry.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/geometry.m	(revision 12878)
@@ -24,14 +24,14 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			checkfield(md,'geometry.surface'  ,'NaN',1,'size',[md.mesh.numberofvertices 1]);
-			checkfield(md,'geometry.bed'      ,'NaN',1,'size',[md.mesh.numberofvertices 1]);
-			checkfield(md,'geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices 1],'>',0);
+			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),
-				checkmessage(['equality thickness=surface-bed violated']);
+				md = checkmessage(md,['equality thickness=surface-bed violated']);
 			end 
 			if solution==TransientSolutionEnum & md.transient.isgroundingline,
-				checkfield(md,'geometry.bathymetry','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'geometry.bathymetry','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/groundingline.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/groundingline.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/groundingline.m	(revision 12878)
@@ -28,19 +28,19 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			checkfield(md,'groundingline.migration','values',{'None' 'AgressiveMigration' 'SoftMigration'});
+			md = checkfield(md,'groundingline.migration','values',{'None' 'AgressiveMigration' 'SoftMigration'});
 
 			if ~strcmp(obj.migration,'None'),
 				if isnan(md.geometry.bathymetry),
-					checkmessage(['requesting grounding line migration, but bathymetry is absent!']);
+					md = checkmessage(md,['requesting grounding line migration, but bathymetry is absent!']);
 				end
 				pos=find(md.mask.vertexongroundedice); 
 				if any(abs(md.geometry.bed(pos)-md.geometry.bathymetry(pos))>10^-10),
-					checkmessage(['bathymetry not equal to bed on grounded ice !']);
+					md = checkmessage(md,['bathymetry not equal to bed on grounded ice !']);
 				end
 				pos=find(md.mask.vertexonfloatingice); 
 				if any(md.geometry.bathymetry(pos)-md.geometry.bed(pos)>10^-9),
-					checkmessage(['bathymetry superior to bed on floating ice !']);
+					md = checkmessage(md,['bathymetry superior to bed on floating ice !']);
 				end
 			end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/hydrology.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/hydrology.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/hydrology.m	(revision 12878)
@@ -35,11 +35,11 @@
 			obj.stabilization=1;
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			%Early return
 			if ~ismember(HydrologyAnalysisEnum,analyses), return; end
 
-			checkfield(md,'hydrology.spcwatercolumn','forcing',1);
-			checkfield(md,'hydrology.stabilization','>=',0);
+			md = checkfield(md,'hydrology.spcwatercolumn','forcing',1);
+			md = checkfield(md,'hydrology.stabilization','>=',0);
 		end % }}}
 		function disp(obj) % {{{
Index: /issm/branches/trunk-jpl-damage/src/m/classes/initialization.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/initialization.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/initialization.m	(revision 12878)
@@ -27,34 +27,34 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 			if ismember(DiagnosticHorizAnalysisEnum,analyses)
 				if ~isnan(md.initialization.vx) & ~isnan(md.initialization.vy),
-					checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
-					checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
+					md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
+					md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
 				end
 			end
 			if ismember(PrognosticAnalysisEnum,analyses),
-				checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
-				checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
 			if ismember(HydrologyAnalysisEnum,analyses),
-				checkfield(md,'initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
 			if ismember(BalancethicknessAnalysisEnum,analyses),
-				checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
-				checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
 				%Triangle with zero velocity
 				if any(sum(abs(md.initialization.vx(md.mesh.elements)),2)==0 & sum(abs(md.initialization.vy(md.mesh.elements)),2)==0)
-					checkmessage('at least one triangle has all its vertices with a zero velocity');
+					md = checkmessage(md,'at least one triangle has all its vertices with a zero velocity');
 				end
 			end
 			if ismember(ThermalAnalysisEnum,analyses),
-				checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
-				checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
-				checkfield(md,'initialization.vz','NaN',1,'size',[md.mesh.numberofvertices 1]);
-				checkfield(md,'initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'initialization.vz','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
-			if (ismember(EnthalpyAnalysisEnum,analyses) & md.thermal.isenthalpy),
-				checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices 1]);
+			if (ismember(EnthalpyAnalysisEnum,analyses) & md.thermal.isenthalpy) | solution==EnthalpySolutionEnum,
+				md = checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices 1]);
 			end
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/inversion.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/inversion.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/inversion.m	(revision 12878)
@@ -75,5 +75,5 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			%Early return
@@ -98,8 +98,8 @@
 
 			if solution==BalancethicknessSolutionEnum
-				checkfield(md,'inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				md = checkfield(md,'inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
 			else
-				checkfield(md,'inversion.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
-				checkfield(md,'inversion.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				md = checkfield(md,'inversion.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				md = checkfield(md,'inversion.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
 			end
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/mask.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/mask.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/mask.m	(revision 12878)
@@ -25,12 +25,12 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			checkfield(md,'mask.elementonfloatingice','size',[md.mesh.numberofelements 1],'values',[0 1]);
-			checkfield(md,'mask.elementongroundedice','size',[md.mesh.numberofelements 1],'values',[0 1]);
-			checkfield(md,'mask.elementonwater'      ,'size',[md.mesh.numberofelements 1],'values',[0 1]);
-			checkfield(md,'mask.vertexonfloatingice','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-			checkfield(md,'mask.vertexongroundedice','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-			checkfield(md,'mask.vertexonwater'      ,'size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'mask.elementonfloatingice','size',[md.mesh.numberofelements 1],'values',[0 1]);
+			md = checkfield(md,'mask.elementongroundedice','size',[md.mesh.numberofelements 1],'values',[0 1]);
+			md = checkfield(md,'mask.elementonwater'      ,'size',[md.mesh.numberofelements 1],'values',[0 1]);
+			md = checkfield(md,'mask.vertexonfloatingice','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'mask.vertexongroundedice','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'mask.vertexonwater'      ,'size',[md.mesh.numberofvertices 1],'values',[0 1]);
 		end % }}}
 		function disp(obj) % {{{
Index: /issm/branches/trunk-jpl-damage/src/m/classes/materials.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/materials.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/materials.m	(revision 12878)
@@ -8,4 +8,5 @@
 		rho_ice                    = 0;
 		rho_water                  = 0;
+		rho_freshwater             = 0;
 		mu_water                   = 0;
 		heatcapacity               = 0;
@@ -35,6 +36,9 @@
 			obj.rho_ice=917;
 
-			%water density (kg/m^3)
+			%ocean water density (kg/m^3)
 			obj.rho_water=1023;
+
+			%fresh water density (kg/m^3)
+			obj.rho_freshwater=1000;
 
 			%water viscosity (N.s/m^2)
@@ -66,12 +70,12 @@
 			obj.rheology_law='Paterson';
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
-			checkfield(md,'materials.rho_ice','>',0);
-			checkfield(md,'materials.rho_water','>',0);
-			checkfield(md,'materials.mu_water','>',0);
-			checkfield(md,'materials.rheology_B','>',0,'size',[md.mesh.numberofvertices 1]);
-			checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements 1]);
-			checkfield(md,'materials.rheology_Z','>',0,'size',[md.mesh.numberofvertices 1]);
-			checkfield(md,'materials.rheology_law','values',{'None' 'Paterson' 'Arrhenius'});
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			md = checkfield(md,'materials.rho_ice','>',0);
+			md = checkfield(md,'materials.rho_water','>',0);
+			md = checkfield(md,'materials.rho_freshwater','>',0);
+			md = checkfield(md,'materials.mu_water','>',0);
+			md = checkfield(md,'materials.rheology_B','>',0,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'materials.rheology_law','values',{'None' 'Paterson' 'Arrhenius'});
 		end % }}}
 		function disp(obj) % {{{
@@ -79,5 +83,6 @@
 
 			fielddisplay(obj,'rho_ice','ice density [kg/m^3]');
-			fielddisplay(obj,'rho_water','water density [kg/m^3]');
+			fielddisplay(obj,'rho_water','ocean water density [kg/m^3]');
+			fielddisplay(obj,'rho_freshwater','fresh water density [kg/m^3]');
 			fielddisplay(obj,'mu_water','water viscosity [N s/m^2]');
 			fielddisplay(obj,'heatcapacity','heat capacity [J/kg/K]');
@@ -96,4 +101,5 @@
 			WriteData(fid,'object',obj,'fieldname','rho_ice','format','Double');
 			WriteData(fid,'object',obj,'fieldname','rho_water','format','Double');
+			WriteData(fid,'object',obj,'fieldname','rho_freshwater','format','Double');
 			WriteData(fid,'object',obj,'fieldname','mu_water','format','Double');
 			WriteData(fid,'object',obj,'fieldname','heatcapacity','format','Double');
Index: /issm/branches/trunk-jpl-damage/src/m/classes/mesh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/mesh.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/mesh.m	(revision 12878)
@@ -64,33 +64,33 @@
 			obj.average_vertex_connectivity=25;
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			checkfield(md,'mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
-			checkfield(md,'mesh.y','NaN',1,'size',[md.mesh.numberofvertices 1]);
-			checkfield(md,'mesh.z','NaN',1,'size',[md.mesh.numberofvertices 1]);
-			checkfield(md,'mesh.elements','NaN',1,'>',0,'values',1:md.mesh.numberofvertices);
+			md = checkfield(md,'mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'mesh.y','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'mesh.z','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'mesh.elements','NaN',1,'>',0,'values',1:md.mesh.numberofvertices);
 			if(md.mesh.dimension==2),
-				checkfield(md,'mesh.elements','size',[md.mesh.numberofelements 3]);
+				md = checkfield(md,'mesh.elements','size',[md.mesh.numberofelements 3]);
 			else
-				checkfield(md,'mesh.elements','size',[md.mesh.numberofelements 6]);
+				md = checkfield(md,'mesh.elements','size',[md.mesh.numberofelements 6]);
 			end
 			if any(~ismember(1:md.mesh.numberofvertices,sort(unique(md.mesh.elements(:)))));
-				checkmessage('orphan nodes have been found. Check the mesh outline');
+				md = checkmessage(md,'orphan nodes have been found. Check the mesh outline');
 			end
-			checkfield(md,'mesh.dimension','values',[2 3]);
-			checkfield(md,'mesh.numberoflayers','>=',0);
-			checkfield(md,'mesh.numberofelements','>',0);
-			checkfield(md,'mesh.numberofvertices','>',0);
+			md = checkfield(md,'mesh.dimension','values',[2 3]);
+			md = checkfield(md,'mesh.numberoflayers','>=',0);
+			md = checkfield(md,'mesh.numberofelements','>',0);
+			md = checkfield(md,'mesh.numberofvertices','>',0);
 			%no checks for numberofedges lat long and hemisphere
-			checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements 1],'values',[0 1]);
-			checkfield(md,'mesh.elementonsurface','size',[md.mesh.numberofelements 1],'values',[0 1]);
-			checkfield(md,'mesh.vertexonbed','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-			checkfield(md,'mesh.vertexonsurface','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements 1],'values',[0 1]);
+			md = checkfield(md,'mesh.elementonsurface','size',[md.mesh.numberofelements 1],'values',[0 1]);
+			md = checkfield(md,'mesh.vertexonbed','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'mesh.vertexonsurface','size',[md.mesh.numberofvertices 1],'values',[0 1]);
 			if (md.mesh.dimension==2),
-				checkfield(md,'mesh.average_vertex_connectivity','>=',9,'message','''mesh.average_vertex_connectivity'' should be at least 9 in 2d');
+				md = checkfield(md,'mesh.average_vertex_connectivity','>=',9,'message','''mesh.average_vertex_connectivity'' should be at least 9 in 2d');
 			else
-				checkfield(md,'mesh.average_vertex_connectivity','>=',24,'message','''mesh.average_vertex_connectivity'' should be at least 24 in 3d');
+				md = checkfield(md,'mesh.average_vertex_connectivity','>=',24,'message','''mesh.average_vertex_connectivity'' should be at least 24 in 3d');
 			end
-			checkfield(md,'mesh.elementconnectivity','size',[md.mesh.numberofelements 3],'NaN',1);
+			md = checkfield(md,'mesh.elementconnectivity','size',[md.mesh.numberofelements 3],'NaN',1);
 
 			%Solution specific checks
@@ -98,22 +98,22 @@
 				case PrognosticSolutionEnum,
 					if md.prognostic.stabilization==3,
-						checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
-						checkfield(md,'mesh.edges','size',[NaN 4]);
-						checkfield(md,'mesh.edges(:,1:3)','>',0);
+						md = checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
+						md = checkfield(md,'mesh.edges','size',[NaN 4]);
+						md = checkfield(md,'mesh.edges(:,1:3)','>',0);
 					end
 				case BalancethicknessSolutionEnum,
 					if md.balancethickness.stabilization==3,
-						checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
-						checkfield(md,'mesh.edges','size',[NaN 4]);
-						checkfield(md,'mesh.edges(:,1:3)','>',0);
+						md = checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
+						md = checkfield(md,'mesh.edges','size',[NaN 4]);
+						md = checkfield(md,'mesh.edges(:,1:3)','>',0);
 					end
 				case TransientSolutionEnum,
 					if md.transient.isprognostic & md.prognostic.stabilization==3,
-						checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
-						checkfield(md,'mesh.edges','size',[NaN 4]);
-						checkfield(md,'mesh.edges(:,1:3)','>',0);
+						md = checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
+						md = checkfield(md,'mesh.edges','size',[NaN 4]);
+						md = checkfield(md,'mesh.edges(:,1:3)','>',0);
 					end
 				case ThermalSolutionEnum,
-					checkfield(md,'mesh.dimension','values',3,'message','thermal solution only supported on 3d meshes');
+					md = checkfield(md,'mesh.dimension','values',3,'message','thermal solution only supported on 3d meshes');
 			end
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/miscellaneous.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/miscellaneous.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/miscellaneous.m	(revision 12878)
@@ -19,7 +19,7 @@
 			end
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			checkfield(md,'miscellaneous.name','empty',1);
+			md = checkfield(md,'miscellaneous.name','empty',1);
 
 		end % }}}
Index: sm/branches/trunk-jpl-damage/src/m/classes/model.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/model.py	(revision 12877)
+++ 	(revision )
@@ -1,114 +1,0 @@
-#module imports {{{
-from mesh import mesh
-from mask import mask
-from geometry import geometry
-from constants import constants
-from surfaceforcings import surfaceforcings
-from basalforcings import basalforcings
-from materials import materials
-from friction import friction
-from flowequation import flowequation
-from timestepping import timestepping
-from initialization import initialization
-from rifts import rifts
-from debug import debug
-from verbose import verbose
-from settings import settings
-from solver import solver
-from none import none
-from balancethickness import balancethickness
-from diagnostic import diagnostic
-from groundingline import groundingline
-from hydrology import hydrology
-from prognostic import prognostic
-from thermal import thermal
-from steadystate import steadystate
-from transient import transient
-from autodiff import autodiff
-from flaim import flaim
-from inversion import inversion
-from qmu import qmu
-from radaroverlay import radaroverlay
-from miscellaneous import miscellaneous
-from private import private
-#}}}
-class model:
-	#properties
-	def __init__(self):
-		# {{{ Properties
-		self.mesh             = mesh()
-		self.mask             = mask()
-		self.geometry         = geometry()
-		self.constants        = constants()
-		self.surfaceforcings  = surfaceforcings()
-		self.basalforcings    = basalforcings()
-		self.materials        = materials()
-		self.friction         = friction()
-		self.flowequation     = flowequation()
-		self.timestepping     = timestepping()
-		self.initialization   = initialization()
-		self.rifts            = rifts()
-
-		self.debug            = debug()
-		self.verbose          = verbose()
-		self.settings         = settings()
-		self.solver           = solver()
-		self.cluster          = none()
-
-		self.balancethickness = balancethickness()
-		self.diagnostic       = diagnostic()
-		self.groundingline    = groundingline()
-		self.hydrology        = hydrology()
-		self.prognostic       = prognostic()
-		self.thermal          = thermal()
-		self.steadystate      = steadystate()
-		self.transient        = transient()
-
-		self.autodiff         = autodiff()
-		self.flaim            = flaim()
-		self.inversion        = inversion()
-		self.qmu              = qmu()
-
-		self.results          = [];
-		self.radaroverlay     = radaroverlay()
-		self.miscellaneous    = miscellaneous()
-		self.private          = private()
-		#}}}
-	def __repr__(obj):
-		# {{{ Display
-
-		#print "Here %s the number: %d" % ("is", 37)
-		string="%19s: %-22s -- %s" % ("mesh","[%s,%s]" % ("1x1",obj.mesh.__class__.__name__),"mesh properties")
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("mask","[%s,%s]" % ("1x1",obj.mask.__class__.__name__),"defines grounded and floating elements"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("geometry","[%s,%s]" % ("1x1",obj.geometry.__class__.__name__),"surface elevation, bedrock topography, ice thickness,..."))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("constants","[%s,%s]" % ("1x1",obj.constants.__class__.__name__),"physical constants"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("surfaceforcings","[%s,%s]" % ("1x1",obj.surfaceforcings.__class__.__name__),"surface forcings"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("basalforcings","[%s,%s]" % ("1x1",obj.basalforcings.__class__.__name__),"bed forcings"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("materials","[%s,%s]" % ("1x1",obj.materials.__class__.__name__),"material properties"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("friction","[%s,%s]" % ("1x1",obj.friction.__class__.__name__),"basal friction/drag properties"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flowequation","[%s,%s]" % ("1x1",obj.flowequation.__class__.__name__),"flow equations"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("timestepping","[%s,%s]" % ("1x1",obj.timestepping.__class__.__name__),"time stepping for transient models"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("initialization","[%s,%s]" % ("1x1",obj.initialization.__class__.__name__),"initial guess/state"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("rifts","[%s,%s]" % ("1x1",obj.rifts.__class__.__name__),"rifts properties'"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("debug","[%s,%s]" % ("1x1",obj.debug.__class__.__name__),"debugging tools (valgrind, gprof"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("verbose","[%s,%s]" % ("1x1",obj.verbose.__class__.__name__),"verbosity level in solve"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("settings","[%s,%s]" % ("1x1",obj.settings.__class__.__name__),"settings properties"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("solver","[%s,%s]" % ("1x1",obj.solver.__class__.__name__),"PETSc options for each solution'"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("cluster","[%s,%s]" % ("1x1",obj.cluster.__class__.__name__),"cluster parameters (number of cpus...)"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("balancethickness","[%s,%s]" % ("1x1",obj.balancethickness.__class__.__name__),"parameters for balancethickness solution"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("diagnostic","[%s,%s]" % ("1x1",obj.diagnostic.__class__.__name__),"parameters for diagnostic solution"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("groundingline","[%s,%s]" % ("1x1",obj.groundingline.__class__.__name__),"parameters for groundingline solution"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("hydrology","[%s,%s]" % ("1x1",obj.hydrology.__class__.__name__),"parameters for hydrology solution"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("prognostic","[%s,%s]" % ("1x1",obj.prognostic.__class__.__name__),"parameters for prognostic solution"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("thermal","[%s,%s]" % ("1x1",obj.thermal.__class__.__name__),"parameters for thermal solution"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("steadystate","[%s,%s]" % ("1x1",obj.steadystate.__class__.__name__),"parameters for steadystate solution"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("transient","[%s,%s]" % ("1x1",obj.transient.__class__.__name__),"parameters for transient solution"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("autodiff","[%s,%s]" % ("1x1",obj.autodiff.__class__.__name__),"automatic differentiation parameters"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flaim","[%s,%s]" % ("1x1",obj.flaim.__class__.__name__),"flaim parameters"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("inversion","[%s,%s]" % ("1x1",obj.inversion.__class__.__name__),"parameters for inverse methods"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("qmu","[%s,%s]" % ("1x1",obj.qmu.__class__.__name__),"dakota properties"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("results","[%s,%s]" % ("1x1",obj.results.__class__.__name__),"model results'"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("radaroverlay","[%s,%s]" % ("1x1",obj.radaroverlay.__class__.__name__),"radar image for plot overlay"))
-		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("miscellaneous","[%s,%s]" % ("1x1",obj.miscellaneous.__class__.__name__),"miscellaneous fields"))
-		return string;
-		 #}}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/model/model.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/model/model.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/model/model.m	(revision 12878)
@@ -6,5 +6,5 @@
 classdef model
     properties (SetAccess=public) %Model fields
-		 % {{{1
+		 % {{{
 		 %Careful here: no other class should be used as default value this is a bug of matlab
 		 mesh             = 0;
@@ -75,5 +75,5 @@
 	 end
 	 methods
-		 function md = model(varargin) % {{{1
+		 function md = model(varargin) % {{{
 
 			 switch nargin
@@ -83,4 +83,10 @@
 					 error('model constructor error message: 0 of 1 argument only in input.');
 				 end
+		 end
+		 %}}}
+		 function md = checkmessage(md,string) % {{{
+			 if(nargout~=1) error('wrong usage, model must be an output'); end
+			 disp(['model not consistent: ' string]);
+			 md.private.isconsistent=false;
 		 end
 		 %}}}
@@ -244,6 +250,7 @@
 			 if isfield(structmd,'pressureload'), md.diagnostic.icefront=structmd.pressureload; end
 			 if isfield(structmd,'diagnostic_ref'), md.diagnostic.referential=structmd.diagnostic_ref; end
-
-
+			 if isfield(structmd,'npart'); md.qmu.numberofpartitions=structmd.npart; end
+			 if isfield(structmd,'part'); md.qmu.partition=structmd.part; end
+				 
 			 %Field changes
 			 if (isfield(structmd,'type') & ischar(structmd.type)), 
@@ -352,9 +359,11 @@
 				 md.mesh.lowerelements(1:md.mesh.numberofelements2d)=NaN;
 			 end
+				 
 			 if ~isfield(structmd,'diagnostic_ref');
 				 md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
 			 end
+
 		 end% }}}
-		 function md = setdefaultparameters(md) % {{{1
+		 function md = setdefaultparameters(md) % {{{
 
 			 %initialize subclasses
Index: /issm/branches/trunk-jpl-damage/src/m/classes/model/model.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/model/model.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/model/model.py	(revision 12878)
@@ -0,0 +1,114 @@
+#module imports {{{
+from mesh import mesh
+from mask import mask
+from geometry import geometry
+from constants import constants
+from surfaceforcings import surfaceforcings
+from basalforcings import basalforcings
+from materials import materials
+from friction import friction
+from flowequation import flowequation
+from timestepping import timestepping
+from initialization import initialization
+from rifts import rifts
+from debug import debug
+from verbose import verbose
+from settings import settings
+from solver import solver
+from generic import generic
+from balancethickness import balancethickness
+from diagnostic import diagnostic
+from groundingline import groundingline
+from hydrology import hydrology
+from prognostic import prognostic
+from thermal import thermal
+from steadystate import steadystate
+from transient import transient
+from autodiff import autodiff
+from flaim import flaim
+from inversion import inversion
+from qmu import qmu
+from radaroverlay import radaroverlay
+from miscellaneous import miscellaneous
+from private import private
+#}}}
+class model(object):
+	#properties
+	def __init__(self):
+		# {{{ Properties
+		self.mesh             = mesh()
+		self.mask             = mask()
+		self.geometry         = geometry()
+		self.constants        = constants()
+		self.surfaceforcings  = surfaceforcings()
+		self.basalforcings    = basalforcings()
+		self.materials        = materials()
+		self.friction         = friction()
+		self.flowequation     = flowequation()
+		self.timestepping     = timestepping()
+		self.initialization   = initialization()
+		self.rifts            = rifts()
+
+		self.debug            = debug()
+		self.verbose          = verbose()
+		self.settings         = settings()
+		self.solver           = solver()
+		self.cluster          = generic()
+
+		self.balancethickness = balancethickness()
+		self.diagnostic       = diagnostic()
+		self.groundingline    = groundingline()
+		self.hydrology        = hydrology()
+		self.prognostic       = prognostic()
+		self.thermal          = thermal()
+		self.steadystate      = steadystate()
+		self.transient        = transient()
+
+		self.autodiff         = autodiff()
+		self.flaim            = flaim()
+		self.inversion        = inversion()
+		self.qmu              = qmu()
+
+		self.results          = [];
+		self.radaroverlay     = radaroverlay()
+		self.miscellaneous    = miscellaneous()
+		self.private          = private()
+		#}}}
+	def __repr__(obj):
+		# {{{ Display
+
+		#print "Here %s the number: %d" % ("is", 37)
+		string="%19s: %-22s -- %s" % ("mesh","[%s,%s]" % ("1x1",obj.mesh.__class__.__name__),"mesh properties")
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("mask","[%s,%s]" % ("1x1",obj.mask.__class__.__name__),"defines grounded and floating elements"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("geometry","[%s,%s]" % ("1x1",obj.geometry.__class__.__name__),"surface elevation, bedrock topography, ice thickness,..."))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("constants","[%s,%s]" % ("1x1",obj.constants.__class__.__name__),"physical constants"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("surfaceforcings","[%s,%s]" % ("1x1",obj.surfaceforcings.__class__.__name__),"surface forcings"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("basalforcings","[%s,%s]" % ("1x1",obj.basalforcings.__class__.__name__),"bed forcings"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("materials","[%s,%s]" % ("1x1",obj.materials.__class__.__name__),"material properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("friction","[%s,%s]" % ("1x1",obj.friction.__class__.__name__),"basal friction/drag properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flowequation","[%s,%s]" % ("1x1",obj.flowequation.__class__.__name__),"flow equations"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("timestepping","[%s,%s]" % ("1x1",obj.timestepping.__class__.__name__),"time stepping for transient models"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("initialization","[%s,%s]" % ("1x1",obj.initialization.__class__.__name__),"initial guess/state"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("rifts","[%s,%s]" % ("1x1",obj.rifts.__class__.__name__),"rifts properties'"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("debug","[%s,%s]" % ("1x1",obj.debug.__class__.__name__),"debugging tools (valgrind, gprof"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("verbose","[%s,%s]" % ("1x1",obj.verbose.__class__.__name__),"verbosity level in solve"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("settings","[%s,%s]" % ("1x1",obj.settings.__class__.__name__),"settings properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("solver","[%s,%s]" % ("1x1",obj.solver.__class__.__name__),"PETSc options for each solution'"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("cluster","[%s,%s]" % ("1x1",obj.cluster.__class__.__name__),"cluster parameters (number of cpus...)"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("balancethickness","[%s,%s]" % ("1x1",obj.balancethickness.__class__.__name__),"parameters for balancethickness solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("diagnostic","[%s,%s]" % ("1x1",obj.diagnostic.__class__.__name__),"parameters for diagnostic solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("groundingline","[%s,%s]" % ("1x1",obj.groundingline.__class__.__name__),"parameters for groundingline solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("hydrology","[%s,%s]" % ("1x1",obj.hydrology.__class__.__name__),"parameters for hydrology solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("prognostic","[%s,%s]" % ("1x1",obj.prognostic.__class__.__name__),"parameters for prognostic solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("thermal","[%s,%s]" % ("1x1",obj.thermal.__class__.__name__),"parameters for thermal solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("steadystate","[%s,%s]" % ("1x1",obj.steadystate.__class__.__name__),"parameters for steadystate solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("transient","[%s,%s]" % ("1x1",obj.transient.__class__.__name__),"parameters for transient solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("autodiff","[%s,%s]" % ("1x1",obj.autodiff.__class__.__name__),"automatic differentiation parameters"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flaim","[%s,%s]" % ("1x1",obj.flaim.__class__.__name__),"flaim parameters"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("inversion","[%s,%s]" % ("1x1",obj.inversion.__class__.__name__),"parameters for inverse methods"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("qmu","[%s,%s]" % ("1x1",obj.qmu.__class__.__name__),"dakota properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("results","[%s,%s]" % ("1x1",obj.results.__class__.__name__),"model results'"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("radaroverlay","[%s,%s]" % ("1x1",obj.radaroverlay.__class__.__name__),"radar image for plot overlay"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("miscellaneous","[%s,%s]" % ("1x1",obj.miscellaneous.__class__.__name__),"miscellaneous fields"))
+		return string;
+		 #}}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/model/planet.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/model/planet.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/model/planet.m	(revision 12878)
@@ -6,5 +6,5 @@
 classdef planet < model
     properties (SetAccess=public) %Planet fields
-		 % {{{1
+		 % {{{
 		 %Planet specific fields
 		 r=NaN;
@@ -14,5 +14,5 @@
 	 end
 	 methods
-		function md=planetmesh(md,varargin) % {{{1
+		function md=planetmesh(md,varargin) % {{{
 		%PLANETMESH: build 2d shell mesh
 		%
Index: /issm/branches/trunk-jpl-damage/src/m/classes/organizer.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/organizer.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/organizer.m	(revision 12878)
@@ -16,5 +16,5 @@
 classdef organizer
     properties (SetAccess=private) 
-		 % {{{1
+		 % {{{
 		 currentstep   =0;
 	 end
@@ -28,5 +28,5 @@
 	 end
 	 methods
-		 function org=organizer(varargin) % {{{1
+		 function org=organizer(varargin) % {{{
 
 			 %process options
@@ -57,5 +57,5 @@
 		 end
 		 %}}}
-		 function disp(org) % {{{1
+		 function disp(org) % {{{
 			 disp(sprintf('   Repository: ''%s''',org.repository));
 			 disp(sprintf('   Prefix:     ''%s''',org.prefix));
@@ -69,5 +69,23 @@
 		 end
 		 %}}}
-		 function md=loadmodel(org,string),% {{{1
+		 function md=load(org,string),% {{{
+
+			 %Get model path
+			 if ~ischar(string), error('argument provided is not a string'); end
+			 path=[org.repository '/' org.prefix string];
+
+			 %figure out if the model is there
+			 if exist(path,'file'),
+				 struc=load(path,'-mat');
+				 name=char(fieldnames(struc));
+				 md=struc.(name);
+				 if nargout,
+					 varargout{1}=md;
+				 end
+			 else
+				 error(['Could not find ' path ]);
+			 end
+		 end%}}}
+		 function md=loadmodel(org,string),% {{{
 
 			 %Get model path
@@ -76,5 +94,5 @@
 
 			 %figure out if the model is there, otherwise, we have to use the default path supplied by user.
-			 if exist(path,'file'),
+			 if exist(path,'file') | exist([path '.mat'],'file'),
 				 md=loadmodel(path);
 				 return;
@@ -95,5 +113,5 @@
 			 end
 		 end%}}}
-		 function bool=perform(org,string) % {{{1
+		 function bool=perform(org,string) % {{{
 			 
 			 bool=false;
@@ -129,5 +147,5 @@
 
 		 end%}}}
-		 function savemodel(org,md) % {{{1
+		 function savemodel(org,md) % {{{
 
 			 %check
@@ -139,5 +157,5 @@
 			 
 			 %check that md is a model
-			 if ~isa(md,'model'),       error('savemodel error message: third argument is not a model'); end
+			 if ~isa(md,'model'), warning('third argument is not a model'); end
 			 if (org.currentstep>length(org.steps)), error(['organizer error message: element with id ' num2str(org.currentstep) ' not found']); end
 
Index: /issm/branches/trunk-jpl-damage/src/m/classes/pairoptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/pairoptions.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/pairoptions.m	(revision 12878)
@@ -223,4 +223,23 @@
 			end
 		end % }}}
+		function marshall(obj,fid,firstindex)% {{{
+
+			for i=1:size(obj.list,1),
+				name  = obj.list{i,1};
+				value = obj.list{i,2};
+
+				%Write option name
+				WriteData(fid,'enum',(firstindex-1)+2*i-1,'data',name,'format','String');
+
+				%Write option value
+				if (isnumeric(value) & numel(value)==1),
+					WriteData(fid,'enum',(firstindex-1)+2*i,'data',value,'format','Double');
+				elseif ischar(value),
+					WriteData(fid,'enum',(firstindex-1)+2*i,'data',value,'format','String');
+				else
+					error(['Cannot marshall option ' name ': format not supported yet']);
+				end
+			end
+		end % }}}
 	end
 end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/pairoptions.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/pairoptions.py	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/pairoptions.py	(revision 12878)
@@ -1,38 +1,213 @@
-class pairoptions:
-	#properties
-	def __init__(self,*args):
-		# {{{ Properties
-		if len(args)%2==1:
-			raise RuntimeError('pairoption error message: an even number of options is required')
-
-		#create a pairoption object
-		if len(args)==0:
-			self.list=[]
-		else:
-			self.list=[]
-			for i in range(int(round(len(args)/2))):
-				if isinstance(args[2*i],str):
-					self.list.append([args[2*i],args[2*i+1]])
+from WriteData import *
+
+class pairoptions(object):
+	"""
+	PAIROPTIONS class definition
+ 
+	    Usage:
+	       pairoptions=pairoptions();
+	       pairoptions=pairoptions('module',true,'solver',false);
+	"""
+
+	def __init__(self,*arg):
+		self.functionname = ''
+		self.list         = {}
+
+		#get calling function name
+		import inspect
+		if len(inspect.stack()) > 1:
+			self.functionname=inspect.stack()[1][3]
+
+		#initialize list
+		if not len(arg):
+			pass    #Do nothing,
+		else:
+			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):
+				self.list[arg[2*i]] = arg[2*i+1];
+			else:
+				#option is not a string, ignore it
+				print "WARNING: option number %d '%s' is not a string and will be ignored." % (i+1,type(arg[2*i]))
+	# }}}
+
+	def addfield(self,field,value):    # {{{
+		"""ADDFIELD - add a field to an options list"""
+		if isinstance(field,str):
+			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 exist"""
+		if isinstance(field,str):
+			if not field 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 occurance 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 occurence 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
+		if self.list:
+			s+="   list: (%ix%i)\n\n" % (len(self.list),2)
+			for item in self.list.iteritems():
+				if   isinstance(item[1],str):
+					s+="     field: %-10s value: '%s'\n" % (item[0],item[1])
+				elif isinstance(item[1],(bool,int,long,float)):
+					s+="     field: %-10s value: %g\n" % (item[0],item[1])
 				else:
-					#option is not a string, ignore it
-					print("%s%i%s"%('buildlist info: option number ',i,' is not a string, it will be ignored'))
-					continue
-
-		#}}}
-	def __repr__(obj):
-		# {{{ Display
-		if not obj.list:
-			string='   list: empty'
-		else:
-			string="   list: (%i)"%(len(obj.list))
-			for i in range(len(obj.list)):
-				if isinstance(obj.list[i][1],str):
-					string2="     field: %-10s value: '%s'"%(obj.list[i][0],obj.list[i][1])
-				elif isinstance(obj.list[i][1],float):
-					string2="     field: %-10s value: %g"%(obj.list[i][0],obj.list[i][1])
-				elif isinstance(obj.list[i][1],int):
-					string2="     field: %-10s value: %i"%(obj.list[i][0],obj.list[i][1])
-				else:
-					string2="     field: %-10s value: (%i)"%(len(obj.list[i][1]))
-				string="%s\n%s"%(string,string2)
-		return string
+					s+="     field: %-10s value: %s\n" % (item[0],type(item[1]))
+		else:
+			s+="   list: empty\n"
+		return s
+	# }}}
+
+	def exist(self,field):    # {{{
+		"""EXIST - check if the option exist"""
+
+		#some argument checking: 
+		if field == None or field == '':
+			raise ValueError('exist error message: bad usage');
+		if not isinstance(field,str):
+			raise TypeError("exist error message: field '%s' should be a string." % str(field));
+
+		#Recover option
+		if field in self.list:
+			return True
+		else:
+			return False
+	# }}}
+
+#	function num = fieldoccurences(obj,field), % {{{
+#	%FIELDOCCURENCES - get number of occurence of a field
+#
+#		%check input 
+#		if ~ischar(field),
+#			error('fieldoccurences error message: field should be a string');
+#		end
+#
+#		%get number of occurence
+#		num=sum(strcmpi(field,obj.list(:,1)));
+#	end % }}}
+
+	def getfieldvalue(self,field,default=None):    # {{{
+		"""
+		GETOPTION - get the value of an option
+	
+		Usage:
+		   value=options.getfieldvalue(field,default)
+	 
+		Find an option value from a field. A default option
+		can be given in input if the field does not exist
+	 
+		Examples:
+		   value=options.getfieldvalue(options,'caxis')
+		   value=options.getfieldvalue(options,'caxis',[0 2])
+		"""
+
+		#some argument checking: 
+		if field == None or field == '':
+			raise ValueError('getfieldvalue error message: bad usage');
+		if not isinstance(field,str):
+			raise TypeError("getfieldvalue error message: field '%s' should be a string." % str(field));
+
+		#Recover option
+		if field in self.list:
+			value=self.list[field]
+		else:
+			if not default == None:
+				value=default
+			else:
+				raise KeyError("error message: field '%s' has not been provided by user (and no default value has been specified)." % field)
+
+		return value
+	# }}}
+
+	def removefield(self,field,warn):    # {{{
+		"""
+		REMOVEFIELD - delete a field in an option list
+	 
+		Usage:
+		   obj=removefield(self,field,warn)
+	 
+		if warn==1 display an info message to warn user that
+		some of his options have been removed.
+		"""
+
+		#check if field exist
+		if field in self.list:
+
+			#remove duplicates from the options list
+			del self.list[field]
+
+			#warn user if requested
+			if warn:
+				print "removefield info: option '%s' has been removed from the list of options." % field
+	# }}}
+
+	def marshall(self,fid,firstindex):    # {{{
+
+		for i,item in enumerate(self.list.iteritems()):
+			name  = item[0]
+			value = item[1]
+
+			#Write option name
+			WriteData(fid,'enum',(firstindex-1)+2*i+1,'data',name,'format','String')
+
+			#Write option value
+			if   isinstance(value,str):
+				WriteData(fid,'enum',(firstindex-1)+2*i+2,'data',value,'format','String')
+			elif isinstance(value,(bool,int,long,float)):
+				WriteData(fid,'enum',(firstindex-1)+2*i+2,'data',value,'format','Double')
+			else:
+				raise TypeError("Cannot marshall option '%s': format not supported yet." % name)
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/classes/plotoptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/plotoptions.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/plotoptions.m	(revision 12878)
@@ -6,5 +6,5 @@
 classdef plotoptions
     properties (SetAccess=public) 
-		 % {{{1
+		 % {{{
 		 numberofplots = 0;
 		 figurenumber  = 1;
@@ -13,9 +13,9 @@
 	 end
 	 methods
-		 function opt=plotoptions(varargin) % {{{1
+		 function opt=plotoptions(varargin) % {{{
 			 opt=buildlist(opt,varargin{:});
 		 end
 		 %}}}
-		 function disp(opt) % {{{1
+		 function disp(opt) % {{{
 			 disp(sprintf('\n%s = \n',inputname(1)));
 			 disp(sprintf('   numberofplots: %i',opt.numberofplots));
@@ -41,5 +41,5 @@
 		 end
 		 %}}}
-		 function opt=buildlist(opt,varargin) % {{{1
+		 function opt=buildlist(opt,varargin) % {{{
 
 			 %check length of input
Index: /issm/branches/trunk-jpl-damage/src/m/classes/private.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/private.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/private.m	(revision 12878)
@@ -6,7 +6,8 @@
 classdef private
 	properties (SetAccess=public) 
-		 runtimename = '';
-		 bamg        = struct();
-		 solution    = '';
+		isconsistent = true;
+		runtimename  = '';
+		bamg         = struct();
+		solution     = '';
 	end
 	methods
@@ -22,5 +23,5 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 		end % }}}
@@ -28,4 +29,5 @@
 			disp(sprintf('   private parameters: do not change'));
 
+			fielddisplay(obj,'isconsistent','is model self consistent');
 			fielddisplay(obj,'runtimename','name of the run launched');
 			fielddisplay(obj,'bamg','structure with mesh properties construced if bamg is used to mesh the domain');
Index: /issm/branches/trunk-jpl-damage/src/m/classes/prognostic.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/prognostic.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/prognostic.m	(revision 12878)
@@ -36,13 +36,13 @@
 			obj.hydrostatic_adjustment='Absolute';
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			%Early return,
 			if ~ismember(PrognosticAnalysisEnum,analyses) |  (solution==TransientSolutionEnum & md.transient.isprognostic==0), return; end
 
-			checkfield(md,'prognostic.spcthickness','forcing',1);
-			checkfield(md,'prognostic.hydrostatic_adjustment','values',{'Absolute' 'Incremental'});
-			checkfield(md,'prognostic.stabilization','values',[0 1 2 3]);
-			checkfield(md,'prognostic.min_thickness','>',0);
+			md = checkfield(md,'prognostic.spcthickness','forcing',1);
+			md = checkfield(md,'prognostic.hydrostatic_adjustment','values',{'Absolute' 'Incremental'});
+			md = checkfield(md,'prognostic.stabilization','values',[0 1 2 3]);
+			md = checkfield(md,'prognostic.min_thickness','>',0);
 
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/qmu.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/qmu.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/qmu.m	(revision 12878)
@@ -35,5 +35,5 @@
 	
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			%Early return
@@ -41,27 +41,27 @@
 
 			if md.qmu.params.evaluation_concurrency~=1,
-				checkmessage(['concurrency should be set to 1 when running dakota in library mode']);
+				md = checkmessage(md,['concurrency should be set to 1 when running dakota in library mode']);
 			end
 			if ~isempty(md.qmu.partition),
 				if numel(md.qmu.partition)~=md.mesh.numberofvertices,
-					checkmessage(['user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1 ']);
+					md = checkmessage(md,['user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1 ']);
 				end
 				if find(md.qmu.partition)>=md.mesh.numberofvertices,
-					checkmessage(['user supplied partition should be indexed from 0 (c-convention)']);
+					md = checkmessage(md,['user supplied partition should be indexed from 0 (c-convention)']);
 				end
 				if min(md.qmu.partition)~=0,
-					checkmessage(['partition vector not indexed from 0 on']);
+					md = checkmessage(md,['partition vector not indexed from 0 on']);
 				end
 				if max(md.qmu.partition)>=md.mesh.numberofvertices,
-					checkmessage(['partition vector cannot have maximum index larger than number of nodes']);
+					md = checkmessage(md,['partition vector cannot have maximum index larger than number of nodes']);
 				end
 				if ~isempty(find(md.qmu.partition<0)),
-					checkmessage(['partition vector cannot have values less than 0']);
+					md = checkmessage(md,['partition vector cannot have values less than 0']);
 				end
 				if ~isempty(find(md.qmu.partition>=md.qmu.numberofpartitions)),
-					checkmessage(['partition vector cannot have values more than md.qmu.numberofpartitions-1']);
+					md = checkmessage(md,['partition vector cannot have values more than md.qmu.numberofpartitions-1']);
 				end
 				if max(md.qmu.partition)>=md.qmu.numberofpartitions,
-					checkmessage(['for qmu analysis, partitioning vector cannot go over npart, number of partition areas']);
+					md = checkmessage(md,['for qmu analysis, partitioning vector cannot go over npart, number of partition areas']);
 				end
 			end
@@ -69,5 +69,5 @@
 			if ~strcmpi(md.cluster.name,'none'),
 				if md.settings.waitonlock==0,
-					checkmessage(['waitonlock should be activated when running qmu in parallel mode!']);
+					md = checkmessage(md,['waitonlock should be activated when running qmu in parallel mode!']);
 				end
 			end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/rifts.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/rifts.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/rifts.m	(revision 12878)
@@ -21,5 +21,5 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 			if isempty(obj.riftstruct) | isnans(obj.riftstruct),
 				numrifts=0;
@@ -29,17 +29,17 @@
 			if numrifts,
 				if ~(md.mesh.dimension==2),
-					checkmessage(['models with rifts are only supported in 2d for now!']);
+					md = checkmessage(md,['models with rifts are only supported in 2d for now!']);
 				end
 				if ~isstruct(obj.riftstruct),
-					checkmessage(['rifts.riftstruct should be a structure!']);
+					md = checkmessage(md,['rifts.riftstruct should be a structure!']);
 				end
 				if ~isempty(find(md.mesh.segmentmarkers>=2)),
 					%We have segments with rift markers, but no rift structure!
-					checkmessage(['model should be processed for rifts (run meshprocessrifts)!']);
+					md = checkmessage(md,['model should be processed for rifts (run meshprocessrifts)!']);
 				end
-				checkfield(md,'rifts.riftstruct.fill','values',[WaterEnum() AirEnum() IceEnum() MelangeEnum()]);
+				md = checkfield(md,'rifts.riftstruct.fill','values',[WaterEnum() AirEnum() IceEnum() MelangeEnum()]);
 			else
 				if ~isnans(obj.riftstruct),
-					checkmessage(['riftstruct shoud be NaN since numrifts is 0!']);
+					md = checkmessage(md,['riftstruct shoud be NaN since numrifts is 0!']);
 				end
 			end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/settings.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/settings.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/settings.m	(revision 12878)
@@ -41,11 +41,11 @@
 			obj.waitonlock=Inf;
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			checkfield(md,'settings.io_gather','numel',1,'values',[0 1]);
-			checkfield(md,'settings.lowmem','numel',1,'values',[0 1]);
-			checkfield(md,'settings.results_as_patches','numel',1,'values',[0 1]);
-			checkfield(md,'settings.output_frequency','numel',1,'>=',1);
-			checkfield(md,'settings.waitonlock','numel',1);
+			md = checkfield(md,'settings.io_gather','numel',1,'values',[0 1]);
+			md = checkfield(md,'settings.lowmem','numel',1,'values',[0 1]);
+			md = checkfield(md,'settings.results_as_patches','numel',1,'values',[0 1]);
+			md = checkfield(md,'settings.output_frequency','numel',1,'>=',1);
+			md = checkfield(md,'settings.waitonlock','numel',1);
 
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/solver.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/solver.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/solver.m	(revision 12878)
@@ -18,5 +18,5 @@
 				 end
 			 end % }}}
-		 function obj = addoptions(obj,analysis,varargin) % {{{1
+		 function obj = addoptions(obj,analysis,varargin) % {{{
 		 % Usage example:
 		 %    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum,stokesoptions());
@@ -54,9 +54,9 @@
 			 end
 		 end % }}}
-		 function checkconsistency(obj,md,solution,analyses) % {{{
+		 function md = checkconsistency(obj,md,solution,analyses) % {{{
 			 analyses=properties(obj);
 			 for i=1:numel(analyses),
 				 if isempty(fieldnames(obj.(analyses{i})))
-					 checkmessage(['md.solver.' analyses{i} ' is empty']);
+					 md = checkmessage(md,['md.solver.' analyses{i} ' is empty']);
 				 end
 			 end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/steadystate.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/steadystate.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/steadystate.m	(revision 12878)
@@ -26,5 +26,5 @@
 			obj.reltol=0.01;
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			%Early return
@@ -32,9 +32,9 @@
 
 			if md.timestepping.time_step~=0,
-				checkmessage(['for a steadystate computation, timestepping.time_step must be zero.']);
+				md = checkmessage(md,['for a steadystate computation, timestepping.time_step must be zero.']);
 			end
 
 			if isnan(md.diagnostic.reltol),
-				checkmessage(['for a steadystate computation, diagnostic.reltol (relative convergence criterion) must be defined!']);
+				md = checkmessage(md,['for a steadystate computation, diagnostic.reltol (relative convergence criterion) must be defined!']);
 			end
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/surfaceforcings.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/surfaceforcings.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/surfaceforcings.m	(revision 12878)
@@ -8,4 +8,20 @@
 		precipitation = NaN;
 		mass_balance  = NaN;
+		ispdd = 0;
+		issmbgradients = 0;
+		isdelta18o = 0;
+	   hc = NaN;
+		smb_pos_max = NaN;
+		smb_pos_min = NaN;
+		a_pos = NaN;
+		b_pos = NaN;
+		a_neg = NaN;
+		b_neg = NaN;
+		monthlytemperatures = NaN;
+		delta18o = NaN;
+		delta18o_surface = NaN;
+		temperatures_presentday = NaN;
+		temperatures_lgm = NaN;
+		precipitations_presentday = NaN;
 	end
 	methods
@@ -19,13 +35,41 @@
 		end % }}}
 		function obj = setdefaultparameters(obj) % {{{
+		  
+		  %pdd method not used in default mode
+		  obj.ispdd=0;
+		  obj.issmbgradients=0;
+		  obj.isdelta18o=0;
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			if ismember(PrognosticAnalysisEnum,analyses),
-				checkfield(md,'surfaceforcings.mass_balance','forcing',1,'NaN',1);
+				md = checkfield(md,'surfaceforcings.ispdd','numel',1,'values',[0 1]);
+				checkfield(md,'surfaceforcings.issmbgradients','numel',1,'values',[0 1]);
+				if(obj.ispdd)
+				        if(obj.isdelta18o==0)
+				        	md = checkfield(md,'surfaceforcings.monthlytemperatures','forcing',1,'NaN',1);
+				        	md = checkfield(md,'surfaceforcings.precipitation','forcing',1,'NaN',1);
+			                else
+				                md = checkfield(md,'surfaceforcings.delta18o','NaN',1);
+				        	md = checkfield(md,'surfaceforcings.delta18o_surface','NaN',1);
+				        	md = checkfield(md,'surfaceforcings.temperatures_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+				        	md = checkfield(md,'surfaceforcings.temperatures_lgm','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+				        	md = checkfield(md,'surfaceforcings.precipitations_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+				        end
+				elseif(obj.issmbgradients)
+					checkfield(md,'surfaceforcings.hc','forcing',1,'NaN',1);
+					checkfield(md,'surfaceforcings.smb_pos_max','forcing',1,'NaN',1);
+					checkfield(md,'surfaceforcings.smb_pos_min','forcing',1,'NaN',1);
+					checkfield(md,'surfaceforcings.a_pos','forcing',1,'NaN',1);
+					checkfield(md,'surfaceforcings.b_pos','forcing',1,'NaN',1);
+					checkfield(md,'surfaceforcings.a_neg','forcing',1,'NaN',1);
+					checkfield(md,'surfaceforcings.b_neg','forcing',1,'NaN',1);
+				else
+					md = checkfield(md,'surfaceforcings.mass_balance','forcing',1,'NaN',1);
+				end
 			end
 			if ismember(BalancethicknessAnalysisEnum,analyses),
-				checkfield(md,'surfaceforcings.mass_balance','size',[md.mesh.numberofvertices 1],'NaN',1);
+				md = checkfield(md,'surfaceforcings.mass_balance','size',[md.mesh.numberofvertices 1],'NaN',1);
 			end
 		end % }}}
@@ -33,6 +77,22 @@
 			disp(sprintf('   surface forcings parameters:'));
 
+			fielddisplay(obj,'mass_balance','surface mass balance [m/yr ice eq]');
+			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,'precipitation','surface precipitation [m/yr water eq]');
-			fielddisplay(obj,'mass_balance','surface mass balance [m/yr ice 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,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if pdd is activated and delta18o activated');
+			fielddisplay(obj,'delta18o','delta18o, required if pdd is activated and delta18o activated');
+			fielddisplay(obj,'delta18o_surface','surface elevation of the delta18o site, required if pdd is activated and delta18o activated');
+			fielddisplay(obj,'issmbgradients','is smb gradients method activated (0 or 1, default is 0)');
+			fielddisplay(obj,'hc',' elevation of intersection between accumulation and ablation regime required if smb gradients is activated');
+			fielddisplay(obj,'smb_pos_max',' maximum value of positive smb required if smb gradients is activated');
+			fielddisplay(obj,'smb_pos_min',' minimum value of positive smb required if smb gradients is activated');
+			fielddisplay(obj,'a_pos',' intercept of hs - smb regression line for accumulation regime required if smb gradients is activated');
+			fielddisplay(obj,'b_pos',' slope of hs - smb regression line for accumulation regime required if smb gradients is activated');
+			fielddisplay(obj,'a_neg',' intercept of hs - smb regression line for ablation regime required if smb gradients is activated');
+			fielddisplay(obj,'b_neg',' slope of hs - smb regression line for ablation regime required if smb gradients is activated');
 
 		end % }}}
@@ -40,4 +100,29 @@
 			WriteData(fid,'object',obj,'fieldname','precipitation','format','DoubleMat','mattype',1);
 			WriteData(fid,'object',obj,'fieldname','mass_balance','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','ispdd','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isdelta18o','format','Boolean');
+			if obj.ispdd,
+			  if obj.isdelta18o
+			        WriteData(fid,'object',obj,'fieldname','temperatures_presentday','format','DoubleMat','mattype',1);
+			        WriteData(fid,'object',obj,'fieldname','temperatures_lgm','format','DoubleMat','mattype',1);
+			        WriteData(fid,'object',obj,'fieldname','precipitations_presentday','format','DoubleMat','mattype',1);
+			        WriteData(fid,'object',obj,'fieldname','delta18o_surface','format','DoubleMat','mattype',1);
+			        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);
+			  end
+			end
+			WriteData(fid,'object',obj,'fieldname','issmbgradients','format','Boolean');
+			if obj.issmbgradients,
+				WriteData(fid,'object',obj,'fieldname','hc','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'fieldname','smb_pos_max','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'fieldname','smb_pos_min','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'fieldname','a_pos','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'fieldname','b_pos','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'fieldname','a_neg','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'fieldname','b_neg','format','DoubleMat','mattype',1);
+			end
+
 		end % }}}
 	end
Index: /issm/branches/trunk-jpl-damage/src/m/classes/thermal.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/thermal.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/thermal.m	(revision 12878)
@@ -40,14 +40,14 @@
 			obj.isenthalpy=0;
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			%Early return
 			if (~ismember(ThermalAnalysisEnum,analyses) & ~ismember(EnthalpyAnalysisEnum,analyses)) | (solution==TransientSolutionEnum & md.transient.isthermal==0), return; end
 
-			checkfield(md,'thermal.stabilization','numel',1,'values',[0 1 2]);
-			checkfield(md,'thermal.spctemperature','forcing',1);
-			if (ismember(EnthalpyAnalysisEnum,analyses) & md.thermal.isenthalpy),
-			checkfield(md,'thermal.spctemperature','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*md.geometry.thickness,'message','spctemperature should be below the adjusted melting point');
-			checkfield(md,'thermal.isenthalpy','numel',1,'values',[0 1]);
+			md = checkfield(md,'thermal.stabilization','numel',1,'values',[0 1 2]);
+			md = checkfield(md,'thermal.spctemperature','forcing',1);
+			if (ismember(EnthalpyAnalysisEnum,analyses) & md.thermal.isenthalpy & md.mesh.dimension==3),
+			md = checkfield(md,'thermal.spctemperature','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*(md.geometry.surface-md.mesh.z),'message','spctemperature should be below the adjusted melting point');
+			md = checkfield(md,'thermal.isenthalpy','numel',1,'values',[0 1]);
 			end
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/timestepping.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/timestepping.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/timestepping.m	(revision 12878)
@@ -33,13 +33,13 @@
 			obj.cfl_coefficient=.5;
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			checkfield(md,'timestepping.start_time','numel',1,'NaN',1);
-			checkfield(md,'timestepping.final_time','numel',1,'NaN',1);
-			checkfield(md,'timestepping.time_step','numel',1,'>=',0,'NaN',1);
-			checkfield(md,'timestepping.time_adapt','numel',1,'values',[0 1]);
-			checkfield(md,'timestepping.cfl_coefficient','numel',1,'>',0,'<=',1);
+			md = checkfield(md,'timestepping.start_time','numel',1,'NaN',1);
+			md = checkfield(md,'timestepping.final_time','numel',1,'NaN',1);
+			md = checkfield(md,'timestepping.time_step','numel',1,'>=',0,'NaN',1);
+			md = checkfield(md,'timestepping.time_adapt','numel',1,'values',[0 1]);
+			md = checkfield(md,'timestepping.cfl_coefficient','numel',1,'>',0,'<=',1);
 			if obj.final_time-obj.start_time<0,
-				checkmessage('timestepping.final_time should be larger than timestepping.start_time');
+				md = checkmessage(md,'timestepping.final_time should be larger than timestepping.start_time');
 			end 
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/transient.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/transient.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/transient.m	(revision 12878)
@@ -30,13 +30,14 @@
 
 		end % }}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 			%Early return
 			if solution~=TransientSolutionEnum, return; end
 
-			checkfield(md,'transient.isprognostic','numel',1,'values',[0 1]);
-			checkfield(md,'transient.isdiagnostic','numel',1,'values',[0 1]);
-			checkfield(md,'transient.isthermal','numel',1,'values',[0 1]);
-			checkfield(md,'transient.isgroundingline','numel',1,'values',[0 1]);
+			md = checkfield(md,'transient.isprognostic','numel',1,'values',[0 1]);
+			md = checkfield(md,'transient.isdiagnostic','numel',1,'values',[0 1]);
+			md = checkfield(md,'transient.isthermal','numel',1,'values',[0 1]);
+			md = checkfield(md,'transient.isgroundingline','numel',1,'values',[0 1]);
+			md = checkfield(md,'transient.requested_outputs','size',[NaN 1]);
 
 		end % }}}
Index: /issm/branches/trunk-jpl-damage/src/m/classes/verbose.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/classes/verbose.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/classes/verbose.m	(revision 12878)
@@ -21,5 +21,5 @@
 classdef verbose
 	properties (SetAccess=public) 
-		% {{{1
+		% {{{
 		%BEGINFIELDS
 		mprocessor  = false;
@@ -35,5 +35,5 @@
 	%}}}
 	methods
-		function verbose=verbose(varargin) % {{{1
+		function verbose=verbose(varargin) % {{{
 
 			switch(nargin),
@@ -70,5 +70,5 @@
 		end
 		%}}}
-		function binary=VerboseToBinary(verbose) % {{{1
+		function binary=VerboseToBinary(verbose) % {{{
 
 		%BEGINVERB2BIN
@@ -85,5 +85,5 @@
 		end
 		%}}}
-		function verbose=BinaryToVerbose(verbose,binary) % {{{1
+		function verbose=BinaryToVerbose(verbose,binary) % {{{
 
 		%BEGINBIN2VERB
@@ -99,8 +99,8 @@
 		end
 		%}}}
-		function checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
 		end % }}}
-		function disp(verbose) % {{{1
+		function disp(verbose) % {{{
 			
 		%BEGINDISP
Index: sm/branches/trunk-jpl-damage/src/m/enum/DebugPetscProfilingEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/DebugPetscProfilingEnum.m	(revision 12877)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DebugPetscProfilingEnum()
-%DEBUGPETSCPROFILINGENUM - Enum of DebugPetscProfiling
-%
-%   WARNING: DO NOT 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=DebugPetscProfilingEnum()
-
-macro=StringToEnum('DebugPetscProfiling');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/DebugProfilingEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/DebugProfilingEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/DebugProfilingEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=DebugProfilingEnum()
+%DEBUGPROFILINGENUM - Enum of DebugProfiling
+%
+%   WARNING: DO NOT 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=DebugProfilingEnum()
+
+macro=StringToEnum('DebugProfiling');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/EnumDefinitions.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/EnumDefinitions.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/EnumDefinitions.py	(revision 12878)
@@ -0,0 +1,4598 @@
+"""
+
+   WARNING: DO NOT MODIFY THIS FILE
+            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+            Please read src/c/EnumDefinitions/README for more information
+
+"""
+
+def AutodiffForwardEnum():
+	"""
+	AUTODIFFFORWARDENUM - Enum of AutodiffForward
+
+	   Usage:
+	      macro=AutodiffForwardEnum()
+	"""
+
+	return StringToEnum('AutodiffForward')
+
+def AutodiffIsautodiffEnum():
+	"""
+	AUTODIFFISAUTODIFFENUM - Enum of AutodiffIsautodiff
+
+	   Usage:
+	      macro=AutodiffIsautodiffEnum()
+	"""
+
+	return StringToEnum('AutodiffIsautodiff')
+
+def AutodiffReverseEnum():
+	"""
+	AUTODIFFREVERSEENUM - Enum of AutodiffReverse
+
+	   Usage:
+	      macro=AutodiffReverseEnum()
+	"""
+
+	return StringToEnum('AutodiffReverse')
+
+def BalancethicknessSpcthicknessEnum():
+	"""
+	BALANCETHICKNESSSPCTHICKNESSENUM - Enum of BalancethicknessSpcthickness
+
+	   Usage:
+	      macro=BalancethicknessSpcthicknessEnum()
+	"""
+
+	return StringToEnum('BalancethicknessSpcthickness')
+
+def BalancethicknessStabilizationEnum():
+	"""
+	BALANCETHICKNESSSTABILIZATIONENUM - Enum of BalancethicknessStabilization
+
+	   Usage:
+	      macro=BalancethicknessStabilizationEnum()
+	"""
+
+	return StringToEnum('BalancethicknessStabilization')
+
+def BalancethicknessThickeningRateEnum():
+	"""
+	BALANCETHICKNESSTHICKENINGRATEENUM - Enum of BalancethicknessThickeningRate
+
+	   Usage:
+	      macro=BalancethicknessThickeningRateEnum()
+	"""
+
+	return StringToEnum('BalancethicknessThickeningRate')
+
+def BasalforcingsGeothermalfluxEnum():
+	"""
+	BASALFORCINGSGEOTHERMALFLUXENUM - Enum of BasalforcingsGeothermalflux
+
+	   Usage:
+	      macro=BasalforcingsGeothermalfluxEnum()
+	"""
+
+	return StringToEnum('BasalforcingsGeothermalflux')
+
+def BasalforcingsMeltingRateCorrectionEnum():
+	"""
+	BASALFORCINGSMELTINGRATECORRECTIONENUM - Enum of BasalforcingsMeltingRateCorrection
+
+	   Usage:
+	      macro=BasalforcingsMeltingRateCorrectionEnum()
+	"""
+
+	return StringToEnum('BasalforcingsMeltingRateCorrection')
+
+def BasalforcingsMeltingRateEnum():
+	"""
+	BASALFORCINGSMELTINGRATEENUM - Enum of BasalforcingsMeltingRate
+
+	   Usage:
+	      macro=BasalforcingsMeltingRateEnum()
+	"""
+
+	return StringToEnum('BasalforcingsMeltingRate')
+
+def BathymetryEnum():
+	"""
+	BATHYMETRYENUM - Enum of Bathymetry
+
+	   Usage:
+	      macro=BathymetryEnum()
+	"""
+
+	return StringToEnum('Bathymetry')
+
+def BedEnum():
+	"""
+	BEDENUM - Enum of Bed
+
+	   Usage:
+	      macro=BedEnum()
+	"""
+
+	return StringToEnum('Bed')
+
+def ConstantsGEnum():
+	"""
+	CONSTANTSGENUM - Enum of ConstantsG
+
+	   Usage:
+	      macro=ConstantsGEnum()
+	"""
+
+	return StringToEnum('ConstantsG')
+
+def ConstantsReferencetemperatureEnum():
+	"""
+	CONSTANTSREFERENCETEMPERATUREENUM - Enum of ConstantsReferencetemperature
+
+	   Usage:
+	      macro=ConstantsReferencetemperatureEnum()
+	"""
+
+	return StringToEnum('ConstantsReferencetemperature')
+
+def ConstantsYtsEnum():
+	"""
+	CONSTANTSYTSENUM - Enum of ConstantsYts
+
+	   Usage:
+	      macro=ConstantsYtsEnum()
+	"""
+
+	return StringToEnum('ConstantsYts')
+
+def DiagnosticAbstolEnum():
+	"""
+	DIAGNOSTICABSTOLENUM - Enum of DiagnosticAbstol
+
+	   Usage:
+	      macro=DiagnosticAbstolEnum()
+	"""
+
+	return StringToEnum('DiagnosticAbstol')
+
+def DiagnosticIcefrontEnum():
+	"""
+	DIAGNOSTICICEFRONTENUM - Enum of DiagnosticIcefront
+
+	   Usage:
+	      macro=DiagnosticIcefrontEnum()
+	"""
+
+	return StringToEnum('DiagnosticIcefront')
+
+def DiagnosticIsnewtonEnum():
+	"""
+	DIAGNOSTICISNEWTONENUM - Enum of DiagnosticIsnewton
+
+	   Usage:
+	      macro=DiagnosticIsnewtonEnum()
+	"""
+
+	return StringToEnum('DiagnosticIsnewton')
+
+def DiagnosticMaxiterEnum():
+	"""
+	DIAGNOSTICMAXITERENUM - Enum of DiagnosticMaxiter
+
+	   Usage:
+	      macro=DiagnosticMaxiterEnum()
+	"""
+
+	return StringToEnum('DiagnosticMaxiter')
+
+def DiagnosticNumRequestedOutputsEnum():
+	"""
+	DIAGNOSTICNUMREQUESTEDOUTPUTSENUM - Enum of DiagnosticNumRequestedOutputs
+
+	   Usage:
+	      macro=DiagnosticNumRequestedOutputsEnum()
+	"""
+
+	return StringToEnum('DiagnosticNumRequestedOutputs')
+
+def DiagnosticPenaltyFactorEnum():
+	"""
+	DIAGNOSTICPENALTYFACTORENUM - Enum of DiagnosticPenaltyFactor
+
+	   Usage:
+	      macro=DiagnosticPenaltyFactorEnum()
+	"""
+
+	return StringToEnum('DiagnosticPenaltyFactor')
+
+def DiagnosticReferentialEnum():
+	"""
+	DIAGNOSTICREFERENTIALENUM - Enum of DiagnosticReferential
+
+	   Usage:
+	      macro=DiagnosticReferentialEnum()
+	"""
+
+	return StringToEnum('DiagnosticReferential')
+
+def DiagnosticReltolEnum():
+	"""
+	DIAGNOSTICRELTOLENUM - Enum of DiagnosticReltol
+
+	   Usage:
+	      macro=DiagnosticReltolEnum()
+	"""
+
+	return StringToEnum('DiagnosticReltol')
+
+def DiagnosticRequestedOutputsEnum():
+	"""
+	DIAGNOSTICREQUESTEDOUTPUTSENUM - Enum of DiagnosticRequestedOutputs
+
+	   Usage:
+	      macro=DiagnosticRequestedOutputsEnum()
+	"""
+
+	return StringToEnum('DiagnosticRequestedOutputs')
+
+def DiagnosticRestolEnum():
+	"""
+	DIAGNOSTICRESTOLENUM - Enum of DiagnosticRestol
+
+	   Usage:
+	      macro=DiagnosticRestolEnum()
+	"""
+
+	return StringToEnum('DiagnosticRestol')
+
+def DiagnosticRiftPenaltyLockEnum():
+	"""
+	DIAGNOSTICRIFTPENALTYLOCKENUM - Enum of DiagnosticRiftPenaltyLock
+
+	   Usage:
+	      macro=DiagnosticRiftPenaltyLockEnum()
+	"""
+
+	return StringToEnum('DiagnosticRiftPenaltyLock')
+
+def DiagnosticRiftPenaltyThresholdEnum():
+	"""
+	DIAGNOSTICRIFTPENALTYTHRESHOLDENUM - Enum of DiagnosticRiftPenaltyThreshold
+
+	   Usage:
+	      macro=DiagnosticRiftPenaltyThresholdEnum()
+	"""
+
+	return StringToEnum('DiagnosticRiftPenaltyThreshold')
+
+def DiagnosticShelfDampeningEnum():
+	"""
+	DIAGNOSTICSHELFDAMPENINGENUM - Enum of DiagnosticShelfDampening
+
+	   Usage:
+	      macro=DiagnosticShelfDampeningEnum()
+	"""
+
+	return StringToEnum('DiagnosticShelfDampening')
+
+def DiagnosticSpcvxEnum():
+	"""
+	DIAGNOSTICSPCVXENUM - Enum of DiagnosticSpcvx
+
+	   Usage:
+	      macro=DiagnosticSpcvxEnum()
+	"""
+
+	return StringToEnum('DiagnosticSpcvx')
+
+def DiagnosticSpcvyEnum():
+	"""
+	DIAGNOSTICSPCVYENUM - Enum of DiagnosticSpcvy
+
+	   Usage:
+	      macro=DiagnosticSpcvyEnum()
+	"""
+
+	return StringToEnum('DiagnosticSpcvy')
+
+def DiagnosticSpcvzEnum():
+	"""
+	DIAGNOSTICSPCVZENUM - Enum of DiagnosticSpcvz
+
+	   Usage:
+	      macro=DiagnosticSpcvzEnum()
+	"""
+
+	return StringToEnum('DiagnosticSpcvz')
+
+def DiagnosticStokesreconditioningEnum():
+	"""
+	DIAGNOSTICSTOKESRECONDITIONINGENUM - Enum of DiagnosticStokesreconditioning
+
+	   Usage:
+	      macro=DiagnosticStokesreconditioningEnum()
+	"""
+
+	return StringToEnum('DiagnosticStokesreconditioning')
+
+def DiagnosticVertexPairingEnum():
+	"""
+	DIAGNOSTICVERTEXPAIRINGENUM - Enum of DiagnosticVertexPairing
+
+	   Usage:
+	      macro=DiagnosticVertexPairingEnum()
+	"""
+
+	return StringToEnum('DiagnosticVertexPairing')
+
+def DiagnosticViscosityOvershootEnum():
+	"""
+	DIAGNOSTICVISCOSITYOVERSHOOTENUM - Enum of DiagnosticViscosityOvershoot
+
+	   Usage:
+	      macro=DiagnosticViscosityOvershootEnum()
+	"""
+
+	return StringToEnum('DiagnosticViscosityOvershoot')
+
+def FlowequationBordermacayealEnum():
+	"""
+	FLOWEQUATIONBORDERMACAYEALENUM - Enum of FlowequationBordermacayeal
+
+	   Usage:
+	      macro=FlowequationBordermacayealEnum()
+	"""
+
+	return StringToEnum('FlowequationBordermacayeal')
+
+def FlowequationBorderpattynEnum():
+	"""
+	FLOWEQUATIONBORDERPATTYNENUM - Enum of FlowequationBorderpattyn
+
+	   Usage:
+	      macro=FlowequationBorderpattynEnum()
+	"""
+
+	return StringToEnum('FlowequationBorderpattyn')
+
+def FlowequationBorderstokesEnum():
+	"""
+	FLOWEQUATIONBORDERSTOKESENUM - Enum of FlowequationBorderstokes
+
+	   Usage:
+	      macro=FlowequationBorderstokesEnum()
+	"""
+
+	return StringToEnum('FlowequationBorderstokes')
+
+def FlowequationElementEquationEnum():
+	"""
+	FLOWEQUATIONELEMENTEQUATIONENUM - Enum of FlowequationElementEquation
+
+	   Usage:
+	      macro=FlowequationElementEquationEnum()
+	"""
+
+	return StringToEnum('FlowequationElementEquation')
+
+def FlowequationIshutterEnum():
+	"""
+	FLOWEQUATIONISHUTTERENUM - Enum of FlowequationIshutter
+
+	   Usage:
+	      macro=FlowequationIshutterEnum()
+	"""
+
+	return StringToEnum('FlowequationIshutter')
+
+def FlowequationIsmacayealpattynEnum():
+	"""
+	FLOWEQUATIONISMACAYEALPATTYNENUM - Enum of FlowequationIsmacayealpattyn
+
+	   Usage:
+	      macro=FlowequationIsmacayealpattynEnum()
+	"""
+
+	return StringToEnum('FlowequationIsmacayealpattyn')
+
+def FlowequationIsstokesEnum():
+	"""
+	FLOWEQUATIONISSTOKESENUM - Enum of FlowequationIsstokes
+
+	   Usage:
+	      macro=FlowequationIsstokesEnum()
+	"""
+
+	return StringToEnum('FlowequationIsstokes')
+
+def FlowequationVertexEquationEnum():
+	"""
+	FLOWEQUATIONVERTEXEQUATIONENUM - Enum of FlowequationVertexEquation
+
+	   Usage:
+	      macro=FlowequationVertexEquationEnum()
+	"""
+
+	return StringToEnum('FlowequationVertexEquation')
+
+def FrictionCoefficientEnum():
+	"""
+	FRICTIONCOEFFICIENTENUM - Enum of FrictionCoefficient
+
+	   Usage:
+	      macro=FrictionCoefficientEnum()
+	"""
+
+	return StringToEnum('FrictionCoefficient')
+
+def FrictionPEnum():
+	"""
+	FRICTIONPENUM - Enum of FrictionP
+
+	   Usage:
+	      macro=FrictionPEnum()
+	"""
+
+	return StringToEnum('FrictionP')
+
+def FrictionQEnum():
+	"""
+	FRICTIONQENUM - Enum of FrictionQ
+
+	   Usage:
+	      macro=FrictionQEnum()
+	"""
+
+	return StringToEnum('FrictionQ')
+
+def GeometryHydrostaticRatioEnum():
+	"""
+	GEOMETRYHYDROSTATICRATIOENUM - Enum of GeometryHydrostaticRatio
+
+	   Usage:
+	      macro=GeometryHydrostaticRatioEnum()
+	"""
+
+	return StringToEnum('GeometryHydrostaticRatio')
+
+def HydrologyCREnum():
+	"""
+	HYDROLOGYCRENUM - Enum of HydrologyCR
+
+	   Usage:
+	      macro=HydrologyCREnum()
+	"""
+
+	return StringToEnum('HydrologyCR')
+
+def HydrologyKnEnum():
+	"""
+	HYDROLOGYKNENUM - Enum of HydrologyKn
+
+	   Usage:
+	      macro=HydrologyKnEnum()
+	"""
+
+	return StringToEnum('HydrologyKn')
+
+def HydrologyNEnum():
+	"""
+	HYDROLOGYNENUM - Enum of HydrologyN
+
+	   Usage:
+	      macro=HydrologyNEnum()
+	"""
+
+	return StringToEnum('HydrologyN')
+
+def HydrologyPEnum():
+	"""
+	HYDROLOGYPENUM - Enum of HydrologyP
+
+	   Usage:
+	      macro=HydrologyPEnum()
+	"""
+
+	return StringToEnum('HydrologyP')
+
+def HydrologyQEnum():
+	"""
+	HYDROLOGYQENUM - Enum of HydrologyQ
+
+	   Usage:
+	      macro=HydrologyQEnum()
+	"""
+
+	return StringToEnum('HydrologyQ')
+
+def HydrologySpcwatercolumnEnum():
+	"""
+	HYDROLOGYSPCWATERCOLUMNENUM - Enum of HydrologySpcwatercolumn
+
+	   Usage:
+	      macro=HydrologySpcwatercolumnEnum()
+	"""
+
+	return StringToEnum('HydrologySpcwatercolumn')
+
+def HydrologyStabilizationEnum():
+	"""
+	HYDROLOGYSTABILIZATIONENUM - Enum of HydrologyStabilization
+
+	   Usage:
+	      macro=HydrologyStabilizationEnum()
+	"""
+
+	return StringToEnum('HydrologyStabilization')
+
+def InversionControlParametersEnum():
+	"""
+	INVERSIONCONTROLPARAMETERSENUM - Enum of InversionControlParameters
+
+	   Usage:
+	      macro=InversionControlParametersEnum()
+	"""
+
+	return StringToEnum('InversionControlParameters')
+
+def InversionCostFunctionEnum():
+	"""
+	INVERSIONCOSTFUNCTIONENUM - Enum of InversionCostFunction
+
+	   Usage:
+	      macro=InversionCostFunctionEnum()
+	"""
+
+	return StringToEnum('InversionCostFunction')
+
+def InversionCostFunctionThresholdEnum():
+	"""
+	INVERSIONCOSTFUNCTIONTHRESHOLDENUM - Enum of InversionCostFunctionThreshold
+
+	   Usage:
+	      macro=InversionCostFunctionThresholdEnum()
+	"""
+
+	return StringToEnum('InversionCostFunctionThreshold')
+
+def InversionCostFunctionsCoefficientsEnum():
+	"""
+	INVERSIONCOSTFUNCTIONSCOEFFICIENTSENUM - Enum of InversionCostFunctionsCoefficients
+
+	   Usage:
+	      macro=InversionCostFunctionsCoefficientsEnum()
+	"""
+
+	return StringToEnum('InversionCostFunctionsCoefficients')
+
+def InversionCostFunctionsEnum():
+	"""
+	INVERSIONCOSTFUNCTIONSENUM - Enum of InversionCostFunctions
+
+	   Usage:
+	      macro=InversionCostFunctionsEnum()
+	"""
+
+	return StringToEnum('InversionCostFunctions')
+
+def InversionGradientOnlyEnum():
+	"""
+	INVERSIONGRADIENTONLYENUM - Enum of InversionGradientOnly
+
+	   Usage:
+	      macro=InversionGradientOnlyEnum()
+	"""
+
+	return StringToEnum('InversionGradientOnly')
+
+def InversionGradientScalingEnum():
+	"""
+	INVERSIONGRADIENTSCALINGENUM - Enum of InversionGradientScaling
+
+	   Usage:
+	      macro=InversionGradientScalingEnum()
+	"""
+
+	return StringToEnum('InversionGradientScaling')
+
+def InversionIscontrolEnum():
+	"""
+	INVERSIONISCONTROLENUM - Enum of InversionIscontrol
+
+	   Usage:
+	      macro=InversionIscontrolEnum()
+	"""
+
+	return StringToEnum('InversionIscontrol')
+
+def InversionTaoEnum():
+	"""
+	INVERSIONTAOENUM - Enum of InversionTao
+
+	   Usage:
+	      macro=InversionTaoEnum()
+	"""
+
+	return StringToEnum('InversionTao')
+
+def InversionIncompleteAdjointEnum():
+	"""
+	INVERSIONINCOMPLETEADJOINTENUM - Enum of InversionIncompleteAdjoint
+
+	   Usage:
+	      macro=InversionIncompleteAdjointEnum()
+	"""
+
+	return StringToEnum('InversionIncompleteAdjoint')
+
+def InversionMaxParametersEnum():
+	"""
+	INVERSIONMAXPARAMETERSENUM - Enum of InversionMaxParameters
+
+	   Usage:
+	      macro=InversionMaxParametersEnum()
+	"""
+
+	return StringToEnum('InversionMaxParameters')
+
+def InversionMaxiterPerStepEnum():
+	"""
+	INVERSIONMAXITERPERSTEPENUM - Enum of InversionMaxiterPerStep
+
+	   Usage:
+	      macro=InversionMaxiterPerStepEnum()
+	"""
+
+	return StringToEnum('InversionMaxiterPerStep')
+
+def InversionMinParametersEnum():
+	"""
+	INVERSIONMINPARAMETERSENUM - Enum of InversionMinParameters
+
+	   Usage:
+	      macro=InversionMinParametersEnum()
+	"""
+
+	return StringToEnum('InversionMinParameters')
+
+def InversionNstepsEnum():
+	"""
+	INVERSIONNSTEPSENUM - Enum of InversionNsteps
+
+	   Usage:
+	      macro=InversionNstepsEnum()
+	"""
+
+	return StringToEnum('InversionNsteps')
+
+def InversionNumControlParametersEnum():
+	"""
+	INVERSIONNUMCONTROLPARAMETERSENUM - Enum of InversionNumControlParameters
+
+	   Usage:
+	      macro=InversionNumControlParametersEnum()
+	"""
+
+	return StringToEnum('InversionNumControlParameters')
+
+def InversionNumCostFunctionsEnum():
+	"""
+	INVERSIONNUMCOSTFUNCTIONSENUM - Enum of InversionNumCostFunctions
+
+	   Usage:
+	      macro=InversionNumCostFunctionsEnum()
+	"""
+
+	return StringToEnum('InversionNumCostFunctions')
+
+def InversionStepThresholdEnum():
+	"""
+	INVERSIONSTEPTHRESHOLDENUM - Enum of InversionStepThreshold
+
+	   Usage:
+	      macro=InversionStepThresholdEnum()
+	"""
+
+	return StringToEnum('InversionStepThreshold')
+
+def InversionThicknessObsEnum():
+	"""
+	INVERSIONTHICKNESSOBSENUM - Enum of InversionThicknessObs
+
+	   Usage:
+	      macro=InversionThicknessObsEnum()
+	"""
+
+	return StringToEnum('InversionThicknessObs')
+
+def InversionVelObsEnum():
+	"""
+	INVERSIONVELOBSENUM - Enum of InversionVelObs
+
+	   Usage:
+	      macro=InversionVelObsEnum()
+	"""
+
+	return StringToEnum('InversionVelObs')
+
+def InversionVxObsEnum():
+	"""
+	INVERSIONVXOBSENUM - Enum of InversionVxObs
+
+	   Usage:
+	      macro=InversionVxObsEnum()
+	"""
+
+	return StringToEnum('InversionVxObs')
+
+def InversionVyObsEnum():
+	"""
+	INVERSIONVYOBSENUM - Enum of InversionVyObs
+
+	   Usage:
+	      macro=InversionVyObsEnum()
+	"""
+
+	return StringToEnum('InversionVyObs')
+
+def InversionVzObsEnum():
+	"""
+	INVERSIONVZOBSENUM - Enum of InversionVzObs
+
+	   Usage:
+	      macro=InversionVzObsEnum()
+	"""
+
+	return StringToEnum('InversionVzObs')
+
+def MaskElementonfloatingiceEnum():
+	"""
+	MASKELEMENTONFLOATINGICEENUM - Enum of MaskElementonfloatingice
+
+	   Usage:
+	      macro=MaskElementonfloatingiceEnum()
+	"""
+
+	return StringToEnum('MaskElementonfloatingice')
+
+def MaskElementongroundediceEnum():
+	"""
+	MASKELEMENTONGROUNDEDICEENUM - Enum of MaskElementongroundedice
+
+	   Usage:
+	      macro=MaskElementongroundediceEnum()
+	"""
+
+	return StringToEnum('MaskElementongroundedice')
+
+def MaskElementonwaterEnum():
+	"""
+	MASKELEMENTONWATERENUM - Enum of MaskElementonwater
+
+	   Usage:
+	      macro=MaskElementonwaterEnum()
+	"""
+
+	return StringToEnum('MaskElementonwater')
+
+def MaskVertexonfloatingiceEnum():
+	"""
+	MASKVERTEXONFLOATINGICEENUM - Enum of MaskVertexonfloatingice
+
+	   Usage:
+	      macro=MaskVertexonfloatingiceEnum()
+	"""
+
+	return StringToEnum('MaskVertexonfloatingice')
+
+def MaskVertexongroundediceEnum():
+	"""
+	MASKVERTEXONGROUNDEDICEENUM - Enum of MaskVertexongroundedice
+
+	   Usage:
+	      macro=MaskVertexongroundediceEnum()
+	"""
+
+	return StringToEnum('MaskVertexongroundedice')
+
+def MaskVertexonwaterEnum():
+	"""
+	MASKVERTEXONWATERENUM - Enum of MaskVertexonwater
+
+	   Usage:
+	      macro=MaskVertexonwaterEnum()
+	"""
+
+	return StringToEnum('MaskVertexonwater')
+
+def MaterialsBetaEnum():
+	"""
+	MATERIALSBETAENUM - Enum of MaterialsBeta
+
+	   Usage:
+	      macro=MaterialsBetaEnum()
+	"""
+
+	return StringToEnum('MaterialsBeta')
+
+def MaterialsHeatcapacityEnum():
+	"""
+	MATERIALSHEATCAPACITYENUM - Enum of MaterialsHeatcapacity
+
+	   Usage:
+	      macro=MaterialsHeatcapacityEnum()
+	"""
+
+	return StringToEnum('MaterialsHeatcapacity')
+
+def MaterialsLatentheatEnum():
+	"""
+	MATERIALSLATENTHEATENUM - Enum of MaterialsLatentheat
+
+	   Usage:
+	      macro=MaterialsLatentheatEnum()
+	"""
+
+	return StringToEnum('MaterialsLatentheat')
+
+def MaterialsMeltingpointEnum():
+	"""
+	MATERIALSMELTINGPOINTENUM - Enum of MaterialsMeltingpoint
+
+	   Usage:
+	      macro=MaterialsMeltingpointEnum()
+	"""
+
+	return StringToEnum('MaterialsMeltingpoint')
+
+def MaterialsMixedLayerCapacityEnum():
+	"""
+	MATERIALSMIXEDLAYERCAPACITYENUM - Enum of MaterialsMixedLayerCapacity
+
+	   Usage:
+	      macro=MaterialsMixedLayerCapacityEnum()
+	"""
+
+	return StringToEnum('MaterialsMixedLayerCapacity')
+
+def MaterialsRheologyBEnum():
+	"""
+	MATERIALSRHEOLOGYBENUM - Enum of MaterialsRheologyB
+
+	   Usage:
+	      macro=MaterialsRheologyBEnum()
+	"""
+
+	return StringToEnum('MaterialsRheologyB')
+
+def MaterialsRheologyBbarEnum():
+	"""
+	MATERIALSRHEOLOGYBBARENUM - Enum of MaterialsRheologyBbar
+
+	   Usage:
+	      macro=MaterialsRheologyBbarEnum()
+	"""
+
+	return StringToEnum('MaterialsRheologyBbar')
+
+def MaterialsRheologyLawEnum():
+	"""
+	MATERIALSRHEOLOGYLAWENUM - Enum of MaterialsRheologyLaw
+
+	   Usage:
+	      macro=MaterialsRheologyLawEnum()
+	"""
+
+	return StringToEnum('MaterialsRheologyLaw')
+
+def MaterialsRheologyNEnum():
+	"""
+	MATERIALSRHEOLOGYNENUM - Enum of MaterialsRheologyN
+
+	   Usage:
+	      macro=MaterialsRheologyNEnum()
+	"""
+
+	return StringToEnum('MaterialsRheologyN')
+
+def MaterialsRheologyZEnum():
+	"""
+	MATERIALSRHEOLOGYZENUM - Enum of MaterialsRheologyZ
+
+	   Usage:
+	      macro=MaterialsRheologyZEnum()
+	"""
+
+	return StringToEnum('MaterialsRheologyZ')
+
+def MaterialsRheologyZbarEnum():
+	"""
+	MATERIALSRHEOLOGYZBARENUM - Enum of MaterialsRheologyZbar
+
+	   Usage:
+	      macro=MaterialsRheologyZbarEnum()
+	"""
+
+	return StringToEnum('MaterialsRheologyZbar')
+
+def MaterialsRhoIceEnum():
+	"""
+	MATERIALSRHOICEENUM - Enum of MaterialsRhoIce
+
+	   Usage:
+	      macro=MaterialsRhoIceEnum()
+	"""
+
+	return StringToEnum('MaterialsRhoIce')
+
+def MaterialsRhoWaterEnum():
+	"""
+	MATERIALSRHOWATERENUM - Enum of MaterialsRhoWater
+
+	   Usage:
+	      macro=MaterialsRhoWaterEnum()
+	"""
+
+	return StringToEnum('MaterialsRhoWater')
+
+def MaterialsRhoFreshwaterEnum():
+	"""
+	MATERIALSRHOFRESHWATERENUM - Enum of MaterialsRhoFreshwater
+
+	   Usage:
+	      macro=MaterialsRhoFreshwaterEnum()
+	"""
+
+	return StringToEnum('MaterialsRhoFreshwater')
+
+def MaterialsMuWaterEnum():
+	"""
+	MATERIALSMUWATERENUM - Enum of MaterialsMuWater
+
+	   Usage:
+	      macro=MaterialsMuWaterEnum()
+	"""
+
+	return StringToEnum('MaterialsMuWater')
+
+def MaterialsThermalExchangeVelocityEnum():
+	"""
+	MATERIALSTHERMALEXCHANGEVELOCITYENUM - Enum of MaterialsThermalExchangeVelocity
+
+	   Usage:
+	      macro=MaterialsThermalExchangeVelocityEnum()
+	"""
+
+	return StringToEnum('MaterialsThermalExchangeVelocity')
+
+def MaterialsThermalconductivityEnum():
+	"""
+	MATERIALSTHERMALCONDUCTIVITYENUM - Enum of MaterialsThermalconductivity
+
+	   Usage:
+	      macro=MaterialsThermalconductivityEnum()
+	"""
+
+	return StringToEnum('MaterialsThermalconductivity')
+
+def MeshAverageVertexConnectivityEnum():
+	"""
+	MESHAVERAGEVERTEXCONNECTIVITYENUM - Enum of MeshAverageVertexConnectivity
+
+	   Usage:
+	      macro=MeshAverageVertexConnectivityEnum()
+	"""
+
+	return StringToEnum('MeshAverageVertexConnectivity')
+
+def MeshDimensionEnum():
+	"""
+	MESHDIMENSIONENUM - Enum of MeshDimension
+
+	   Usage:
+	      macro=MeshDimensionEnum()
+	"""
+
+	return StringToEnum('MeshDimension')
+
+def MeshEdgesEnum():
+	"""
+	MESHEDGESENUM - Enum of MeshEdges
+
+	   Usage:
+	      macro=MeshEdgesEnum()
+	"""
+
+	return StringToEnum('MeshEdges')
+
+def MeshElementconnectivityEnum():
+	"""
+	MESHELEMENTCONNECTIVITYENUM - Enum of MeshElementconnectivity
+
+	   Usage:
+	      macro=MeshElementconnectivityEnum()
+	"""
+
+	return StringToEnum('MeshElementconnectivity')
+
+def MeshElementonbedEnum():
+	"""
+	MESHELEMENTONBEDENUM - Enum of MeshElementonbed
+
+	   Usage:
+	      macro=MeshElementonbedEnum()
+	"""
+
+	return StringToEnum('MeshElementonbed')
+
+def MeshElementonsurfaceEnum():
+	"""
+	MESHELEMENTONSURFACEENUM - Enum of MeshElementonsurface
+
+	   Usage:
+	      macro=MeshElementonsurfaceEnum()
+	"""
+
+	return StringToEnum('MeshElementonsurface')
+
+def MeshElements2dEnum():
+	"""
+	MESHELEMENTS2DENUM - Enum of MeshElements2d
+
+	   Usage:
+	      macro=MeshElements2dEnum()
+	"""
+
+	return StringToEnum('MeshElements2d')
+
+def MeshElementsEnum():
+	"""
+	MESHELEMENTSENUM - Enum of MeshElements
+
+	   Usage:
+	      macro=MeshElementsEnum()
+	"""
+
+	return StringToEnum('MeshElements')
+
+def MeshLowerelementsEnum():
+	"""
+	MESHLOWERELEMENTSENUM - Enum of MeshLowerelements
+
+	   Usage:
+	      macro=MeshLowerelementsEnum()
+	"""
+
+	return StringToEnum('MeshLowerelements')
+
+def MeshNumberofedgesEnum():
+	"""
+	MESHNUMBEROFEDGESENUM - Enum of MeshNumberofedges
+
+	   Usage:
+	      macro=MeshNumberofedgesEnum()
+	"""
+
+	return StringToEnum('MeshNumberofedges')
+
+def MeshNumberofelements2dEnum():
+	"""
+	MESHNUMBEROFELEMENTS2DENUM - Enum of MeshNumberofelements2d
+
+	   Usage:
+	      macro=MeshNumberofelements2dEnum()
+	"""
+
+	return StringToEnum('MeshNumberofelements2d')
+
+def MeshNumberofelementsEnum():
+	"""
+	MESHNUMBEROFELEMENTSENUM - Enum of MeshNumberofelements
+
+	   Usage:
+	      macro=MeshNumberofelementsEnum()
+	"""
+
+	return StringToEnum('MeshNumberofelements')
+
+def MeshNumberoflayersEnum():
+	"""
+	MESHNUMBEROFLAYERSENUM - Enum of MeshNumberoflayers
+
+	   Usage:
+	      macro=MeshNumberoflayersEnum()
+	"""
+
+	return StringToEnum('MeshNumberoflayers')
+
+def MeshNumberofvertices2dEnum():
+	"""
+	MESHNUMBEROFVERTICES2DENUM - Enum of MeshNumberofvertices2d
+
+	   Usage:
+	      macro=MeshNumberofvertices2dEnum()
+	"""
+
+	return StringToEnum('MeshNumberofvertices2d')
+
+def MeshNumberofverticesEnum():
+	"""
+	MESHNUMBEROFVERTICESENUM - Enum of MeshNumberofvertices
+
+	   Usage:
+	      macro=MeshNumberofverticesEnum()
+	"""
+
+	return StringToEnum('MeshNumberofvertices')
+
+def MeshUpperelementsEnum():
+	"""
+	MESHUPPERELEMENTSENUM - Enum of MeshUpperelements
+
+	   Usage:
+	      macro=MeshUpperelementsEnum()
+	"""
+
+	return StringToEnum('MeshUpperelements')
+
+def MeshVertexonbedEnum():
+	"""
+	MESHVERTEXONBEDENUM - Enum of MeshVertexonbed
+
+	   Usage:
+	      macro=MeshVertexonbedEnum()
+	"""
+
+	return StringToEnum('MeshVertexonbed')
+
+def MeshVertexonsurfaceEnum():
+	"""
+	MESHVERTEXONSURFACEENUM - Enum of MeshVertexonsurface
+
+	   Usage:
+	      macro=MeshVertexonsurfaceEnum()
+	"""
+
+	return StringToEnum('MeshVertexonsurface')
+
+def MeshXEnum():
+	"""
+	MESHXENUM - Enum of MeshX
+
+	   Usage:
+	      macro=MeshXEnum()
+	"""
+
+	return StringToEnum('MeshX')
+
+def MeshYEnum():
+	"""
+	MESHYENUM - Enum of MeshY
+
+	   Usage:
+	      macro=MeshYEnum()
+	"""
+
+	return StringToEnum('MeshY')
+
+def MeshZEnum():
+	"""
+	MESHZENUM - Enum of MeshZ
+
+	   Usage:
+	      macro=MeshZEnum()
+	"""
+
+	return StringToEnum('MeshZ')
+
+def MiscellaneousNameEnum():
+	"""
+	MISCELLANEOUSNAMEENUM - Enum of MiscellaneousName
+
+	   Usage:
+	      macro=MiscellaneousNameEnum()
+	"""
+
+	return StringToEnum('MiscellaneousName')
+
+def PrognosticHydrostaticAdjustmentEnum():
+	"""
+	PROGNOSTICHYDROSTATICADJUSTMENTENUM - Enum of PrognosticHydrostaticAdjustment
+
+	   Usage:
+	      macro=PrognosticHydrostaticAdjustmentEnum()
+	"""
+
+	return StringToEnum('PrognosticHydrostaticAdjustment')
+
+def PrognosticMinThicknessEnum():
+	"""
+	PROGNOSTICMINTHICKNESSENUM - Enum of PrognosticMinThickness
+
+	   Usage:
+	      macro=PrognosticMinThicknessEnum()
+	"""
+
+	return StringToEnum('PrognosticMinThickness')
+
+def PrognosticPenaltyFactorEnum():
+	"""
+	PROGNOSTICPENALTYFACTORENUM - Enum of PrognosticPenaltyFactor
+
+	   Usage:
+	      macro=PrognosticPenaltyFactorEnum()
+	"""
+
+	return StringToEnum('PrognosticPenaltyFactor')
+
+def PrognosticSpcthicknessEnum():
+	"""
+	PROGNOSTICSPCTHICKNESSENUM - Enum of PrognosticSpcthickness
+
+	   Usage:
+	      macro=PrognosticSpcthicknessEnum()
+	"""
+
+	return StringToEnum('PrognosticSpcthickness')
+
+def PrognosticStabilizationEnum():
+	"""
+	PROGNOSTICSTABILIZATIONENUM - Enum of PrognosticStabilization
+
+	   Usage:
+	      macro=PrognosticStabilizationEnum()
+	"""
+
+	return StringToEnum('PrognosticStabilization')
+
+def PrognosticVertexPairingEnum():
+	"""
+	PROGNOSTICVERTEXPAIRINGENUM - Enum of PrognosticVertexPairing
+
+	   Usage:
+	      macro=PrognosticVertexPairingEnum()
+	"""
+
+	return StringToEnum('PrognosticVertexPairing')
+
+def QmuIsdakotaEnum():
+	"""
+	QMUISDAKOTAENUM - Enum of QmuIsdakota
+
+	   Usage:
+	      macro=QmuIsdakotaEnum()
+	"""
+
+	return StringToEnum('QmuIsdakota')
+
+def QmuMassFluxSegmentsEnum():
+	"""
+	QMUMASSFLUXSEGMENTSENUM - Enum of QmuMassFluxSegments
+
+	   Usage:
+	      macro=QmuMassFluxSegmentsEnum()
+	"""
+
+	return StringToEnum('QmuMassFluxSegments')
+
+def QmuNumberofpartitionsEnum():
+	"""
+	QMUNUMBEROFPARTITIONSENUM - Enum of QmuNumberofpartitions
+
+	   Usage:
+	      macro=QmuNumberofpartitionsEnum()
+	"""
+
+	return StringToEnum('QmuNumberofpartitions')
+
+def QmuNumberofresponsesEnum():
+	"""
+	QMUNUMBEROFRESPONSESENUM - Enum of QmuNumberofresponses
+
+	   Usage:
+	      macro=QmuNumberofresponsesEnum()
+	"""
+
+	return StringToEnum('QmuNumberofresponses')
+
+def QmuPartitionEnum():
+	"""
+	QMUPARTITIONENUM - Enum of QmuPartition
+
+	   Usage:
+	      macro=QmuPartitionEnum()
+	"""
+
+	return StringToEnum('QmuPartition')
+
+def QmuResponsedescriptorsEnum():
+	"""
+	QMURESPONSEDESCRIPTORSENUM - Enum of QmuResponsedescriptors
+
+	   Usage:
+	      macro=QmuResponsedescriptorsEnum()
+	"""
+
+	return StringToEnum('QmuResponsedescriptors')
+
+def QmuVariabledescriptorsEnum():
+	"""
+	QMUVARIABLEDESCRIPTORSENUM - Enum of QmuVariabledescriptors
+
+	   Usage:
+	      macro=QmuVariabledescriptorsEnum()
+	"""
+
+	return StringToEnum('QmuVariabledescriptors')
+
+def RiftsNumriftsEnum():
+	"""
+	RIFTSNUMRIFTSENUM - Enum of RiftsNumrifts
+
+	   Usage:
+	      macro=RiftsNumriftsEnum()
+	"""
+
+	return StringToEnum('RiftsNumrifts')
+
+def RiftsRiftstructEnum():
+	"""
+	RIFTSRIFTSTRUCTENUM - Enum of RiftsRiftstruct
+
+	   Usage:
+	      macro=RiftsRiftstructEnum()
+	"""
+
+	return StringToEnum('RiftsRiftstruct')
+
+def SettingsIoGatherEnum():
+	"""
+	SETTINGSIOGATHERENUM - Enum of SettingsIoGather
+
+	   Usage:
+	      macro=SettingsIoGatherEnum()
+	"""
+
+	return StringToEnum('SettingsIoGather')
+
+def SettingsLowmemEnum():
+	"""
+	SETTINGSLOWMEMENUM - Enum of SettingsLowmem
+
+	   Usage:
+	      macro=SettingsLowmemEnum()
+	"""
+
+	return StringToEnum('SettingsLowmem')
+
+def SettingsOutputFrequencyEnum():
+	"""
+	SETTINGSOUTPUTFREQUENCYENUM - Enum of SettingsOutputFrequency
+
+	   Usage:
+	      macro=SettingsOutputFrequencyEnum()
+	"""
+
+	return StringToEnum('SettingsOutputFrequency')
+
+def SettingsResultsAsPatchesEnum():
+	"""
+	SETTINGSRESULTSASPATCHESENUM - Enum of SettingsResultsAsPatches
+
+	   Usage:
+	      macro=SettingsResultsAsPatchesEnum()
+	"""
+
+	return StringToEnum('SettingsResultsAsPatches')
+
+def SettingsWaitonlockEnum():
+	"""
+	SETTINGSWAITONLOCKENUM - Enum of SettingsWaitonlock
+
+	   Usage:
+	      macro=SettingsWaitonlockEnum()
+	"""
+
+	return StringToEnum('SettingsWaitonlock')
+
+def SurfaceforcingsDelta18oEnum():
+	"""
+	SURFACEFORCINGSDELTA18OENUM - Enum of SurfaceforcingsDelta18o
+
+	   Usage:
+	      macro=SurfaceforcingsDelta18oEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsDelta18o')
+
+def SurfaceforcingsDelta18oSurfaceEnum():
+	"""
+	SURFACEFORCINGSDELTA18OSURFACEENUM - Enum of SurfaceforcingsDelta18oSurface
+
+	   Usage:
+	      macro=SurfaceforcingsDelta18oSurfaceEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsDelta18oSurface')
+
+def SurfaceforcingsIsdelta18oEnum():
+	"""
+	SURFACEFORCINGSISDELTA18OENUM - Enum of SurfaceforcingsIsdelta18o
+
+	   Usage:
+	      macro=SurfaceforcingsIsdelta18oEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsIsdelta18o')
+
+def SurfaceforcingsPrecipitationsPresentdayEnum():
+	"""
+	SURFACEFORCINGSPRECIPITATIONSPRESENTDAYENUM - Enum of SurfaceforcingsPrecipitationsPresentday
+
+	   Usage:
+	      macro=SurfaceforcingsPrecipitationsPresentdayEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsPrecipitationsPresentday')
+
+def SurfaceforcingsTemperaturesPresentdayEnum():
+	"""
+	SURFACEFORCINGSTEMPERATURESPRESENTDAYENUM - Enum of SurfaceforcingsTemperaturesPresentday
+
+	   Usage:
+	      macro=SurfaceforcingsTemperaturesPresentdayEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsTemperaturesPresentday')
+
+def SurfaceforcingsTemperaturesLgmEnum():
+	"""
+	SURFACEFORCINGSTEMPERATURESLGMENUM - Enum of SurfaceforcingsTemperaturesLgm
+
+	   Usage:
+	      macro=SurfaceforcingsTemperaturesLgmEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsTemperaturesLgm')
+
+def DebugProfilingEnum():
+	"""
+	DEBUGPROFILINGENUM - Enum of DebugProfiling
+
+	   Usage:
+	      macro=DebugProfilingEnum()
+	"""
+
+	return StringToEnum('DebugProfiling')
+
+def ProfilingCurrentMemEnum():
+	"""
+	PROFILINGCURRENTMEMENUM - Enum of ProfilingCurrentMem
+
+	   Usage:
+	      macro=ProfilingCurrentMemEnum()
+	"""
+
+	return StringToEnum('ProfilingCurrentMem')
+
+def ProfilingCurrentFlopsEnum():
+	"""
+	PROFILINGCURRENTFLOPSENUM - Enum of ProfilingCurrentFlops
+
+	   Usage:
+	      macro=ProfilingCurrentFlopsEnum()
+	"""
+
+	return StringToEnum('ProfilingCurrentFlops')
+
+def ProfilingSolutionTimeEnum():
+	"""
+	PROFILINGSOLUTIONTIMEENUM - Enum of ProfilingSolutionTime
+
+	   Usage:
+	      macro=ProfilingSolutionTimeEnum()
+	"""
+
+	return StringToEnum('ProfilingSolutionTime')
+
+def MaxIterationConvergenceFlagEnum():
+	"""
+	MAXITERATIONCONVERGENCEFLAGENUM - Enum of MaxIterationConvergenceFlag
+
+	   Usage:
+	      macro=MaxIterationConvergenceFlagEnum()
+	"""
+
+	return StringToEnum('MaxIterationConvergenceFlag')
+
+def SteadystateMaxiterEnum():
+	"""
+	STEADYSTATEMAXITERENUM - Enum of SteadystateMaxiter
+
+	   Usage:
+	      macro=SteadystateMaxiterEnum()
+	"""
+
+	return StringToEnum('SteadystateMaxiter')
+
+def SteadystateNumRequestedOutputsEnum():
+	"""
+	STEADYSTATENUMREQUESTEDOUTPUTSENUM - Enum of SteadystateNumRequestedOutputs
+
+	   Usage:
+	      macro=SteadystateNumRequestedOutputsEnum()
+	"""
+
+	return StringToEnum('SteadystateNumRequestedOutputs')
+
+def SteadystateReltolEnum():
+	"""
+	STEADYSTATERELTOLENUM - Enum of SteadystateReltol
+
+	   Usage:
+	      macro=SteadystateReltolEnum()
+	"""
+
+	return StringToEnum('SteadystateReltol')
+
+def SteadystateRequestedOutputsEnum():
+	"""
+	STEADYSTATEREQUESTEDOUTPUTSENUM - Enum of SteadystateRequestedOutputs
+
+	   Usage:
+	      macro=SteadystateRequestedOutputsEnum()
+	"""
+
+	return StringToEnum('SteadystateRequestedOutputs')
+
+def SurfaceEnum():
+	"""
+	SURFACEENUM - Enum of Surface
+
+	   Usage:
+	      macro=SurfaceEnum()
+	"""
+
+	return StringToEnum('Surface')
+
+def SurfaceforcingsPrecipitationEnum():
+	"""
+	SURFACEFORCINGSPRECIPITATIONENUM - Enum of SurfaceforcingsPrecipitation
+
+	   Usage:
+	      macro=SurfaceforcingsPrecipitationEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsPrecipitation')
+
+def SurfaceforcingsMassBalanceEnum():
+	"""
+	SURFACEFORCINGSMASSBALANCEENUM - Enum of SurfaceforcingsMassBalance
+
+	   Usage:
+	      macro=SurfaceforcingsMassBalanceEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsMassBalance')
+
+def SurfaceforcingsIspddEnum():
+	"""
+	SURFACEFORCINGSISPDDENUM - Enum of SurfaceforcingsIspdd
+
+	   Usage:
+	      macro=SurfaceforcingsIspddEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsIspdd')
+
+def SurfaceforcingsIssmbgradientsEnum():
+	"""
+	SURFACEFORCINGSISSMBGRADIENTSENUM - Enum of SurfaceforcingsIssmbgradients
+
+	   Usage:
+	      macro=SurfaceforcingsIssmbgradientsEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsIssmbgradients')
+
+def SurfaceforcingsMonthlytemperaturesEnum():
+	"""
+	SURFACEFORCINGSMONTHLYTEMPERATURESENUM - Enum of SurfaceforcingsMonthlytemperatures
+
+	   Usage:
+	      macro=SurfaceforcingsMonthlytemperaturesEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsMonthlytemperatures')
+
+def SurfaceforcingsHcEnum():
+	"""
+	SURFACEFORCINGSHCENUM - Enum of SurfaceforcingsHc
+
+	   Usage:
+	      macro=SurfaceforcingsHcEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsHc')
+
+def SurfaceforcingsSmbPosMaxEnum():
+	"""
+	SURFACEFORCINGSSMBPOSMAXENUM - Enum of SurfaceforcingsSmbPosMax
+
+	   Usage:
+	      macro=SurfaceforcingsSmbPosMaxEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsSmbPosMax')
+
+def SurfaceforcingsSmbPosMinEnum():
+	"""
+	SURFACEFORCINGSSMBPOSMINENUM - Enum of SurfaceforcingsSmbPosMin
+
+	   Usage:
+	      macro=SurfaceforcingsSmbPosMinEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsSmbPosMin')
+
+def SurfaceforcingsAPosEnum():
+	"""
+	SURFACEFORCINGSAPOSENUM - Enum of SurfaceforcingsAPos
+
+	   Usage:
+	      macro=SurfaceforcingsAPosEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsAPos')
+
+def SurfaceforcingsBPosEnum():
+	"""
+	SURFACEFORCINGSBPOSENUM - Enum of SurfaceforcingsBPos
+
+	   Usage:
+	      macro=SurfaceforcingsBPosEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsBPos')
+
+def SurfaceforcingsANegEnum():
+	"""
+	SURFACEFORCINGSANEGENUM - Enum of SurfaceforcingsANeg
+
+	   Usage:
+	      macro=SurfaceforcingsANegEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsANeg')
+
+def SurfaceforcingsBNegEnum():
+	"""
+	SURFACEFORCINGSBNEGENUM - Enum of SurfaceforcingsBNeg
+
+	   Usage:
+	      macro=SurfaceforcingsBNegEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsBNeg')
+
+def ThermalMaxiterEnum():
+	"""
+	THERMALMAXITERENUM - Enum of ThermalMaxiter
+
+	   Usage:
+	      macro=ThermalMaxiterEnum()
+	"""
+
+	return StringToEnum('ThermalMaxiter')
+
+def ThermalPenaltyFactorEnum():
+	"""
+	THERMALPENALTYFACTORENUM - Enum of ThermalPenaltyFactor
+
+	   Usage:
+	      macro=ThermalPenaltyFactorEnum()
+	"""
+
+	return StringToEnum('ThermalPenaltyFactor')
+
+def ThermalPenaltyLockEnum():
+	"""
+	THERMALPENALTYLOCKENUM - Enum of ThermalPenaltyLock
+
+	   Usage:
+	      macro=ThermalPenaltyLockEnum()
+	"""
+
+	return StringToEnum('ThermalPenaltyLock')
+
+def ThermalPenaltyThresholdEnum():
+	"""
+	THERMALPENALTYTHRESHOLDENUM - Enum of ThermalPenaltyThreshold
+
+	   Usage:
+	      macro=ThermalPenaltyThresholdEnum()
+	"""
+
+	return StringToEnum('ThermalPenaltyThreshold')
+
+def ThermalSpctemperatureEnum():
+	"""
+	THERMALSPCTEMPERATUREENUM - Enum of ThermalSpctemperature
+
+	   Usage:
+	      macro=ThermalSpctemperatureEnum()
+	"""
+
+	return StringToEnum('ThermalSpctemperature')
+
+def ThermalStabilizationEnum():
+	"""
+	THERMALSTABILIZATIONENUM - Enum of ThermalStabilization
+
+	   Usage:
+	      macro=ThermalStabilizationEnum()
+	"""
+
+	return StringToEnum('ThermalStabilization')
+
+def ThermalIsenthalpyEnum():
+	"""
+	THERMALISENTHALPYENUM - Enum of ThermalIsenthalpy
+
+	   Usage:
+	      macro=ThermalIsenthalpyEnum()
+	"""
+
+	return StringToEnum('ThermalIsenthalpy')
+
+def ThicknessEnum():
+	"""
+	THICKNESSENUM - Enum of Thickness
+
+	   Usage:
+	      macro=ThicknessEnum()
+	"""
+
+	return StringToEnum('Thickness')
+
+def TimesteppingStartTimeEnum():
+	"""
+	TIMESTEPPINGSTARTTIMEENUM - Enum of TimesteppingStartTime
+
+	   Usage:
+	      macro=TimesteppingStartTimeEnum()
+	"""
+
+	return StringToEnum('TimesteppingStartTime')
+
+def TimesteppingFinalTimeEnum():
+	"""
+	TIMESTEPPINGFINALTIMEENUM - Enum of TimesteppingFinalTime
+
+	   Usage:
+	      macro=TimesteppingFinalTimeEnum()
+	"""
+
+	return StringToEnum('TimesteppingFinalTime')
+
+def TimesteppingCflCoefficientEnum():
+	"""
+	TIMESTEPPINGCFLCOEFFICIENTENUM - Enum of TimesteppingCflCoefficient
+
+	   Usage:
+	      macro=TimesteppingCflCoefficientEnum()
+	"""
+
+	return StringToEnum('TimesteppingCflCoefficient')
+
+def TimesteppingTimeAdaptEnum():
+	"""
+	TIMESTEPPINGTIMEADAPTENUM - Enum of TimesteppingTimeAdapt
+
+	   Usage:
+	      macro=TimesteppingTimeAdaptEnum()
+	"""
+
+	return StringToEnum('TimesteppingTimeAdapt')
+
+def TimesteppingTimeStepEnum():
+	"""
+	TIMESTEPPINGTIMESTEPENUM - Enum of TimesteppingTimeStep
+
+	   Usage:
+	      macro=TimesteppingTimeStepEnum()
+	"""
+
+	return StringToEnum('TimesteppingTimeStep')
+
+def TransientIsdiagnosticEnum():
+	"""
+	TRANSIENTISDIAGNOSTICENUM - Enum of TransientIsdiagnostic
+
+	   Usage:
+	      macro=TransientIsdiagnosticEnum()
+	"""
+
+	return StringToEnum('TransientIsdiagnostic')
+
+def TransientIsgroundinglineEnum():
+	"""
+	TRANSIENTISGROUNDINGLINEENUM - Enum of TransientIsgroundingline
+
+	   Usage:
+	      macro=TransientIsgroundinglineEnum()
+	"""
+
+	return StringToEnum('TransientIsgroundingline')
+
+def TransientIsprognosticEnum():
+	"""
+	TRANSIENTISPROGNOSTICENUM - Enum of TransientIsprognostic
+
+	   Usage:
+	      macro=TransientIsprognosticEnum()
+	"""
+
+	return StringToEnum('TransientIsprognostic')
+
+def TransientIsthermalEnum():
+	"""
+	TRANSIENTISTHERMALENUM - Enum of TransientIsthermal
+
+	   Usage:
+	      macro=TransientIsthermalEnum()
+	"""
+
+	return StringToEnum('TransientIsthermal')
+
+def TransientNumRequestedOutputsEnum():
+	"""
+	TRANSIENTNUMREQUESTEDOUTPUTSENUM - Enum of TransientNumRequestedOutputs
+
+	   Usage:
+	      macro=TransientNumRequestedOutputsEnum()
+	"""
+
+	return StringToEnum('TransientNumRequestedOutputs')
+
+def TransientRequestedOutputsEnum():
+	"""
+	TRANSIENTREQUESTEDOUTPUTSENUM - Enum of TransientRequestedOutputs
+
+	   Usage:
+	      macro=TransientRequestedOutputsEnum()
+	"""
+
+	return StringToEnum('TransientRequestedOutputs')
+
+def SolutionTypeEnum():
+	"""
+	SOLUTIONTYPEENUM - Enum of SolutionType
+
+	   Usage:
+	      macro=SolutionTypeEnum()
+	"""
+
+	return StringToEnum('SolutionType')
+
+def AnalysisTypeEnum():
+	"""
+	ANALYSISTYPEENUM - Enum of AnalysisType
+
+	   Usage:
+	      macro=AnalysisTypeEnum()
+	"""
+
+	return StringToEnum('AnalysisType')
+
+def ConfigurationTypeEnum():
+	"""
+	CONFIGURATIONTYPEENUM - Enum of ConfigurationType
+
+	   Usage:
+	      macro=ConfigurationTypeEnum()
+	"""
+
+	return StringToEnum('ConfigurationType')
+
+def AdjointBalancethicknessAnalysisEnum():
+	"""
+	ADJOINTBALANCETHICKNESSANALYSISENUM - Enum of AdjointBalancethicknessAnalysis
+
+	   Usage:
+	      macro=AdjointBalancethicknessAnalysisEnum()
+	"""
+
+	return StringToEnum('AdjointBalancethicknessAnalysis')
+
+def AdjointHorizAnalysisEnum():
+	"""
+	ADJOINTHORIZANALYSISENUM - Enum of AdjointHorizAnalysis
+
+	   Usage:
+	      macro=AdjointHorizAnalysisEnum()
+	"""
+
+	return StringToEnum('AdjointHorizAnalysis')
+
+def AdjointSolutionEnum():
+	"""
+	ADJOINTSOLUTIONENUM - Enum of AdjointSolution
+
+	   Usage:
+	      macro=AdjointSolutionEnum()
+	"""
+
+	return StringToEnum('AdjointSolution')
+
+def AnalysisCounterEnum():
+	"""
+	ANALYSISCOUNTERENUM - Enum of AnalysisCounter
+
+	   Usage:
+	      macro=AnalysisCounterEnum()
+	"""
+
+	return StringToEnum('AnalysisCounter')
+
+def BalancethicknessAnalysisEnum():
+	"""
+	BALANCETHICKNESSANALYSISENUM - Enum of BalancethicknessAnalysis
+
+	   Usage:
+	      macro=BalancethicknessAnalysisEnum()
+	"""
+
+	return StringToEnum('BalancethicknessAnalysis')
+
+def BalancethicknessSolutionEnum():
+	"""
+	BALANCETHICKNESSSOLUTIONENUM - Enum of BalancethicknessSolution
+
+	   Usage:
+	      macro=BalancethicknessSolutionEnum()
+	"""
+
+	return StringToEnum('BalancethicknessSolution')
+
+def BedSlopeAnalysisEnum():
+	"""
+	BEDSLOPEANALYSISENUM - Enum of BedSlopeAnalysis
+
+	   Usage:
+	      macro=BedSlopeAnalysisEnum()
+	"""
+
+	return StringToEnum('BedSlopeAnalysis')
+
+def BedSlopeSolutionEnum():
+	"""
+	BEDSLOPESOLUTIONENUM - Enum of BedSlopeSolution
+
+	   Usage:
+	      macro=BedSlopeSolutionEnum()
+	"""
+
+	return StringToEnum('BedSlopeSolution')
+
+def BedSlopeXAnalysisEnum():
+	"""
+	BEDSLOPEXANALYSISENUM - Enum of BedSlopeXAnalysis
+
+	   Usage:
+	      macro=BedSlopeXAnalysisEnum()
+	"""
+
+	return StringToEnum('BedSlopeXAnalysis')
+
+def BedSlopeYAnalysisEnum():
+	"""
+	BEDSLOPEYANALYSISENUM - Enum of BedSlopeYAnalysis
+
+	   Usage:
+	      macro=BedSlopeYAnalysisEnum()
+	"""
+
+	return StringToEnum('BedSlopeYAnalysis')
+
+def DiagnosticHorizAnalysisEnum():
+	"""
+	DIAGNOSTICHORIZANALYSISENUM - Enum of DiagnosticHorizAnalysis
+
+	   Usage:
+	      macro=DiagnosticHorizAnalysisEnum()
+	"""
+
+	return StringToEnum('DiagnosticHorizAnalysis')
+
+def DiagnosticHutterAnalysisEnum():
+	"""
+	DIAGNOSTICHUTTERANALYSISENUM - Enum of DiagnosticHutterAnalysis
+
+	   Usage:
+	      macro=DiagnosticHutterAnalysisEnum()
+	"""
+
+	return StringToEnum('DiagnosticHutterAnalysis')
+
+def DiagnosticSolutionEnum():
+	"""
+	DIAGNOSTICSOLUTIONENUM - Enum of DiagnosticSolution
+
+	   Usage:
+	      macro=DiagnosticSolutionEnum()
+	"""
+
+	return StringToEnum('DiagnosticSolution')
+
+def DiagnosticVertAnalysisEnum():
+	"""
+	DIAGNOSTICVERTANALYSISENUM - Enum of DiagnosticVertAnalysis
+
+	   Usage:
+	      macro=DiagnosticVertAnalysisEnum()
+	"""
+
+	return StringToEnum('DiagnosticVertAnalysis')
+
+def EnthalpyAnalysisEnum():
+	"""
+	ENTHALPYANALYSISENUM - Enum of EnthalpyAnalysis
+
+	   Usage:
+	      macro=EnthalpyAnalysisEnum()
+	"""
+
+	return StringToEnum('EnthalpyAnalysis')
+
+def EnthalpySolutionEnum():
+	"""
+	ENTHALPYSOLUTIONENUM - Enum of EnthalpySolution
+
+	   Usage:
+	      macro=EnthalpySolutionEnum()
+	"""
+
+	return StringToEnum('EnthalpySolution')
+
+def FlaimAnalysisEnum():
+	"""
+	FLAIMANALYSISENUM - Enum of FlaimAnalysis
+
+	   Usage:
+	      macro=FlaimAnalysisEnum()
+	"""
+
+	return StringToEnum('FlaimAnalysis')
+
+def FlaimSolutionEnum():
+	"""
+	FLAIMSOLUTIONENUM - Enum of FlaimSolution
+
+	   Usage:
+	      macro=FlaimSolutionEnum()
+	"""
+
+	return StringToEnum('FlaimSolution')
+
+def HydrologyAnalysisEnum():
+	"""
+	HYDROLOGYANALYSISENUM - Enum of HydrologyAnalysis
+
+	   Usage:
+	      macro=HydrologyAnalysisEnum()
+	"""
+
+	return StringToEnum('HydrologyAnalysis')
+
+def HydrologySolutionEnum():
+	"""
+	HYDROLOGYSOLUTIONENUM - Enum of HydrologySolution
+
+	   Usage:
+	      macro=HydrologySolutionEnum()
+	"""
+
+	return StringToEnum('HydrologySolution')
+
+def MeltingAnalysisEnum():
+	"""
+	MELTINGANALYSISENUM - Enum of MeltingAnalysis
+
+	   Usage:
+	      macro=MeltingAnalysisEnum()
+	"""
+
+	return StringToEnum('MeltingAnalysis')
+
+def NoneAnalysisEnum():
+	"""
+	NONEANALYSISENUM - Enum of NoneAnalysis
+
+	   Usage:
+	      macro=NoneAnalysisEnum()
+	"""
+
+	return StringToEnum('NoneAnalysis')
+
+def PrognosticAnalysisEnum():
+	"""
+	PROGNOSTICANALYSISENUM - Enum of PrognosticAnalysis
+
+	   Usage:
+	      macro=PrognosticAnalysisEnum()
+	"""
+
+	return StringToEnum('PrognosticAnalysis')
+
+def PrognosticSolutionEnum():
+	"""
+	PROGNOSTICSOLUTIONENUM - Enum of PrognosticSolution
+
+	   Usage:
+	      macro=PrognosticSolutionEnum()
+	"""
+
+	return StringToEnum('PrognosticSolution')
+
+def SteadystateSolutionEnum():
+	"""
+	STEADYSTATESOLUTIONENUM - Enum of SteadystateSolution
+
+	   Usage:
+	      macro=SteadystateSolutionEnum()
+	"""
+
+	return StringToEnum('SteadystateSolution')
+
+def SurfaceSlopeAnalysisEnum():
+	"""
+	SURFACESLOPEANALYSISENUM - Enum of SurfaceSlopeAnalysis
+
+	   Usage:
+	      macro=SurfaceSlopeAnalysisEnum()
+	"""
+
+	return StringToEnum('SurfaceSlopeAnalysis')
+
+def SurfaceSlopeSolutionEnum():
+	"""
+	SURFACESLOPESOLUTIONENUM - Enum of SurfaceSlopeSolution
+
+	   Usage:
+	      macro=SurfaceSlopeSolutionEnum()
+	"""
+
+	return StringToEnum('SurfaceSlopeSolution')
+
+def SurfaceSlopeXAnalysisEnum():
+	"""
+	SURFACESLOPEXANALYSISENUM - Enum of SurfaceSlopeXAnalysis
+
+	   Usage:
+	      macro=SurfaceSlopeXAnalysisEnum()
+	"""
+
+	return StringToEnum('SurfaceSlopeXAnalysis')
+
+def SurfaceSlopeYAnalysisEnum():
+	"""
+	SURFACESLOPEYANALYSISENUM - Enum of SurfaceSlopeYAnalysis
+
+	   Usage:
+	      macro=SurfaceSlopeYAnalysisEnum()
+	"""
+
+	return StringToEnum('SurfaceSlopeYAnalysis')
+
+def ThermalAnalysisEnum():
+	"""
+	THERMALANALYSISENUM - Enum of ThermalAnalysis
+
+	   Usage:
+	      macro=ThermalAnalysisEnum()
+	"""
+
+	return StringToEnum('ThermalAnalysis')
+
+def ThermalSolutionEnum():
+	"""
+	THERMALSOLUTIONENUM - Enum of ThermalSolution
+
+	   Usage:
+	      macro=ThermalSolutionEnum()
+	"""
+
+	return StringToEnum('ThermalSolution')
+
+def TransientSolutionEnum():
+	"""
+	TRANSIENTSOLUTIONENUM - Enum of TransientSolution
+
+	   Usage:
+	      macro=TransientSolutionEnum()
+	"""
+
+	return StringToEnum('TransientSolution')
+
+def ApproximationEnum():
+	"""
+	APPROXIMATIONENUM - Enum of Approximation
+
+	   Usage:
+	      macro=ApproximationEnum()
+	"""
+
+	return StringToEnum('Approximation')
+
+def HutterApproximationEnum():
+	"""
+	HUTTERAPPROXIMATIONENUM - Enum of HutterApproximation
+
+	   Usage:
+	      macro=HutterApproximationEnum()
+	"""
+
+	return StringToEnum('HutterApproximation')
+
+def MacAyealApproximationEnum():
+	"""
+	MACAYEALAPPROXIMATIONENUM - Enum of MacAyealApproximation
+
+	   Usage:
+	      macro=MacAyealApproximationEnum()
+	"""
+
+	return StringToEnum('MacAyealApproximation')
+
+def MacAyealPattynApproximationEnum():
+	"""
+	MACAYEALPATTYNAPPROXIMATIONENUM - Enum of MacAyealPattynApproximation
+
+	   Usage:
+	      macro=MacAyealPattynApproximationEnum()
+	"""
+
+	return StringToEnum('MacAyealPattynApproximation')
+
+def MacAyealStokesApproximationEnum():
+	"""
+	MACAYEALSTOKESAPPROXIMATIONENUM - Enum of MacAyealStokesApproximation
+
+	   Usage:
+	      macro=MacAyealStokesApproximationEnum()
+	"""
+
+	return StringToEnum('MacAyealStokesApproximation')
+
+def NoneApproximationEnum():
+	"""
+	NONEAPPROXIMATIONENUM - Enum of NoneApproximation
+
+	   Usage:
+	      macro=NoneApproximationEnum()
+	"""
+
+	return StringToEnum('NoneApproximation')
+
+def PattynApproximationEnum():
+	"""
+	PATTYNAPPROXIMATIONENUM - Enum of PattynApproximation
+
+	   Usage:
+	      macro=PattynApproximationEnum()
+	"""
+
+	return StringToEnum('PattynApproximation')
+
+def PattynStokesApproximationEnum():
+	"""
+	PATTYNSTOKESAPPROXIMATIONENUM - Enum of PattynStokesApproximation
+
+	   Usage:
+	      macro=PattynStokesApproximationEnum()
+	"""
+
+	return StringToEnum('PattynStokesApproximation')
+
+def StokesApproximationEnum():
+	"""
+	STOKESAPPROXIMATIONENUM - Enum of StokesApproximation
+
+	   Usage:
+	      macro=StokesApproximationEnum()
+	"""
+
+	return StringToEnum('StokesApproximation')
+
+def ConstraintsEnum():
+	"""
+	CONSTRAINTSENUM - Enum of Constraints
+
+	   Usage:
+	      macro=ConstraintsEnum()
+	"""
+
+	return StringToEnum('Constraints')
+
+def LoadsEnum():
+	"""
+	LOADSENUM - Enum of Loads
+
+	   Usage:
+	      macro=LoadsEnum()
+	"""
+
+	return StringToEnum('Loads')
+
+def MaterialsEnum():
+	"""
+	MATERIALSENUM - Enum of Materials
+
+	   Usage:
+	      macro=MaterialsEnum()
+	"""
+
+	return StringToEnum('Materials')
+
+def NodesEnum():
+	"""
+	NODESENUM - Enum of Nodes
+
+	   Usage:
+	      macro=NodesEnum()
+	"""
+
+	return StringToEnum('Nodes')
+
+def ParametersEnum():
+	"""
+	PARAMETERSENUM - Enum of Parameters
+
+	   Usage:
+	      macro=ParametersEnum()
+	"""
+
+	return StringToEnum('Parameters')
+
+def VerticesEnum():
+	"""
+	VERTICESENUM - Enum of Vertices
+
+	   Usage:
+	      macro=VerticesEnum()
+	"""
+
+	return StringToEnum('Vertices')
+
+def ResultsEnum():
+	"""
+	RESULTSENUM - Enum of Results
+
+	   Usage:
+	      macro=ResultsEnum()
+	"""
+
+	return StringToEnum('Results')
+
+def BoolInputEnum():
+	"""
+	BOOLINPUTENUM - Enum of BoolInput
+
+	   Usage:
+	      macro=BoolInputEnum()
+	"""
+
+	return StringToEnum('BoolInput')
+
+def BoolParamEnum():
+	"""
+	BOOLPARAMENUM - Enum of BoolParam
+
+	   Usage:
+	      macro=BoolParamEnum()
+	"""
+
+	return StringToEnum('BoolParam')
+
+def ContourEnum():
+	"""
+	CONTOURENUM - Enum of Contour
+
+	   Usage:
+	      macro=ContourEnum()
+	"""
+
+	return StringToEnum('Contour')
+
+def ControlInputEnum():
+	"""
+	CONTROLINPUTENUM - Enum of ControlInput
+
+	   Usage:
+	      macro=ControlInputEnum()
+	"""
+
+	return StringToEnum('ControlInput')
+
+def DatasetInputEnum():
+	"""
+	DATASETINPUTENUM - Enum of DatasetInput
+
+	   Usage:
+	      macro=DatasetInputEnum()
+	"""
+
+	return StringToEnum('DatasetInput')
+
+def DofIndexingEnum():
+	"""
+	DOFINDEXINGENUM - Enum of DofIndexing
+
+	   Usage:
+	      macro=DofIndexingEnum()
+	"""
+
+	return StringToEnum('DofIndexing')
+
+def DoubleInputEnum():
+	"""
+	DOUBLEINPUTENUM - Enum of DoubleInput
+
+	   Usage:
+	      macro=DoubleInputEnum()
+	"""
+
+	return StringToEnum('DoubleInput')
+
+def DoubleMatArrayParamEnum():
+	"""
+	DOUBLEMATARRAYPARAMENUM - Enum of DoubleMatArrayParam
+
+	   Usage:
+	      macro=DoubleMatArrayParamEnum()
+	"""
+
+	return StringToEnum('DoubleMatArrayParam')
+
+def DoubleMatParamEnum():
+	"""
+	DOUBLEMATPARAMENUM - Enum of DoubleMatParam
+
+	   Usage:
+	      macro=DoubleMatParamEnum()
+	"""
+
+	return StringToEnum('DoubleMatParam')
+
+def DoubleParamEnum():
+	"""
+	DOUBLEPARAMENUM - Enum of DoubleParam
+
+	   Usage:
+	      macro=DoubleParamEnum()
+	"""
+
+	return StringToEnum('DoubleParam')
+
+def DoubleVecParamEnum():
+	"""
+	DOUBLEVECPARAMENUM - Enum of DoubleVecParam
+
+	   Usage:
+	      macro=DoubleVecParamEnum()
+	"""
+
+	return StringToEnum('DoubleVecParam')
+
+def ElementEnum():
+	"""
+	ELEMENTENUM - Enum of Element
+
+	   Usage:
+	      macro=ElementEnum()
+	"""
+
+	return StringToEnum('Element')
+
+def ElementResultEnum():
+	"""
+	ELEMENTRESULTENUM - Enum of ElementResult
+
+	   Usage:
+	      macro=ElementResultEnum()
+	"""
+
+	return StringToEnum('ElementResult')
+
+def ExternalResultEnum():
+	"""
+	EXTERNALRESULTENUM - Enum of ExternalResult
+
+	   Usage:
+	      macro=ExternalResultEnum()
+	"""
+
+	return StringToEnum('ExternalResult')
+
+def FileParamEnum():
+	"""
+	FILEPARAMENUM - Enum of FileParam
+
+	   Usage:
+	      macro=FileParamEnum()
+	"""
+
+	return StringToEnum('FileParam')
+
+def HookEnum():
+	"""
+	HOOKENUM - Enum of Hook
+
+	   Usage:
+	      macro=HookEnum()
+	"""
+
+	return StringToEnum('Hook')
+
+def IcefrontEnum():
+	"""
+	ICEFRONTENUM - Enum of Icefront
+
+	   Usage:
+	      macro=IcefrontEnum()
+	"""
+
+	return StringToEnum('Icefront')
+
+def InputEnum():
+	"""
+	INPUTENUM - Enum of Input
+
+	   Usage:
+	      macro=InputEnum()
+	"""
+
+	return StringToEnum('Input')
+
+def IntInputEnum():
+	"""
+	INTINPUTENUM - Enum of IntInput
+
+	   Usage:
+	      macro=IntInputEnum()
+	"""
+
+	return StringToEnum('IntInput')
+
+def IntParamEnum():
+	"""
+	INTPARAMENUM - Enum of IntParam
+
+	   Usage:
+	      macro=IntParamEnum()
+	"""
+
+	return StringToEnum('IntParam')
+
+def IntVecParamEnum():
+	"""
+	INTVECPARAMENUM - Enum of IntVecParam
+
+	   Usage:
+	      macro=IntVecParamEnum()
+	"""
+
+	return StringToEnum('IntVecParam')
+
+def TransientParamEnum():
+	"""
+	TRANSIENTPARAMENUM - Enum of TransientParam
+
+	   Usage:
+	      macro=TransientParamEnum()
+	"""
+
+	return StringToEnum('TransientParam')
+
+def MacAyeal2dIceFrontEnum():
+	"""
+	MACAYEAL2DICEFRONTENUM - Enum of MacAyeal2dIceFront
+
+	   Usage:
+	      macro=MacAyeal2dIceFrontEnum()
+	"""
+
+	return StringToEnum('MacAyeal2dIceFront')
+
+def MacAyeal3dIceFrontEnum():
+	"""
+	MACAYEAL3DICEFRONTENUM - Enum of MacAyeal3dIceFront
+
+	   Usage:
+	      macro=MacAyeal3dIceFrontEnum()
+	"""
+
+	return StringToEnum('MacAyeal3dIceFront')
+
+def MaticeEnum():
+	"""
+	MATICEENUM - Enum of Matice
+
+	   Usage:
+	      macro=MaticeEnum()
+	"""
+
+	return StringToEnum('Matice')
+
+def MatparEnum():
+	"""
+	MATPARENUM - Enum of Matpar
+
+	   Usage:
+	      macro=MatparEnum()
+	"""
+
+	return StringToEnum('Matpar')
+
+def NodeEnum():
+	"""
+	NODEENUM - Enum of Node
+
+	   Usage:
+	      macro=NodeEnum()
+	"""
+
+	return StringToEnum('Node')
+
+def NumericalfluxEnum():
+	"""
+	NUMERICALFLUXENUM - Enum of Numericalflux
+
+	   Usage:
+	      macro=NumericalfluxEnum()
+	"""
+
+	return StringToEnum('Numericalflux')
+
+def ParamEnum():
+	"""
+	PARAMENUM - Enum of Param
+
+	   Usage:
+	      macro=ParamEnum()
+	"""
+
+	return StringToEnum('Param')
+
+def PattynIceFrontEnum():
+	"""
+	PATTYNICEFRONTENUM - Enum of PattynIceFront
+
+	   Usage:
+	      macro=PattynIceFrontEnum()
+	"""
+
+	return StringToEnum('PattynIceFront')
+
+def PengridEnum():
+	"""
+	PENGRIDENUM - Enum of Pengrid
+
+	   Usage:
+	      macro=PengridEnum()
+	"""
+
+	return StringToEnum('Pengrid')
+
+def PenpairEnum():
+	"""
+	PENPAIRENUM - Enum of Penpair
+
+	   Usage:
+	      macro=PenpairEnum()
+	"""
+
+	return StringToEnum('Penpair')
+
+def PentaEnum():
+	"""
+	PENTAENUM - Enum of Penta
+
+	   Usage:
+	      macro=PentaEnum()
+	"""
+
+	return StringToEnum('Penta')
+
+def PentaP1InputEnum():
+	"""
+	PENTAP1INPUTENUM - Enum of PentaP1Input
+
+	   Usage:
+	      macro=PentaP1InputEnum()
+	"""
+
+	return StringToEnum('PentaP1Input')
+
+def MatrixParamEnum():
+	"""
+	MATRIXPARAMENUM - Enum of MatrixParam
+
+	   Usage:
+	      macro=MatrixParamEnum()
+	"""
+
+	return StringToEnum('MatrixParam')
+
+def VectorParamEnum():
+	"""
+	VECTORPARAMENUM - Enum of VectorParam
+
+	   Usage:
+	      macro=VectorParamEnum()
+	"""
+
+	return StringToEnum('VectorParam')
+
+def RiftfrontEnum():
+	"""
+	RIFTFRONTENUM - Enum of Riftfront
+
+	   Usage:
+	      macro=RiftfrontEnum()
+	"""
+
+	return StringToEnum('Riftfront')
+
+def SegmentEnum():
+	"""
+	SEGMENTENUM - Enum of Segment
+
+	   Usage:
+	      macro=SegmentEnum()
+	"""
+
+	return StringToEnum('Segment')
+
+def SegmentRiftfrontEnum():
+	"""
+	SEGMENTRIFTFRONTENUM - Enum of SegmentRiftfront
+
+	   Usage:
+	      macro=SegmentRiftfrontEnum()
+	"""
+
+	return StringToEnum('SegmentRiftfront')
+
+def SpcDynamicEnum():
+	"""
+	SPCDYNAMICENUM - Enum of SpcDynamic
+
+	   Usage:
+	      macro=SpcDynamicEnum()
+	"""
+
+	return StringToEnum('SpcDynamic')
+
+def SpcStaticEnum():
+	"""
+	SPCSTATICENUM - Enum of SpcStatic
+
+	   Usage:
+	      macro=SpcStaticEnum()
+	"""
+
+	return StringToEnum('SpcStatic')
+
+def SpcTransientEnum():
+	"""
+	SPCTRANSIENTENUM - Enum of SpcTransient
+
+	   Usage:
+	      macro=SpcTransientEnum()
+	"""
+
+	return StringToEnum('SpcTransient')
+
+def StokesIceFrontEnum():
+	"""
+	STOKESICEFRONTENUM - Enum of StokesIceFront
+
+	   Usage:
+	      macro=StokesIceFrontEnum()
+	"""
+
+	return StringToEnum('StokesIceFront')
+
+def StringArrayParamEnum():
+	"""
+	STRINGARRAYPARAMENUM - Enum of StringArrayParam
+
+	   Usage:
+	      macro=StringArrayParamEnum()
+	"""
+
+	return StringToEnum('StringArrayParam')
+
+def StringParamEnum():
+	"""
+	STRINGPARAMENUM - Enum of StringParam
+
+	   Usage:
+	      macro=StringParamEnum()
+	"""
+
+	return StringToEnum('StringParam')
+
+def TriaEnum():
+	"""
+	TRIAENUM - Enum of Tria
+
+	   Usage:
+	      macro=TriaEnum()
+	"""
+
+	return StringToEnum('Tria')
+
+def TriaP1InputEnum():
+	"""
+	TRIAP1INPUTENUM - Enum of TriaP1Input
+
+	   Usage:
+	      macro=TriaP1InputEnum()
+	"""
+
+	return StringToEnum('TriaP1Input')
+
+def VertexEnum():
+	"""
+	VERTEXENUM - Enum of Vertex
+
+	   Usage:
+	      macro=VertexEnum()
+	"""
+
+	return StringToEnum('Vertex')
+
+def AirEnum():
+	"""
+	AIRENUM - Enum of Air
+
+	   Usage:
+	      macro=AirEnum()
+	"""
+
+	return StringToEnum('Air')
+
+def IceEnum():
+	"""
+	ICEENUM - Enum of Ice
+
+	   Usage:
+	      macro=IceEnum()
+	"""
+
+	return StringToEnum('Ice')
+
+def MelangeEnum():
+	"""
+	MELANGEENUM - Enum of Melange
+
+	   Usage:
+	      macro=MelangeEnum()
+	"""
+
+	return StringToEnum('Melange')
+
+def WaterEnum():
+	"""
+	WATERENUM - Enum of Water
+
+	   Usage:
+	      macro=WaterEnum()
+	"""
+
+	return StringToEnum('Water')
+
+def ClosedEnum():
+	"""
+	CLOSEDENUM - Enum of Closed
+
+	   Usage:
+	      macro=ClosedEnum()
+	"""
+
+	return StringToEnum('Closed')
+
+def FreeEnum():
+	"""
+	FREEENUM - Enum of Free
+
+	   Usage:
+	      macro=FreeEnum()
+	"""
+
+	return StringToEnum('Free')
+
+def OpenEnum():
+	"""
+	OPENENUM - Enum of Open
+
+	   Usage:
+	      macro=OpenEnum()
+	"""
+
+	return StringToEnum('Open')
+
+def AdjointpEnum():
+	"""
+	ADJOINTPENUM - Enum of Adjointp
+
+	   Usage:
+	      macro=AdjointpEnum()
+	"""
+
+	return StringToEnum('Adjointp')
+
+def AdjointxEnum():
+	"""
+	ADJOINTXENUM - Enum of Adjointx
+
+	   Usage:
+	      macro=AdjointxEnum()
+	"""
+
+	return StringToEnum('Adjointx')
+
+def AdjointyEnum():
+	"""
+	ADJOINTYENUM - Enum of Adjointy
+
+	   Usage:
+	      macro=AdjointyEnum()
+	"""
+
+	return StringToEnum('Adjointy')
+
+def AdjointzEnum():
+	"""
+	ADJOINTZENUM - Enum of Adjointz
+
+	   Usage:
+	      macro=AdjointzEnum()
+	"""
+
+	return StringToEnum('Adjointz')
+
+def BedSlopeXEnum():
+	"""
+	BEDSLOPEXENUM - Enum of BedSlopeX
+
+	   Usage:
+	      macro=BedSlopeXEnum()
+	"""
+
+	return StringToEnum('BedSlopeX')
+
+def BedSlopeYEnum():
+	"""
+	BEDSLOPEYENUM - Enum of BedSlopeY
+
+	   Usage:
+	      macro=BedSlopeYEnum()
+	"""
+
+	return StringToEnum('BedSlopeY')
+
+def BoundaryEnum():
+	"""
+	BOUNDARYENUM - Enum of Boundary
+
+	   Usage:
+	      macro=BoundaryEnum()
+	"""
+
+	return StringToEnum('Boundary')
+
+def ConstantEnum():
+	"""
+	CONSTANTENUM - Enum of Constant
+
+	   Usage:
+	      macro=ConstantEnum()
+	"""
+
+	return StringToEnum('Constant')
+
+def ConvergedEnum():
+	"""
+	CONVERGEDENUM - Enum of Converged
+
+	   Usage:
+	      macro=ConvergedEnum()
+	"""
+
+	return StringToEnum('Converged')
+
+def ExtToIuEnum():
+	"""
+	EXTTOIUENUM - Enum of ExtToIu
+
+	   Usage:
+	      macro=ExtToIuEnum()
+	"""
+
+	return StringToEnum('ExtToIu')
+
+def FillEnum():
+	"""
+	FILLENUM - Enum of Fill
+
+	   Usage:
+	      macro=FillEnum()
+	"""
+
+	return StringToEnum('Fill')
+
+def FractionIncrementEnum():
+	"""
+	FRACTIONINCREMENTENUM - Enum of FractionIncrement
+
+	   Usage:
+	      macro=FractionIncrementEnum()
+	"""
+
+	return StringToEnum('FractionIncrement')
+
+def FrictionEnum():
+	"""
+	FRICTIONENUM - Enum of Friction
+
+	   Usage:
+	      macro=FrictionEnum()
+	"""
+
+	return StringToEnum('Friction')
+
+def GroundinglineMeltingRateEnum():
+	"""
+	GROUNDINGLINEMELTINGRATEENUM - Enum of GroundinglineMeltingRate
+
+	   Usage:
+	      macro=GroundinglineMeltingRateEnum()
+	"""
+
+	return StringToEnum('GroundinglineMeltingRate')
+
+def InternalEnum():
+	"""
+	INTERNALENUM - Enum of Internal
+
+	   Usage:
+	      macro=InternalEnum()
+	"""
+
+	return StringToEnum('Internal')
+
+def IuToExtEnum():
+	"""
+	IUTOEXTENUM - Enum of IuToExt
+
+	   Usage:
+	      macro=IuToExtEnum()
+	"""
+
+	return StringToEnum('IuToExt')
+
+def MassFluxEnum():
+	"""
+	MASSFLUXENUM - Enum of MassFlux
+
+	   Usage:
+	      macro=MassFluxEnum()
+	"""
+
+	return StringToEnum('MassFlux')
+
+def MaxPenetrationEnum():
+	"""
+	MAXPENETRATIONENUM - Enum of MaxPenetration
+
+	   Usage:
+	      macro=MaxPenetrationEnum()
+	"""
+
+	return StringToEnum('MaxPenetration')
+
+def MeltingOffsetEnum():
+	"""
+	MELTINGOFFSETENUM - Enum of MeltingOffset
+
+	   Usage:
+	      macro=MeltingOffsetEnum()
+	"""
+
+	return StringToEnum('MeltingOffset')
+
+def MisfitEnum():
+	"""
+	MISFITENUM - Enum of Misfit
+
+	   Usage:
+	      macro=MisfitEnum()
+	"""
+
+	return StringToEnum('Misfit')
+
+def NumberNodeToElementConnectivityEnum():
+	"""
+	NUMBERNODETOELEMENTCONNECTIVITYENUM - Enum of NumberNodeToElementConnectivity
+
+	   Usage:
+	      macro=NumberNodeToElementConnectivityEnum()
+	"""
+
+	return StringToEnum('NumberNodeToElementConnectivity')
+
+def PressureEnum():
+	"""
+	PRESSUREENUM - Enum of Pressure
+
+	   Usage:
+	      macro=PressureEnum()
+	"""
+
+	return StringToEnum('Pressure')
+
+def PressurePicardEnum():
+	"""
+	PRESSUREPICARDENUM - Enum of PressurePicard
+
+	   Usage:
+	      macro=PressurePicardEnum()
+	"""
+
+	return StringToEnum('PressurePicard')
+
+def QmuPressureEnum():
+	"""
+	QMUPRESSUREENUM - Enum of QmuPressure
+
+	   Usage:
+	      macro=QmuPressureEnum()
+	"""
+
+	return StringToEnum('QmuPressure')
+
+def QmuVxEnum():
+	"""
+	QMUVXENUM - Enum of QmuVx
+
+	   Usage:
+	      macro=QmuVxEnum()
+	"""
+
+	return StringToEnum('QmuVx')
+
+def QmuVyEnum():
+	"""
+	QMUVYENUM - Enum of QmuVy
+
+	   Usage:
+	      macro=QmuVyEnum()
+	"""
+
+	return StringToEnum('QmuVy')
+
+def QmuVzEnum():
+	"""
+	QMUVZENUM - Enum of QmuVz
+
+	   Usage:
+	      macro=QmuVzEnum()
+	"""
+
+	return StringToEnum('QmuVz')
+
+def QmuThicknessEnum():
+	"""
+	QMUTHICKNESSENUM - Enum of QmuThickness
+
+	   Usage:
+	      macro=QmuThicknessEnum()
+	"""
+
+	return StringToEnum('QmuThickness')
+
+def QmuBedEnum():
+	"""
+	QMUBEDENUM - Enum of QmuBed
+
+	   Usage:
+	      macro=QmuBedEnum()
+	"""
+
+	return StringToEnum('QmuBed')
+
+def QmuSurfaceEnum():
+	"""
+	QMUSURFACEENUM - Enum of QmuSurface
+
+	   Usage:
+	      macro=QmuSurfaceEnum()
+	"""
+
+	return StringToEnum('QmuSurface')
+
+def QmuMeltingEnum():
+	"""
+	QMUMELTINGENUM - Enum of QmuMelting
+
+	   Usage:
+	      macro=QmuMeltingEnum()
+	"""
+
+	return StringToEnum('QmuMelting')
+
+def ResetPenaltiesEnum():
+	"""
+	RESETPENALTIESENUM - Enum of ResetPenalties
+
+	   Usage:
+	      macro=ResetPenaltiesEnum()
+	"""
+
+	return StringToEnum('ResetPenalties')
+
+def SegmentOnIceShelfEnum():
+	"""
+	SEGMENTONICESHELFENUM - Enum of SegmentOnIceShelf
+
+	   Usage:
+	      macro=SegmentOnIceShelfEnum()
+	"""
+
+	return StringToEnum('SegmentOnIceShelf')
+
+def SurfaceAbsVelMisfitEnum():
+	"""
+	SURFACEABSVELMISFITENUM - Enum of SurfaceAbsVelMisfit
+
+	   Usage:
+	      macro=SurfaceAbsVelMisfitEnum()
+	"""
+
+	return StringToEnum('SurfaceAbsVelMisfit')
+
+def SurfaceAreaEnum():
+	"""
+	SURFACEAREAENUM - Enum of SurfaceArea
+
+	   Usage:
+	      macro=SurfaceAreaEnum()
+	"""
+
+	return StringToEnum('SurfaceArea')
+
+def SurfaceAverageVelMisfitEnum():
+	"""
+	SURFACEAVERAGEVELMISFITENUM - Enum of SurfaceAverageVelMisfit
+
+	   Usage:
+	      macro=SurfaceAverageVelMisfitEnum()
+	"""
+
+	return StringToEnum('SurfaceAverageVelMisfit')
+
+def SurfaceLogVelMisfitEnum():
+	"""
+	SURFACELOGVELMISFITENUM - Enum of SurfaceLogVelMisfit
+
+	   Usage:
+	      macro=SurfaceLogVelMisfitEnum()
+	"""
+
+	return StringToEnum('SurfaceLogVelMisfit')
+
+def SurfaceLogVxVyMisfitEnum():
+	"""
+	SURFACELOGVXVYMISFITENUM - Enum of SurfaceLogVxVyMisfit
+
+	   Usage:
+	      macro=SurfaceLogVxVyMisfitEnum()
+	"""
+
+	return StringToEnum('SurfaceLogVxVyMisfit')
+
+def SurfaceRelVelMisfitEnum():
+	"""
+	SURFACERELVELMISFITENUM - Enum of SurfaceRelVelMisfit
+
+	   Usage:
+	      macro=SurfaceRelVelMisfitEnum()
+	"""
+
+	return StringToEnum('SurfaceRelVelMisfit')
+
+def SurfaceSlopeXEnum():
+	"""
+	SURFACESLOPEXENUM - Enum of SurfaceSlopeX
+
+	   Usage:
+	      macro=SurfaceSlopeXEnum()
+	"""
+
+	return StringToEnum('SurfaceSlopeX')
+
+def SurfaceSlopeYEnum():
+	"""
+	SURFACESLOPEYENUM - Enum of SurfaceSlopeY
+
+	   Usage:
+	      macro=SurfaceSlopeYEnum()
+	"""
+
+	return StringToEnum('SurfaceSlopeY')
+
+def TemperatureEnum():
+	"""
+	TEMPERATUREENUM - Enum of Temperature
+
+	   Usage:
+	      macro=TemperatureEnum()
+	"""
+
+	return StringToEnum('Temperature')
+
+def TemperatureOldEnum():
+	"""
+	TEMPERATUREOLDENUM - Enum of TemperatureOld
+
+	   Usage:
+	      macro=TemperatureOldEnum()
+	"""
+
+	return StringToEnum('TemperatureOld')
+
+def TemperaturePicardEnum():
+	"""
+	TEMPERATUREPICARDENUM - Enum of TemperaturePicard
+
+	   Usage:
+	      macro=TemperaturePicardEnum()
+	"""
+
+	return StringToEnum('TemperaturePicard')
+
+def ThicknessAbsMisfitEnum():
+	"""
+	THICKNESSABSMISFITENUM - Enum of ThicknessAbsMisfit
+
+	   Usage:
+	      macro=ThicknessAbsMisfitEnum()
+	"""
+
+	return StringToEnum('ThicknessAbsMisfit')
+
+def TypeEnum():
+	"""
+	TYPEENUM - Enum of Type
+
+	   Usage:
+	      macro=TypeEnum()
+	"""
+
+	return StringToEnum('Type')
+
+def VelEnum():
+	"""
+	VELENUM - Enum of Vel
+
+	   Usage:
+	      macro=VelEnum()
+	"""
+
+	return StringToEnum('Vel')
+
+def VelocityEnum():
+	"""
+	VELOCITYENUM - Enum of Velocity
+
+	   Usage:
+	      macro=VelocityEnum()
+	"""
+
+	return StringToEnum('Velocity')
+
+def VxAverageEnum():
+	"""
+	VXAVERAGEENUM - Enum of VxAverage
+
+	   Usage:
+	      macro=VxAverageEnum()
+	"""
+
+	return StringToEnum('VxAverage')
+
+def VxEnum():
+	"""
+	VXENUM - Enum of Vx
+
+	   Usage:
+	      macro=VxEnum()
+	"""
+
+	return StringToEnum('Vx')
+
+def VxPicardEnum():
+	"""
+	VXPICARDENUM - Enum of VxPicard
+
+	   Usage:
+	      macro=VxPicardEnum()
+	"""
+
+	return StringToEnum('VxPicard')
+
+def VyAverageEnum():
+	"""
+	VYAVERAGEENUM - Enum of VyAverage
+
+	   Usage:
+	      macro=VyAverageEnum()
+	"""
+
+	return StringToEnum('VyAverage')
+
+def VyEnum():
+	"""
+	VYENUM - Enum of Vy
+
+	   Usage:
+	      macro=VyEnum()
+	"""
+
+	return StringToEnum('Vy')
+
+def VyPicardEnum():
+	"""
+	VYPICARDENUM - Enum of VyPicard
+
+	   Usage:
+	      macro=VyPicardEnum()
+	"""
+
+	return StringToEnum('VyPicard')
+
+def VzEnum():
+	"""
+	VZENUM - Enum of Vz
+
+	   Usage:
+	      macro=VzEnum()
+	"""
+
+	return StringToEnum('Vz')
+
+def VzMacAyealEnum():
+	"""
+	VZMACAYEALENUM - Enum of VzMacAyeal
+
+	   Usage:
+	      macro=VzMacAyealEnum()
+	"""
+
+	return StringToEnum('VzMacAyeal')
+
+def VzPattynEnum():
+	"""
+	VZPATTYNENUM - Enum of VzPattyn
+
+	   Usage:
+	      macro=VzPattynEnum()
+	"""
+
+	return StringToEnum('VzPattyn')
+
+def VzPicardEnum():
+	"""
+	VZPICARDENUM - Enum of VzPicard
+
+	   Usage:
+	      macro=VzPicardEnum()
+	"""
+
+	return StringToEnum('VzPicard')
+
+def VzStokesEnum():
+	"""
+	VZSTOKESENUM - Enum of VzStokes
+
+	   Usage:
+	      macro=VzStokesEnum()
+	"""
+
+	return StringToEnum('VzStokes')
+
+def VxMeshEnum():
+	"""
+	VXMESHENUM - Enum of VxMesh
+
+	   Usage:
+	      macro=VxMeshEnum()
+	"""
+
+	return StringToEnum('VxMesh')
+
+def VyMeshEnum():
+	"""
+	VYMESHENUM - Enum of VyMesh
+
+	   Usage:
+	      macro=VyMeshEnum()
+	"""
+
+	return StringToEnum('VyMesh')
+
+def VzMeshEnum():
+	"""
+	VZMESHENUM - Enum of VzMesh
+
+	   Usage:
+	      macro=VzMeshEnum()
+	"""
+
+	return StringToEnum('VzMesh')
+
+def EnthalpyEnum():
+	"""
+	ENTHALPYENUM - Enum of Enthalpy
+
+	   Usage:
+	      macro=EnthalpyEnum()
+	"""
+
+	return StringToEnum('Enthalpy')
+
+def EnthalpyPicardEnum():
+	"""
+	ENTHALPYPICARDENUM - Enum of EnthalpyPicard
+
+	   Usage:
+	      macro=EnthalpyPicardEnum()
+	"""
+
+	return StringToEnum('EnthalpyPicard')
+
+def ThicknessAbsGradientEnum():
+	"""
+	THICKNESSABSGRADIENTENUM - Enum of ThicknessAbsGradient
+
+	   Usage:
+	      macro=ThicknessAbsGradientEnum()
+	"""
+
+	return StringToEnum('ThicknessAbsGradient')
+
+def StepResponsesEnum():
+	"""
+	STEPRESPONSESENUM - Enum of StepResponses
+
+	   Usage:
+	      macro=StepResponsesEnum()
+	"""
+
+	return StringToEnum('StepResponses')
+
+def IntMatParamEnum():
+	"""
+	INTMATPARAMENUM - Enum of IntMatParam
+
+	   Usage:
+	      macro=IntMatParamEnum()
+	"""
+
+	return StringToEnum('IntMatParam')
+
+def RheologyBbarAbsGradientEnum():
+	"""
+	RHEOLOGYBBARABSGRADIENTENUM - Enum of RheologyBbarAbsGradient
+
+	   Usage:
+	      macro=RheologyBbarAbsGradientEnum()
+	"""
+
+	return StringToEnum('RheologyBbarAbsGradient')
+
+def DragCoefficientAbsGradientEnum():
+	"""
+	DRAGCOEFFICIENTABSGRADIENTENUM - Enum of DragCoefficientAbsGradient
+
+	   Usage:
+	      macro=DragCoefficientAbsGradientEnum()
+	"""
+
+	return StringToEnum('DragCoefficientAbsGradient')
+
+def TransientInputEnum():
+	"""
+	TRANSIENTINPUTENUM - Enum of TransientInput
+
+	   Usage:
+	      macro=TransientInputEnum()
+	"""
+
+	return StringToEnum('TransientInput')
+
+def OutputfilenameEnum():
+	"""
+	OUTPUTFILENAMEENUM - Enum of Outputfilename
+
+	   Usage:
+	      macro=OutputfilenameEnum()
+	"""
+
+	return StringToEnum('Outputfilename')
+
+def WaterfractionEnum():
+	"""
+	WATERFRACTIONENUM - Enum of Waterfraction
+
+	   Usage:
+	      macro=WaterfractionEnum()
+	"""
+
+	return StringToEnum('Waterfraction')
+
+def WatercolumnEnum():
+	"""
+	WATERCOLUMNENUM - Enum of Watercolumn
+
+	   Usage:
+	      macro=WatercolumnEnum()
+	"""
+
+	return StringToEnum('Watercolumn')
+
+def BasalFrictionEnum():
+	"""
+	BASALFRICTIONENUM - Enum of BasalFriction
+
+	   Usage:
+	      macro=BasalFrictionEnum()
+	"""
+
+	return StringToEnum('BasalFriction')
+
+def ViscousHeatingEnum():
+	"""
+	VISCOUSHEATINGENUM - Enum of ViscousHeating
+
+	   Usage:
+	      macro=ViscousHeatingEnum()
+	"""
+
+	return StringToEnum('ViscousHeating')
+
+def QmuTemperatureEnum():
+	"""
+	QMUTEMPERATUREENUM - Enum of QmuTemperature
+
+	   Usage:
+	      macro=QmuTemperatureEnum()
+	"""
+
+	return StringToEnum('QmuTemperature')
+
+def HydrologyWaterVxEnum():
+	"""
+	HYDROLOGYWATERVXENUM - Enum of HydrologyWaterVx
+
+	   Usage:
+	      macro=HydrologyWaterVxEnum()
+	"""
+
+	return StringToEnum('HydrologyWaterVx')
+
+def HydrologyWaterVyEnum():
+	"""
+	HYDROLOGYWATERVYENUM - Enum of HydrologyWaterVy
+
+	   Usage:
+	      macro=HydrologyWaterVyEnum()
+	"""
+
+	return StringToEnum('HydrologyWaterVy')
+
+def StressTensorEnum():
+	"""
+	STRESSTENSORENUM - Enum of StressTensor
+
+	   Usage:
+	      macro=StressTensorEnum()
+	"""
+
+	return StringToEnum('StressTensor')
+
+def StressTensorxxEnum():
+	"""
+	STRESSTENSORXXENUM - Enum of StressTensorxx
+
+	   Usage:
+	      macro=StressTensorxxEnum()
+	"""
+
+	return StringToEnum('StressTensorxx')
+
+def StressTensorxyEnum():
+	"""
+	STRESSTENSORXYENUM - Enum of StressTensorxy
+
+	   Usage:
+	      macro=StressTensorxyEnum()
+	"""
+
+	return StringToEnum('StressTensorxy')
+
+def StressTensorxzEnum():
+	"""
+	STRESSTENSORXZENUM - Enum of StressTensorxz
+
+	   Usage:
+	      macro=StressTensorxzEnum()
+	"""
+
+	return StringToEnum('StressTensorxz')
+
+def StressTensoryyEnum():
+	"""
+	STRESSTENSORYYENUM - Enum of StressTensoryy
+
+	   Usage:
+	      macro=StressTensoryyEnum()
+	"""
+
+	return StringToEnum('StressTensoryy')
+
+def StressTensoryzEnum():
+	"""
+	STRESSTENSORYZENUM - Enum of StressTensoryz
+
+	   Usage:
+	      macro=StressTensoryzEnum()
+	"""
+
+	return StringToEnum('StressTensoryz')
+
+def StressTensorzzEnum():
+	"""
+	STRESSTENSORZZENUM - Enum of StressTensorzz
+
+	   Usage:
+	      macro=StressTensorzzEnum()
+	"""
+
+	return StringToEnum('StressTensorzz')
+
+def IceVolumeEnum():
+	"""
+	ICEVOLUMEENUM - Enum of IceVolume
+
+	   Usage:
+	      macro=IceVolumeEnum()
+	"""
+
+	return StringToEnum('IceVolume')
+
+def TotalSmbEnum():
+	"""
+	TOTALSMBENUM - Enum of TotalSmb
+
+	   Usage:
+	      macro=TotalSmbEnum()
+	"""
+
+	return StringToEnum('TotalSmb')
+
+def P0Enum():
+	"""
+	P0ENUM - Enum of P0
+
+	   Usage:
+	      macro=P0Enum()
+	"""
+
+	return StringToEnum('P0')
+
+def P1Enum():
+	"""
+	P1ENUM - Enum of P1
+
+	   Usage:
+	      macro=P1Enum()
+	"""
+
+	return StringToEnum('P1')
+
+def P1DGEnum():
+	"""
+	P1DGENUM - Enum of P1DG
+
+	   Usage:
+	      macro=P1DGEnum()
+	"""
+
+	return StringToEnum('P1DG')
+
+def SaveResultsEnum():
+	"""
+	SAVERESULTSENUM - Enum of SaveResults
+
+	   Usage:
+	      macro=SaveResultsEnum()
+	"""
+
+	return StringToEnum('SaveResults')
+
+def BoolElementResultEnum():
+	"""
+	BOOLELEMENTRESULTENUM - Enum of BoolElementResult
+
+	   Usage:
+	      macro=BoolElementResultEnum()
+	"""
+
+	return StringToEnum('BoolElementResult')
+
+def BoolExternalResultEnum():
+	"""
+	BOOLEXTERNALRESULTENUM - Enum of BoolExternalResult
+
+	   Usage:
+	      macro=BoolExternalResultEnum()
+	"""
+
+	return StringToEnum('BoolExternalResult')
+
+def DoubleElementResultEnum():
+	"""
+	DOUBLEELEMENTRESULTENUM - Enum of DoubleElementResult
+
+	   Usage:
+	      macro=DoubleElementResultEnum()
+	"""
+
+	return StringToEnum('DoubleElementResult')
+
+def DoubleExternalResultEnum():
+	"""
+	DOUBLEEXTERNALRESULTENUM - Enum of DoubleExternalResult
+
+	   Usage:
+	      macro=DoubleExternalResultEnum()
+	"""
+
+	return StringToEnum('DoubleExternalResult')
+
+def DoubleMatExternalResultEnum():
+	"""
+	DOUBLEMATEXTERNALRESULTENUM - Enum of DoubleMatExternalResult
+
+	   Usage:
+	      macro=DoubleMatExternalResultEnum()
+	"""
+
+	return StringToEnum('DoubleMatExternalResult')
+
+def DoubleVecExternalResultEnum():
+	"""
+	DOUBLEVECEXTERNALRESULTENUM - Enum of DoubleVecExternalResult
+
+	   Usage:
+	      macro=DoubleVecExternalResultEnum()
+	"""
+
+	return StringToEnum('DoubleVecExternalResult')
+
+def IntExternalResultEnum():
+	"""
+	INTEXTERNALRESULTENUM - Enum of IntExternalResult
+
+	   Usage:
+	      macro=IntExternalResultEnum()
+	"""
+
+	return StringToEnum('IntExternalResult')
+
+def JEnum():
+	"""
+	JENUM - Enum of J
+
+	   Usage:
+	      macro=JEnum()
+	"""
+
+	return StringToEnum('J')
+
+def PatchEnum():
+	"""
+	PATCHENUM - Enum of Patch
+
+	   Usage:
+	      macro=PatchEnum()
+	"""
+
+	return StringToEnum('Patch')
+
+def PatchNodesEnum():
+	"""
+	PATCHNODESENUM - Enum of PatchNodes
+
+	   Usage:
+	      macro=PatchNodesEnum()
+	"""
+
+	return StringToEnum('PatchNodes')
+
+def PatchVerticesEnum():
+	"""
+	PATCHVERTICESENUM - Enum of PatchVertices
+
+	   Usage:
+	      macro=PatchVerticesEnum()
+	"""
+
+	return StringToEnum('PatchVertices')
+
+def PentaP1ElementResultEnum():
+	"""
+	PENTAP1ELEMENTRESULTENUM - Enum of PentaP1ElementResult
+
+	   Usage:
+	      macro=PentaP1ElementResultEnum()
+	"""
+
+	return StringToEnum('PentaP1ElementResult')
+
+def PetscVecExternalResultEnum():
+	"""
+	PETSCVECEXTERNALRESULTENUM - Enum of PetscVecExternalResult
+
+	   Usage:
+	      macro=PetscVecExternalResultEnum()
+	"""
+
+	return StringToEnum('PetscVecExternalResult')
+
+def StringExternalResultEnum():
+	"""
+	STRINGEXTERNALRESULTENUM - Enum of StringExternalResult
+
+	   Usage:
+	      macro=StringExternalResultEnum()
+	"""
+
+	return StringToEnum('StringExternalResult')
+
+def StepEnum():
+	"""
+	STEPENUM - Enum of Step
+
+	   Usage:
+	      macro=StepEnum()
+	"""
+
+	return StringToEnum('Step')
+
+def TimeEnum():
+	"""
+	TIMEENUM - Enum of Time
+
+	   Usage:
+	      macro=TimeEnum()
+	"""
+
+	return StringToEnum('Time')
+
+def TriaP1ElementResultEnum():
+	"""
+	TRIAP1ELEMENTRESULTENUM - Enum of TriaP1ElementResult
+
+	   Usage:
+	      macro=TriaP1ElementResultEnum()
+	"""
+
+	return StringToEnum('TriaP1ElementResult')
+
+def WaterColumnOldEnum():
+	"""
+	WATERCOLUMNOLDENUM - Enum of WaterColumnOld
+
+	   Usage:
+	      macro=WaterColumnOldEnum()
+	"""
+
+	return StringToEnum('WaterColumnOld')
+
+def MinVelEnum():
+	"""
+	MINVELENUM - Enum of MinVel
+
+	   Usage:
+	      macro=MinVelEnum()
+	"""
+
+	return StringToEnum('MinVel')
+
+def MaxVelEnum():
+	"""
+	MAXVELENUM - Enum of MaxVel
+
+	   Usage:
+	      macro=MaxVelEnum()
+	"""
+
+	return StringToEnum('MaxVel')
+
+def MinVxEnum():
+	"""
+	MINVXENUM - Enum of MinVx
+
+	   Usage:
+	      macro=MinVxEnum()
+	"""
+
+	return StringToEnum('MinVx')
+
+def MaxVxEnum():
+	"""
+	MAXVXENUM - Enum of MaxVx
+
+	   Usage:
+	      macro=MaxVxEnum()
+	"""
+
+	return StringToEnum('MaxVx')
+
+def MaxAbsVxEnum():
+	"""
+	MAXABSVXENUM - Enum of MaxAbsVx
+
+	   Usage:
+	      macro=MaxAbsVxEnum()
+	"""
+
+	return StringToEnum('MaxAbsVx')
+
+def MinVyEnum():
+	"""
+	MINVYENUM - Enum of MinVy
+
+	   Usage:
+	      macro=MinVyEnum()
+	"""
+
+	return StringToEnum('MinVy')
+
+def MaxVyEnum():
+	"""
+	MAXVYENUM - Enum of MaxVy
+
+	   Usage:
+	      macro=MaxVyEnum()
+	"""
+
+	return StringToEnum('MaxVy')
+
+def MaxAbsVyEnum():
+	"""
+	MAXABSVYENUM - Enum of MaxAbsVy
+
+	   Usage:
+	      macro=MaxAbsVyEnum()
+	"""
+
+	return StringToEnum('MaxAbsVy')
+
+def MinVzEnum():
+	"""
+	MINVZENUM - Enum of MinVz
+
+	   Usage:
+	      macro=MinVzEnum()
+	"""
+
+	return StringToEnum('MinVz')
+
+def MaxVzEnum():
+	"""
+	MAXVZENUM - Enum of MaxVz
+
+	   Usage:
+	      macro=MaxVzEnum()
+	"""
+
+	return StringToEnum('MaxVz')
+
+def MaxAbsVzEnum():
+	"""
+	MAXABSVZENUM - Enum of MaxAbsVz
+
+	   Usage:
+	      macro=MaxAbsVzEnum()
+	"""
+
+	return StringToEnum('MaxAbsVz')
+
+def RelativeEnum():
+	"""
+	RELATIVEENUM - Enum of Relative
+
+	   Usage:
+	      macro=RelativeEnum()
+	"""
+
+	return StringToEnum('Relative')
+
+def AbsoluteEnum():
+	"""
+	ABSOLUTEENUM - Enum of Absolute
+
+	   Usage:
+	      macro=AbsoluteEnum()
+	"""
+
+	return StringToEnum('Absolute')
+
+def IncrementalEnum():
+	"""
+	INCREMENTALENUM - Enum of Incremental
+
+	   Usage:
+	      macro=IncrementalEnum()
+	"""
+
+	return StringToEnum('Incremental')
+
+def AgressiveMigrationEnum():
+	"""
+	AGRESSIVEMIGRATIONENUM - Enum of AgressiveMigration
+
+	   Usage:
+	      macro=AgressiveMigrationEnum()
+	"""
+
+	return StringToEnum('AgressiveMigration')
+
+def NoneEnum():
+	"""
+	NONEENUM - Enum of None
+
+	   Usage:
+	      macro=NoneEnum()
+	"""
+
+	return StringToEnum('None')
+
+def SoftMigrationEnum():
+	"""
+	SOFTMIGRATIONENUM - Enum of SoftMigration
+
+	   Usage:
+	      macro=SoftMigrationEnum()
+	"""
+
+	return StringToEnum('SoftMigration')
+
+def StokesSolverEnum():
+	"""
+	STOKESSOLVERENUM - Enum of StokesSolver
+
+	   Usage:
+	      macro=StokesSolverEnum()
+	"""
+
+	return StringToEnum('StokesSolver')
+
+def AdjointEnum():
+	"""
+	ADJOINTENUM - Enum of Adjoint
+
+	   Usage:
+	      macro=AdjointEnum()
+	"""
+
+	return StringToEnum('Adjoint')
+
+def ColinearEnum():
+	"""
+	COLINEARENUM - Enum of Colinear
+
+	   Usage:
+	      macro=ColinearEnum()
+	"""
+
+	return StringToEnum('Colinear')
+
+def ControlSteadyEnum():
+	"""
+	CONTROLSTEADYENUM - Enum of ControlSteady
+
+	   Usage:
+	      macro=ControlSteadyEnum()
+	"""
+
+	return StringToEnum('ControlSteady')
+
+def FsetEnum():
+	"""
+	FSETENUM - Enum of Fset
+
+	   Usage:
+	      macro=FsetEnum()
+	"""
+
+	return StringToEnum('Fset')
+
+def Gradient1Enum():
+	"""
+	GRADIENT1ENUM - Enum of Gradient1
+
+	   Usage:
+	      macro=Gradient1Enum()
+	"""
+
+	return StringToEnum('Gradient1')
+
+def Gradient2Enum():
+	"""
+	GRADIENT2ENUM - Enum of Gradient2
+
+	   Usage:
+	      macro=Gradient2Enum()
+	"""
+
+	return StringToEnum('Gradient2')
+
+def Gradient3Enum():
+	"""
+	GRADIENT3ENUM - Enum of Gradient3
+
+	   Usage:
+	      macro=Gradient3Enum()
+	"""
+
+	return StringToEnum('Gradient3')
+
+def GradientEnum():
+	"""
+	GRADIENTENUM - Enum of Gradient
+
+	   Usage:
+	      macro=GradientEnum()
+	"""
+
+	return StringToEnum('Gradient')
+
+def GroundinglineMigrationEnum():
+	"""
+	GROUNDINGLINEMIGRATIONENUM - Enum of GroundinglineMigration
+
+	   Usage:
+	      macro=GroundinglineMigrationEnum()
+	"""
+
+	return StringToEnum('GroundinglineMigration')
+
+def GsetEnum():
+	"""
+	GSETENUM - Enum of Gset
+
+	   Usage:
+	      macro=GsetEnum()
+	"""
+
+	return StringToEnum('Gset')
+
+def IndexEnum():
+	"""
+	INDEXENUM - Enum of Index
+
+	   Usage:
+	      macro=IndexEnum()
+	"""
+
+	return StringToEnum('Index')
+
+def IndexedEnum():
+	"""
+	INDEXEDENUM - Enum of Indexed
+
+	   Usage:
+	      macro=IndexedEnum()
+	"""
+
+	return StringToEnum('Indexed')
+
+def IntersectEnum():
+	"""
+	INTERSECTENUM - Enum of Intersect
+
+	   Usage:
+	      macro=IntersectEnum()
+	"""
+
+	return StringToEnum('Intersect')
+
+def NodalEnum():
+	"""
+	NODALENUM - Enum of Nodal
+
+	   Usage:
+	      macro=NodalEnum()
+	"""
+
+	return StringToEnum('Nodal')
+
+def OldGradientEnum():
+	"""
+	OLDGRADIENTENUM - Enum of OldGradient
+
+	   Usage:
+	      macro=OldGradientEnum()
+	"""
+
+	return StringToEnum('OldGradient')
+
+def OutputFilePointerEnum():
+	"""
+	OUTPUTFILEPOINTERENUM - Enum of OutputFilePointer
+
+	   Usage:
+	      macro=OutputFilePointerEnum()
+	"""
+
+	return StringToEnum('OutputFilePointer')
+
+def PetscOptionsAnalysesEnum():
+	"""
+	PETSCOPTIONSANALYSESENUM - Enum of PetscOptionsAnalyses
+
+	   Usage:
+	      macro=PetscOptionsAnalysesEnum()
+	"""
+
+	return StringToEnum('PetscOptionsAnalyses')
+
+def PetscOptionsStringsEnum():
+	"""
+	PETSCOPTIONSSTRINGSENUM - Enum of PetscOptionsStrings
+
+	   Usage:
+	      macro=PetscOptionsStringsEnum()
+	"""
+
+	return StringToEnum('PetscOptionsStrings')
+
+def QmuErrNameEnum():
+	"""
+	QMUERRNAMEENUM - Enum of QmuErrName
+
+	   Usage:
+	      macro=QmuErrNameEnum()
+	"""
+
+	return StringToEnum('QmuErrName')
+
+def QmuInNameEnum():
+	"""
+	QMUINNAMEENUM - Enum of QmuInName
+
+	   Usage:
+	      macro=QmuInNameEnum()
+	"""
+
+	return StringToEnum('QmuInName')
+
+def QmuOutNameEnum():
+	"""
+	QMUOUTNAMEENUM - Enum of QmuOutName
+
+	   Usage:
+	      macro=QmuOutNameEnum()
+	"""
+
+	return StringToEnum('QmuOutName')
+
+def RegularEnum():
+	"""
+	REGULARENUM - Enum of Regular
+
+	   Usage:
+	      macro=RegularEnum()
+	"""
+
+	return StringToEnum('Regular')
+
+def ScaledEnum():
+	"""
+	SCALEDENUM - Enum of Scaled
+
+	   Usage:
+	      macro=ScaledEnum()
+	"""
+
+	return StringToEnum('Scaled')
+
+def SeparateEnum():
+	"""
+	SEPARATEENUM - Enum of Separate
+
+	   Usage:
+	      macro=SeparateEnum()
+	"""
+
+	return StringToEnum('Separate')
+
+def SsetEnum():
+	"""
+	SSETENUM - Enum of Sset
+
+	   Usage:
+	      macro=SsetEnum()
+	"""
+
+	return StringToEnum('Sset')
+
+def VerboseEnum():
+	"""
+	VERBOSEENUM - Enum of Verbose
+
+	   Usage:
+	      macro=VerboseEnum()
+	"""
+
+	return StringToEnum('Verbose')
+
+def TriangleInterpEnum():
+	"""
+	TRIANGLEINTERPENUM - Enum of TriangleInterp
+
+	   Usage:
+	      macro=TriangleInterpEnum()
+	"""
+
+	return StringToEnum('TriangleInterp')
+
+def BilinearInterpEnum():
+	"""
+	BILINEARINTERPENUM - Enum of BilinearInterp
+
+	   Usage:
+	      macro=BilinearInterpEnum()
+	"""
+
+	return StringToEnum('BilinearInterp')
+
+def NearestInterpEnum():
+	"""
+	NEARESTINTERPENUM - Enum of NearestInterp
+
+	   Usage:
+	      macro=NearestInterpEnum()
+	"""
+
+	return StringToEnum('NearestInterp')
+
+def XYEnum():
+	"""
+	XYENUM - Enum of XY
+
+	   Usage:
+	      macro=XYEnum()
+	"""
+
+	return StringToEnum('XY')
+
+def XYZPEnum():
+	"""
+	XYZPENUM - Enum of XYZP
+
+	   Usage:
+	      macro=XYZPEnum()
+	"""
+
+	return StringToEnum('XYZP')
+
+def OptionEnum():
+	"""
+	OPTIONENUM - Enum of Option
+
+	   Usage:
+	      macro=OptionEnum()
+	"""
+
+	return StringToEnum('Option')
+
+def OptionCellEnum():
+	"""
+	OPTIONCELLENUM - Enum of OptionCell
+
+	   Usage:
+	      macro=OptionCellEnum()
+	"""
+
+	return StringToEnum('OptionCell')
+
+def OptionCharEnum():
+	"""
+	OPTIONCHARENUM - Enum of OptionChar
+
+	   Usage:
+	      macro=OptionCharEnum()
+	"""
+
+	return StringToEnum('OptionChar')
+
+def OptionStructEnum():
+	"""
+	OPTIONSTRUCTENUM - Enum of OptionStruct
+
+	   Usage:
+	      macro=OptionStructEnum()
+	"""
+
+	return StringToEnum('OptionStruct')
+
+def OptionDoubleEnum():
+	"""
+	OPTIONDOUBLEENUM - Enum of OptionDouble
+
+	   Usage:
+	      macro=OptionDoubleEnum()
+	"""
+
+	return StringToEnum('OptionDouble')
+
+def OptionLogicalEnum():
+	"""
+	OPTIONLOGICALENUM - Enum of OptionLogical
+
+	   Usage:
+	      macro=OptionLogicalEnum()
+	"""
+
+	return StringToEnum('OptionLogical')
+
+def PatersonEnum():
+	"""
+	PATERSONENUM - Enum of Paterson
+
+	   Usage:
+	      macro=PatersonEnum()
+	"""
+
+	return StringToEnum('Paterson')
+
+def ArrheniusEnum():
+	"""
+	ARRHENIUSENUM - Enum of Arrhenius
+
+	   Usage:
+	      macro=ArrheniusEnum()
+	"""
+
+	return StringToEnum('Arrhenius')
+
+def MaximumNumberOfEnums():
+	"""
+	MAXIMUMNUMBEROFENUMS - Enum of MaximumNumberOfEnums
+
+	   Usage:
+	      macro=MaximumNumberOfEnums()
+	"""
+
+	return 458
+
Index: /issm/branches/trunk-jpl-damage/src/m/enum/MaterialsRhoFreshwaterEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/MaterialsRhoFreshwaterEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/MaterialsRhoFreshwaterEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=MaterialsRhoFreshwaterEnum()
+%MATERIALSRHOFRESHWATERENUM - Enum of MaterialsRhoFreshwater
+%
+%   WARNING: DO NOT 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=MaterialsRhoFreshwaterEnum()
+
+macro=StringToEnum('MaterialsRhoFreshwater');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/MaximumNumberOfEnums.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/MaximumNumberOfEnums.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/MaximumNumberOfEnums.m	(revision 12878)
@@ -9,3 +9,3 @@
 %      macro=MaximumNumberOfEnums()
 
-macro=439;
+macro=458;
Index: sm/branches/trunk-jpl-damage/src/m/enum/PetscProfilingCurrentFlopsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/PetscProfilingCurrentFlopsEnum.m	(revision 12877)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PetscProfilingCurrentFlopsEnum()
-%PETSCPROFILINGCURRENTFLOPSENUM - Enum of PetscProfilingCurrentFlops
-%
-%   WARNING: DO NOT 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=PetscProfilingCurrentFlopsEnum()
-
-macro=StringToEnum('PetscProfilingCurrentFlops');
Index: sm/branches/trunk-jpl-damage/src/m/enum/PetscProfilingCurrentMemEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/PetscProfilingCurrentMemEnum.m	(revision 12877)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PetscProfilingCurrentMemEnum()
-%PETSCPROFILINGCURRENTMEMENUM - Enum of PetscProfilingCurrentMem
-%
-%   WARNING: DO NOT 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=PetscProfilingCurrentMemEnum()
-
-macro=StringToEnum('PetscProfilingCurrentMem');
Index: sm/branches/trunk-jpl-damage/src/m/enum/PetscProfilingSolutionTimeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/PetscProfilingSolutionTimeEnum.m	(revision 12877)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PetscProfilingSolutionTimeEnum()
-%PETSCPROFILINGSOLUTIONTIMEENUM - Enum of PetscProfilingSolutionTime
-%
-%   WARNING: DO NOT 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=PetscProfilingSolutionTimeEnum()
-
-macro=StringToEnum('PetscProfilingSolutionTime');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/ProfilingCurrentFlopsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/ProfilingCurrentFlopsEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/ProfilingCurrentFlopsEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=ProfilingCurrentFlopsEnum()
+%PROFILINGCURRENTFLOPSENUM - Enum of ProfilingCurrentFlops
+%
+%   WARNING: DO NOT 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=ProfilingCurrentFlopsEnum()
+
+macro=StringToEnum('ProfilingCurrentFlops');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/ProfilingCurrentMemEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/ProfilingCurrentMemEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/ProfilingCurrentMemEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=ProfilingCurrentMemEnum()
+%PROFILINGCURRENTMEMENUM - Enum of ProfilingCurrentMem
+%
+%   WARNING: DO NOT 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=ProfilingCurrentMemEnum()
+
+macro=StringToEnum('ProfilingCurrentMem');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/ProfilingSolutionTimeEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/ProfilingSolutionTimeEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/ProfilingSolutionTimeEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=ProfilingSolutionTimeEnum()
+%PROFILINGSOLUTIONTIMEENUM - Enum of ProfilingSolutionTime
+%
+%   WARNING: DO NOT 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=ProfilingSolutionTimeEnum()
+
+macro=StringToEnum('ProfilingSolutionTime');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsANegEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsANegEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsANegEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsANegEnum()
+%SURFACEFORCINGSANEGENUM - Enum of SurfaceforcingsANeg
+%
+%   WARNING: DO NOT 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=SurfaceforcingsANegEnum()
+
+macro=StringToEnum('SurfaceforcingsANeg');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsAPosEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsAPosEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsAPosEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsAPosEnum()
+%SURFACEFORCINGSAPOSENUM - Enum of SurfaceforcingsAPos
+%
+%   WARNING: DO NOT 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=SurfaceforcingsAPosEnum()
+
+macro=StringToEnum('SurfaceforcingsAPos');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsBNegEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsBNegEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsBNegEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsBNegEnum()
+%SURFACEFORCINGSBNEGENUM - Enum of SurfaceforcingsBNeg
+%
+%   WARNING: DO NOT 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=SurfaceforcingsBNegEnum()
+
+macro=StringToEnum('SurfaceforcingsBNeg');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsBPosEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsBPosEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsBPosEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsBPosEnum()
+%SURFACEFORCINGSBPOSENUM - Enum of SurfaceforcingsBPos
+%
+%   WARNING: DO NOT 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=SurfaceforcingsBPosEnum()
+
+macro=StringToEnum('SurfaceforcingsBPos');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsDelta18oEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsDelta18oEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsDelta18oEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsDelta18oEnum()
+%SURFACEFORCINGSDELTA18OENUM - Enum of SurfaceforcingsDelta18o
+%
+%   WARNING: DO NOT 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=SurfaceforcingsDelta18oEnum()
+
+macro=StringToEnum('SurfaceforcingsDelta18o');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsDelta18oSurfaceEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsDelta18oSurfaceEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsDelta18oSurfaceEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsDelta18oSurfaceEnum()
+%SURFACEFORCINGSDELTA18OSURFACEENUM - Enum of SurfaceforcingsDelta18oSurface
+%
+%   WARNING: DO NOT 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=SurfaceforcingsDelta18oSurfaceEnum()
+
+macro=StringToEnum('SurfaceforcingsDelta18oSurface');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsHcEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsHcEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsHcEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsHcEnum()
+%SURFACEFORCINGSHCENUM - Enum of SurfaceforcingsHc
+%
+%   WARNING: DO NOT 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=SurfaceforcingsHcEnum()
+
+macro=StringToEnum('SurfaceforcingsHc');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsIsdelta18oEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsIsdelta18oEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsIsdelta18oEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsIsdelta18oEnum()
+%SURFACEFORCINGSISDELTA18OENUM - Enum of SurfaceforcingsIsdelta18o
+%
+%   WARNING: DO NOT 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=SurfaceforcingsIsdelta18oEnum()
+
+macro=StringToEnum('SurfaceforcingsIsdelta18o');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsIspddEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsIspddEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsIspddEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsIspddEnum()
+%SURFACEFORCINGSISPDDENUM - Enum of SurfaceforcingsIspdd
+%
+%   WARNING: DO NOT 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=SurfaceforcingsIspddEnum()
+
+macro=StringToEnum('SurfaceforcingsIspdd');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsIssmbgradientsEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsIssmbgradientsEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsIssmbgradientsEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsIssmbgradientsEnum()
+%SURFACEFORCINGSISSMBGRADIENTSENUM - Enum of SurfaceforcingsIssmbgradients
+%
+%   WARNING: DO NOT 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=SurfaceforcingsIssmbgradientsEnum()
+
+macro=StringToEnum('SurfaceforcingsIssmbgradients');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsMonthlytemperaturesEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsMonthlytemperaturesEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsMonthlytemperaturesEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsMonthlytemperaturesEnum()
+%SURFACEFORCINGSMONTHLYTEMPERATURESENUM - Enum of SurfaceforcingsMonthlytemperatures
+%
+%   WARNING: DO NOT 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=SurfaceforcingsMonthlytemperaturesEnum()
+
+macro=StringToEnum('SurfaceforcingsMonthlytemperatures');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsPrecipitationsPresentdayEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsPrecipitationsPresentdayEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsPrecipitationsPresentdayEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsPrecipitationsPresentdayEnum()
+%SURFACEFORCINGSPRECIPITATIONSPRESENTDAYENUM - Enum of SurfaceforcingsPrecipitationsPresentday
+%
+%   WARNING: DO NOT 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=SurfaceforcingsPrecipitationsPresentdayEnum()
+
+macro=StringToEnum('SurfaceforcingsPrecipitationsPresentday');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsSmbPosMaxEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsSmbPosMaxEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsSmbPosMaxEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsSmbPosMaxEnum()
+%SURFACEFORCINGSSMBPOSMAXENUM - Enum of SurfaceforcingsSmbPosMax
+%
+%   WARNING: DO NOT 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=SurfaceforcingsSmbPosMaxEnum()
+
+macro=StringToEnum('SurfaceforcingsSmbPosMax');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsSmbPosMinEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsSmbPosMinEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsSmbPosMinEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsSmbPosMinEnum()
+%SURFACEFORCINGSSMBPOSMINENUM - Enum of SurfaceforcingsSmbPosMin
+%
+%   WARNING: DO NOT 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=SurfaceforcingsSmbPosMinEnum()
+
+macro=StringToEnum('SurfaceforcingsSmbPosMin');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsTemperaturesLgmEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsTemperaturesLgmEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsTemperaturesLgmEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsTemperaturesLgmEnum()
+%SURFACEFORCINGSTEMPERATURESLGMENUM - Enum of SurfaceforcingsTemperaturesLgm
+%
+%   WARNING: DO NOT 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=SurfaceforcingsTemperaturesLgmEnum()
+
+macro=StringToEnum('SurfaceforcingsTemperaturesLgm');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsTemperaturesPresentdayEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsTemperaturesPresentdayEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/SurfaceforcingsTemperaturesPresentdayEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsTemperaturesPresentdayEnum()
+%SURFACEFORCINGSTEMPERATURESPRESENTDAYENUM - Enum of SurfaceforcingsTemperaturesPresentday
+%
+%   WARNING: DO NOT 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=SurfaceforcingsTemperaturesPresentdayEnum()
+
+macro=StringToEnum('SurfaceforcingsTemperaturesPresentday');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/TotalSmbEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/TotalSmbEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/TotalSmbEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=TotalSmbEnum()
+%TOTALSMBENUM - Enum of TotalSmb
+%
+%   WARNING: DO NOT 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=TotalSmbEnum()
+
+macro=StringToEnum('TotalSmb');
Index: /issm/branches/trunk-jpl-damage/src/m/enum/TransientParamEnum.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/enum/TransientParamEnum.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/enum/TransientParamEnum.m	(revision 12878)
@@ -0,0 +1,11 @@
+function macro=TransientParamEnum()
+%TRANSIENTPARAMENUM - Enum of TransientParam
+%
+%   WARNING: DO NOT 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=TransientParamEnum()
+
+macro=StringToEnum('TransientParam');
Index: /issm/branches/trunk-jpl-damage/src/m/model/MatlabFuncs.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/MatlabFuncs.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/MatlabFuncs.py	(revision 12878)
@@ -0,0 +1,47 @@
+def strcmp(s1,s2):
+
+	if s1 == s2:
+		return True
+	else:
+		return False
+
+def strncmp(s1,s2,n):
+
+	if s1[0:n] == s2[0:n]:
+		return True
+	else:
+		return False
+
+def strcmpi(s1,s2):
+
+	if s1.lower() == s2.lower():
+		return True
+	else:
+		return False
+
+def strncmpi(s1,s2,n):
+
+	if s1.lower()[0:n] == s2.lower()[0:n]:
+		return True
+	else:
+		return False
+
+def ismember(a,s):
+	import numpy
+
+	if not isinstance(s,(tuple,list,dict,numpy.ndarray)):
+		s=[s]
+
+	if not isinstance(a,(tuple,list,dict,numpy.ndarray)):
+		a=[a]
+
+	if not isinstance(a,numpy.ndarray):
+		b=[item in s for item in a]
+
+	else:
+		b=numpy.empty_like(a)
+		for i,item in enumerate(a.flat):
+			b.flat[i]=item in s
+
+	return b
+
Index: /issm/branches/trunk-jpl-damage/src/m/model/MatlabProcessPatch.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/MatlabProcessPatch.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/MatlabProcessPatch.m	(revision 12878)
@@ -5,5 +5,5 @@
 %      Result=ProcessPatch(Result);
 
-%return if there is no fiel Patch
+%return if there is no field Patch
 if (~isfield(structure,'Patch')),
 	return;
Index: /issm/branches/trunk-jpl-damage/src/m/model/MatlabProcessPatch.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/MatlabProcessPatch.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/MatlabProcessPatch.py	(revision 12878)
@@ -0,0 +1,19 @@
+def MatlabProcessPatch(structure):
+	"""
+	PROCESSPATCH - create a structure from a patch
+ 
+	    Usage:
+	       Result=ProcessPatch(Result);
+	"""
+
+	#loop over steps
+	for structurei in structure.itervalues():
+
+		#return if there is no field Patch
+		if not 'Patch' in structurei:
+			continue
+
+		raise SystemError("MatlabProcessPatch not implemented in Python.")
+
+	return structure
+
Index: /issm/branches/trunk-jpl-damage/src/m/model/ProfileValues.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/ProfileValues.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/ProfileValues.m	(revision 12878)
@@ -0,0 +1,21 @@
+function [Z,data_interp]=ProfileValues(md,data,xprof,yprof,resolution)
+%PROFILEVALUES - compute the value of a field on a vertical profile
+%
+%   This routine gets the value of a given field of the model on points
+%   given by filname (Argus type file)
+%
+%   Usage:
+%      [z,data]=ProfileValues(md,data,filename,resolution)
+%      [z,data]=ProfileValues(md,data,profile_structure,resolution)
+
+%Get bed and surface for each 2d point, offset to make sure that it is inside the glacier system
+offset=10^-3;
+bed=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.bed,1),xprof,yprof)+offset;
+surface=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.surface,1),xprof,yprof)-offset;
+
+%Some useful parameters
+layers=ceil(mean(md.geometry.thickness)/resolution);
+Z=(bed:resolution:surface)';
+X=xprof*ones(size(Z));
+Y=yprof*ones(size(Z));
+data_interp=InterpFromMeshToMesh3d(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,data,X,Y,Z,NaN);
Index: /issm/branches/trunk-jpl-damage/src/m/model/SectionValues.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/SectionValues.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/SectionValues.m	(revision 12878)
@@ -12,8 +12,8 @@
 if ischar(infile),
 	%read infile:
-	contempt=expread(infile);
-	nods=contempt.nods;
-	x=contempt.x;
-	y=contempt.y;
+	profile=expread(infile);
+	nods=profile.nods;
+	x=profile.x;
+	y=profile.y;
 else
 	%read infile:
Index: /issm/branches/trunk-jpl-damage/src/m/model/WriteData.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/WriteData.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/WriteData.m	(revision 12878)
@@ -35,5 +35,5 @@
 %Step 2: write the data itself.
 if     strcmpi(format,'Boolean'),% {{{
-	if(numel(data)~=1), error(['field ' field ' cannot be marshalled as it has more than one element!']); end
+	if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
 
 	%first write length of record
@@ -59,5 +59,5 @@
 	% }}}
 elseif strcmpi(format,'Double'), % {{{
-	if(numel(data)~=1), error(['field ' field ' cannot be marshalled as it has more than one element!']); end
+	if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
 
 	%first write length of record
@@ -233,5 +233,5 @@
 	enum=eval([string 'Enum();']); 
 end % }}}
-function code=FormatToCode(format) % {{{1
+function code=FormatToCode(format) % {{{
 %This routine takes the format string, and hardcodes it into an integer, which 
 %is passed along the record, in order to identify the nature of the dataset being 
Index: /issm/branches/trunk-jpl-damage/src/m/model/WriteData.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/WriteData.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/WriteData.py	(revision 12878)
@@ -0,0 +1,274 @@
+import numpy
+import math
+import struct
+from MatlabFuncs import *
+
+def WriteData(fid,*args):
+	"""
+	WRITEDATA - write model field in binary file
+ 
+	    Usage:
+	       WriteData(fid,*args)
+	"""
+
+	#process options
+	options=pairoptions(args)
+
+	#Get data properties
+	if options.exist('object'):
+		#This is an object field, construct enum and data
+		obj       = options.getfieldvalue('object')
+		fieldname = options.getfieldvalue('fieldname')
+		classname = type(obj)
+
+		enum      = BuildEnum(classname+'_'+fieldname)
+		data      = getattr(obj,fieldname)
+	else:
+		#No processing required
+		data = options.getfieldvalue('data')
+		enum = options.getfieldvalue('enum')
+	format  = options.getfieldvalue('format')
+	mattype = options.getfieldvalue('mattype',0)    #only required for matrices
+
+	#Process sparse matrices
+#	if issparse(data),
+#		data=full(data);
+#	end
+
+	#Step 1: write the enum to identify this record uniquely
+	fid.write(struct.pack('i',enum)) 
+
+	#Step 2: write the data itself.
+	if   strcmpi(format,'Boolean'):    # {{{
+		if len(data) !=1:
+			raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum))
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4))  #1 bool (disguised as an int)+code
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write integer
+		fid.write(struct.pack('i',data))  #send an int, not easy to send a bool
+		# }}}
+
+	elif strcmpi(format,'Integer'):    # {{{
+		if len(data) !=1:
+			raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum))
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4))  #1 integer + code
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write integer
+		fid.write(struct.pack('i',data)) 
+		# }}}
+
+	elif strcmpi(format,'Double'):    # {{{
+		if len(data) !=1:
+			raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum))
+
+		#first write length of record
+		fid.write(struct.pack('i',8+4))  #1 double+code
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write double
+		fid.write(struct.pack('d',data)) 
+		# }}}
+
+	elif strcmpi(format,'String'):    # {{{
+		#first write length of record
+		fid.write(struct.pack('i',len(data)+4+4))  #string + string size + code
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write string
+		fid.write(struct.pack('i',len(data))) 
+		fid.write(struct.pack('%ds' % len(data),data)) 
+		# }}}
+
+	elif strcmpi(format,'BooleanMat'):    # {{{
+
+		#Get size
+		s=data.shape
+		#if matrix = NaN, then do not write anything
+		if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
+			s[0]=0
+			s[1]=0
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4+8*s[0]*s[1]+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
+
+		#write data code and matrix type: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+		fid.write(struct.pack('i',mattype))
+
+		#now write matrix
+		fid.write(struct.pack('i',s[0])) 
+		fid.write(struct.pack('i',s[1])) 
+		for i in xrange(s[0]):
+			for j in xrange(s[1]):
+				fid.write(struct.pack('i',data[i][j]))    #get to the "c" convention, hence the transpose
+		# }}}
+
+	elif strcmpi(format,'IntMat'):    # {{{
+
+		#Get size
+		s=data.shape
+		#if matrix = NaN, then do not write anything
+		if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
+			s[0]=0
+			s[1]=0
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4+8*s[0]*s[1]+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
+
+		#write data code and matrix type: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+		fid.write(struct.pack('i',mattype))
+
+		#now write matrix
+		fid.write(struct.pack('i',s[0])) 
+		fid.write(struct.pack('i',s[1])) 
+		for i in xrange(s[0]):
+			for j in xrange(s[1]):
+				fid.write(struct.pack('i',data[i][j]))    #get to the "c" convention, hence the transpose
+		# }}}
+
+	elif strcmpi(format,'DoubleMat'):    # {{{
+
+		#Get size
+		s=data.shape
+		#if matrix = NaN, then do not write anything
+		if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
+			s[0]=0
+			s[1]=0
+
+		#first write length of record
+		fid.write(struct.pack('i',4+4+8*s[0]*s[1]+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
+
+		#write data code and matrix type: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+		fid.write(struct.pack('i',mattype))
+
+		#now write matrix
+		fid.write(struct.pack('i',s[0])) 
+		fid.write(struct.pack('i',s[1])) 
+		for i in xrange(s[0]):
+			for j in xrange(s[1]):
+				fid.write(struct.pack('d',data[i][j]))    #get to the "c" convention, hence the transpose
+		# }}}
+
+	elif strcmpi(format,'MatArray'):    # {{{
+
+		#first get length of record
+		recordlength=4+4    #number of records + code
+		for matrix in data:
+			s=matrix.shape
+			recordlength+=4*2+s[0]*s[1]*8    #row and col of matrix + matrix of doubles
+
+		#write length of record
+		fid.write(struct.pack('i',recordlength)) 
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#write data, first number of records
+		fid.write(struct.pack('i',len(data))) 
+
+		#write each matrix: 
+		for matrix in data:
+			s=matrix.shape
+			fid.write(struct.pack('i',s[0])) 
+			fid.write(struct.pack('i',s[1])) 
+			for i in xrange(s[0]):
+				for j in xrange(s[1]):
+					fid.write(struct.pack('d',matrix[i][j]))
+		# }}}
+
+	elif strcmpi(format,'StringArray'):    # {{{
+
+		#first get length of record
+		recordlength=4+4    #for length of array + code
+		for string in data:
+			recordlength+=4+len(string)    #for each string
+
+		#write length of record
+		fid.write(struct.pack('i',recordlength)) 
+
+		#write data code: 
+		fid.write(struct.pack('i',FormatToCode(format))) 
+
+		#now write length of string array
+		fid.write(struct.pack('i',len(data))) 
+
+		#now write the strings
+		for string in data:
+			fid.write(struct.pack('i',len(string))) 
+			fid.write(struct.pack('%ds' % len(string),string)) 
+		# }}}
+
+	else:    # {{{
+		raise TypeError('WriteData error message: data type: %d not supported yet! (%s)' % (format,EnumToString(enum)))
+	# }}}
+
+def BuildEnum(string): # {{{
+	"""
+	BUILDENUM - build enum out of string
+ 
+    Usage:
+       enum=BuildEnum(string)
+	"""
+
+	if '_' in string:
+		substrs=string.split('_')
+		string=''
+		for str in substrs:
+			string+=str[0].upper()+str[1:]
+	else:
+		#take first letter of string and make it uppercase: 
+		string=str[0].upper()+str[1:]
+
+	#Get Enum
+	exec('enum='+string+'Enum()',globals())
+
+	return enum
+# }}}
+
+def FormatToCode(format): # {{{
+	"""
+	This routine takes the format string, and hardcodes it into an integer, which 
+	is passed along the record, in order to identify the nature of the dataset being 
+	sent.
+	"""
+
+	if   strcmpi(format,'Boolean'):
+		code=1
+	elif strcmpi(format,'Integer'):
+		code=2
+	elif strcmpi(format,'Double'):
+		code=3
+	elif strcmpi(format,'String'):
+		code=4
+	elif strcmpi(format,'BooleanMat'):
+		code=5
+	elif strcmpi(format,'IntMat'):
+		code=6
+	elif strcmpi(format,'DoubleMat'):
+		code=7
+	elif strcmpi(format,'MatArray'):
+		code=8
+	elif strcmpi(format,'StringArray'):
+		code=9
+	else:
+		raise InputError('FormatToCode error message: data type not supported yet!')
+
+	return code
+# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/model/addnote.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/addnote.py	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/addnote.py	(revision 12878)
@@ -1,29 +1,25 @@
-def addnote(md, string):
+def addnote(md,string):
+	"""
+	ADDNOTE - add a note to the existing model notes field
+	 
+	    Usage:
+	       md=addnote(md,string);
+	 
+	    Example:
+	       md=addnote(md,'Pine Island, Geometry of 2007');
+	"""
 
-    # Local Variables: md, string, i, notes, miscellaneous, newnotes
-    # Function calls: ischar, nargout, cell, nargin, length, addnote, error
-    #ADDNOTE - add a note to the existing model notes field
-    #
-    #   Usage:
-    #      md=addnote(md,string);
-    #
-    #   Example:
-    #      md=addnote(md,'Pine Island, Geometry of 2007');
-    
-	if not isinstance(string,basetring):
-        print 'addnote error message: second input argument should be a string'
-		return []
-    
-    notes = md.miscellaneous.notes
-    
-	if isinstance(notes,basestring):
+	if not isinstance(string,str):
+		raise TypeError('addnote error message: second input argument should be a string')
+
+	notes=md.miscellaneous.notes
+
+	if isinstance(notes,str):
 		newnotes=[notes,string]
-    else:
-		newnotes=[];
-		for i in range(len(notes)):
-			newnotes=newnotes+notes[i]
-            
-        newnotes=newnotes+nodes;
-        
-    md.miscellaneous.notes = newnotes
-    return md
+	else:
+		newnotes=notes.append(string)
+
+	md.miscellaneous.notes=newnotes
+
+	return md
+
Index: /issm/branches/trunk-jpl-damage/src/m/model/averaging.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/averaging.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/averaging.m	(revision 12878)
@@ -1,3 +1,3 @@
-function average=averaging(md,data,iterations)
+function average=averaging(md,data,iterations,varargin)
 %AVERAGING - smooths the input over the mesh
 %
@@ -8,33 +8,61 @@
 %   by taking the average of the element around a node weighted by the
 %   elements volume
+%   For 3d mesh, a last argument can be added to specify the layer to be averaged on.
 %
 %   Usage:
 %      smoothdata=averaging(md,data,iterations)
+%      smoothdata=averaging(md,data,iterations,layer)
 %
 %   Examples:
 %      velsmoothed=averaging(md,md.initialization.vel,4);
 %      pressure=averaging(md,md.initialization.pressure,0);
+%      temperature=averaging(md,md.initialization.temperature,1,1);
 
-if length(data)~=md.mesh.numberofelements & length(data)~=md.mesh.numberofvertices
+if ((nargin~=4) & (nargin~=3)),
+	error('averaging error message');
+end
+if (length(data)~=md.mesh.numberofelements & length(data)~=md.mesh.numberofvertices),
 	error('averaging error message: data not supported yet');
+end
+if md.mesh.dimension==3 & nargin==4,
+	if varargin{1}<=0 | varargin{1}>md.mesh.numberoflayers,
+		error('layer should be between 1 and md.mesh.numberoflayers');
+	end
+	layer=varargin{1};
+else
+	layer=0;
 end
 
 %initialization
-weights=zeros(md.mesh.numberofvertices,1);
-data=data(:);
+if layer==0,
+	weights=zeros(md.mesh.numberofvertices,1);
+	data=data(:);
+else 
+	weights=zeros(md.mesh.numberofvertices2d,1);
+	data=data((layer-1)*md.mesh.numberofvertices2d+1:layer*md.mesh.numberofvertices2d,:);
+end
 
-%load some variables (it is much faster if the variab;es are loaded from md once for all)
-index=md.mesh.elements;
-numberofnodes=md.mesh.numberofvertices;
-numberofelements=md.mesh.numberofelements;
+%load some variables (it is much faster if the variabes are loaded from md once for all)
+if layer==0,
+	index=md.mesh.elements;
+	numberofnodes=md.mesh.numberofvertices;
+	numberofelements=md.mesh.numberofelements;
+else
+	index=md.mesh.elements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	numberofelements=md.mesh.numberofelements2d;
+end
 
 %build some variables
 line=index(:);
-if md.mesh.dimension==3
+if md.mesh.dimension==3 & layer==0,
 	rep=6;
 	areas=GetAreas(index,md.mesh.x,md.mesh.y,md.mesh.z);
+elseif md.mesh.dimension==2,
+	rep=3;
+	areas=GetAreas(index,md.mesh.x,md.mesh.y);
 else
 	rep=3;
-	areas=GetAreas(index,md.mesh.x,md.mesh.y);
+	areas=GetAreas(index,md.mesh.x2d,md.mesh.y2d);
 end
 summation=1/rep*ones(rep,1);
Index: /issm/branches/trunk-jpl-damage/src/m/model/collapse.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/collapse.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/collapse.m	(revision 12878)
@@ -42,4 +42,5 @@
 if ~isnan(md.initialization.vz),md.initialization.vz=DepthAverage(md,md.initialization.vz);end;
 if ~isnan(md.initialization.vel),md.initialization.vel=DepthAverage(md,md.initialization.vel);end;
+if ~isnan(md.initialization.temperature),md.initialization.temperature=DepthAverage(md,md.initialization.temperature);end;
 
 %bedinfo and surface info
@@ -92,4 +93,5 @@
 md.geometry.thickness=project2d(md,md.geometry.thickness,1);
 md.geometry.bed=project2d(md,md.geometry.bed,1);
+md.geometry.bathymetry=project2d(md,md.geometry.bathymetry,1);
 md.mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1);
 md.mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1);
Index: /issm/branches/trunk-jpl-damage/src/m/model/contourenvelope.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/contourenvelope.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/contourenvelope.m	(revision 12878)
@@ -35,8 +35,8 @@
 %Now, build the connectivity tables for this mesh.
 %Computing connectivity
-if size(md.mesh.vertexconnectivity,1)~=md.mesh.numberofvertices,
+if (size(md.mesh.vertexconnectivity,1)~=md.mesh.numberofvertices & size(md.mesh.vertexconnectivity,1)~=md.mesh.numberofvertices2d),
 	md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
 end
-if size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements,
+if (size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements & size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements2d),
 	md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
 end
@@ -44,9 +44,24 @@
 %get nodes inside profile
 mesh.elementconnectivity=md.mesh.elementconnectivity;
+if md.mesh.dimension==2;
+	mesh.elements=md.mesh.elements;
+	mesh.x=md.mesh.x;
+	mesh.y=md.mesh.y;
+	mesh.numberofvertices=md.mesh.numberofvertices;
+	mesh.numberofelements=md.mesh.numberofelements;
+else
+	mesh.elements=md.mesh.elements2d;
+	mesh.x=md.mesh.x2d;
+	mesh.y=md.mesh.y2d;
+	mesh.numberofvertices=md.mesh.numberofvertices2d;
+	mesh.numberofelements=md.mesh.numberofelements2d;
+end
+
 if nargin==2,
+
 	if isfile,
 		%get flag list of elements and nodes inside the contour
-		nodein=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,file,'node',1);
-		elemin=(sum(nodein(md.mesh.elements),2)==size(md.mesh.elements,2));
+		nodein=ContourToMesh(mesh.elements,mesh.x,mesh.y,file,'node',1);
+		elemin=(sum(nodein(mesh.elements),2)==size(mesh.elements,2));
 		%modify element connectivity
 		elemout=find(~elemin);
@@ -55,10 +70,10 @@
 	else
 		%get flag list of elements and nodes inside the contour
-		nodein=zeros(md.mesh.numberofvertices,1); 
-		elemin=zeros(md.mesh.numberofelements,1); 
+		nodein=zeros(mesh.numberofvertices,1); 
+		elemin=zeros(mesh.numberofelements,1); 
 		
 		pos=find(flags); 
 		elemin(pos)=1;
-		nodein(md.mesh.elements(pos,:))=1;
+		nodein(mesh.elements(pos,:))=1;
 
 		%modify element connectivity
@@ -87,11 +102,11 @@
 	els2=mesh.elementconnectivity(el1,find(mesh.elementconnectivity(el1,:)));
 	if length(els2)>1,
-		flag=intersect(md.mesh.elements(els2(1),:),md.mesh.elements(els2(2),:));
-		nods1=md.mesh.elements(el1,:);
+		flag=intersect(mesh.elements(els2(1),:),mesh.elements(els2(2),:));
+		nods1=mesh.elements(el1,:);
 		nods1(find(nods1==flag))=[];
 		segments(count,:)=[nods1 el1];
 
-		ord1=find(nods1(1)==md.mesh.elements(el1,:));
-		ord2=find(nods1(2)==md.mesh.elements(el1,:));
+		ord1=find(nods1(1)==mesh.elements(el1,:));
+		ord2=find(nods1(2)==mesh.elements(el1,:));
 
 		%swap segment nodes if necessary
@@ -104,12 +119,12 @@
 		count=count+1;
 	else
-		nods1=md.mesh.elements(el1,:);
-		flag=setdiff(nods1,md.mesh.elements(els2,:));
+		nods1=mesh.elements(el1,:);
+		flag=setdiff(nods1,mesh.elements(els2,:));
 		for j=1:3,
 			nods=nods1; nods(j)=[];
 			if any(ismember(flag,nods)),
 				segments(count,:)=[nods el1];
-				ord1=find(nods(1)==md.mesh.elements(el1,:));
-				ord2=find(nods(2)==md.mesh.elements(el1,:));
+				ord1=find(nods(1)==mesh.elements(el1,:));
+				ord2=find(nods(2)==mesh.elements(el1,:));
 				if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
 					temp=segments(count,1);
Index: /issm/branches/trunk-jpl-damage/src/m/model/extrude.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/extrude.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/extrude.m	(revision 12878)
@@ -143,4 +143,5 @@
 md.surfaceforcings.precipitation=project3d(md,'vector',md.surfaceforcings.precipitation,'type','node');
 md.balancethickness.thickening_rate=project3d(md,'vector',md.balancethickness.thickening_rate,'type','node');
+md.surfaceforcings.monthlytemperatures=project3d(md,'vector',md.surfaceforcings.monthlytemperatures,'type','node');
 
 %results
@@ -223,4 +224,7 @@
 if ~isnan(md.inversion.max_parameters),md.inversion.max_parameters=project3d(md,'vector',md.inversion.max_parameters,'type','node');end;
 if ~isnan(md.qmu.partition),md.qmu.partition=project3d(md,'vector',md.qmu.partition','type','node');end
+if(md.surfaceforcings.isdelta18o),md.surfaceforcings.temperatures_lgm=project3d(md,'vector',md.surfaceforcings.temperatures_lgm,'type','node');end
+if(md.surfaceforcings.isdelta18o),md.surfaceforcings.temperatures_presentday=project3d(md,'vector',md.surfaceforcings.temperatures_presentday,'type','node');end
+if(md.surfaceforcings.isdelta18o),md.surfaceforcings.precipitations_presentday=project3d(md,'vector',md.surfaceforcings.precipitations_presentday,'type','node');end
 
 %Put lithostatic pressure if there is an existing pressure
Index: /issm/branches/trunk-jpl-damage/src/m/model/ismodelselfconsistent.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/ismodelselfconsistent.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/ismodelselfconsistent.m	(revision 12878)
@@ -6,5 +6,5 @@
 
 %initialize consistency as true
-modelconsistency(true);
+md.private.isconsistent=true;
 
 %Get solution and associated analyses
@@ -12,5 +12,5 @@
 [analyses,numanalyses]=AnalysisConfiguration(solution);
 
-%Go through al model field check that it is a class and call checkconsistency
+%Go through a model field, check that it is a class, and call checkconsistency
 fields=properties('model');
 for i=1:length(fields),
@@ -24,17 +24,17 @@
 	%Check that current field is an object
 	if ~isobject(md.(field))
-		checkmessage(['field ''' char(field) ''' is not an object']);
+		md=checkmessage(md,['field ''' char(field) ''' is not an object']);
 	end
 
 	%Check consistency of the object
 	if verLessThan('matlab', '7.6')
-		checkconsistency(md.(field),md,solution,analyses);
+		md=checkconsistency(md.(field),md,solution,analyses);
 	else
-		md.(field).checkconsistency(md,solution,analyses);
+		md=md.(field).checkconsistency(md,solution,analyses);
 	end
 end
 
 %error message if mode is not consistent
-if modelconsistency==false,
-	error(' ');
+if md.private.isconsistent==false,
+	error('Model not consistent, see messages above');
 end
Index: /issm/branches/trunk-jpl-damage/src/m/model/ismodelselfconsistent.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/ismodelselfconsistent.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/ismodelselfconsistent.py	(revision 12878)
@@ -0,0 +1,34 @@
+def ismodelselfconsistent(md):
+	"""
+	ISMODELSELFCONSISTENT - check that model forms a closed form solvable problem.
+
+	    Usage:
+	       ismodelselfconsistent(md),
+	"""
+
+	#initialize consistency as true
+	md.private.isconsistent=true
+
+	#Get solution and associated analyses
+	solution=md.private.solution
+	analyses,numanalyses=AnalysisConfiguration(solution)
+
+	#Go through a model fields, check that it is a class, and call checkconsistency
+	fields=vars('model')
+	for field in fields:
+
+		#Some properties do not need to be checked
+		if field in ['results','debug','radaroverlay']:
+			continue
+
+		#Check that current field is an object
+		if not hasattr(getattr(md,field),'checkconsistency'):
+			md=checkmessage(md,"field '%s' is not an object." % field)
+
+		#Check consistency of the object
+		exec("md.%s.checkconsistency(md,solution,analyses)" % field)
+
+	#error message if mode is not consistent
+	if not md.private.isconsistent:
+		raise RuntimeError('Model not consistent, see messages above.')
+
Index: /issm/branches/trunk-jpl-damage/src/m/model/loadresultsfromcluster.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/loadresultsfromcluster.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/loadresultsfromcluster.m	(revision 12878)
@@ -13,9 +13,17 @@
 
 %Download outputs from the cluster
-if verLessThan('matlab', '7.6');
-	Download(cluster,md);
+filelist={[md.miscellaneous.name '.outlog'],[md.miscellaneous.name '.errlog']};
+if md.qmu.isdakota,
+	filelist{end+1}=[md.miscellaneous.name '.qmu.err'];
+	filelist{end+1}=[md.miscellaneous.name '.qmu.out'];
+	if isfield(md.qmu.params,'tabular_graphics_data'),
+		if md.qmu.params.tabular_graphics_data==true,
+			filelist{end+1}='dakota_tabular.dat';
+		end
+	end
 else
-	cluster.Download(md);
+	filelist{end+1}=[md.miscellaneous.name '.outbin'];
 end
+Download(cluster,md.private.runtimename,filelist);
 
 %If we are here, no errors in the solution sequence, call loadresultsfromdisk.
Index: /issm/branches/trunk-jpl-damage/src/m/model/loadresultsfromcluster.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/loadresultsfromcluster.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/loadresultsfromcluster.py	(revision 12878)
@@ -0,0 +1,61 @@
+import os
+import platform
+import socket
+from MatlabFuncs import *
+
+def loadresultsfromcluster(md,runtimename=False):
+	"""
+	LOADRESULTSFROMCLUSTER - load results of solution sequence from cluster
+ 
+	    Usage:
+	       md=loadresultsfromcluster(md,runtimename);
+	"""
+
+	#retrieve cluster, to be able to call its methods
+	cluster=md.cluster
+
+	if runtimename:
+		md.private.runtimename=runtimename
+	end
+
+	#Download outputs from the cluster
+	filelist=[md.miscellaneous.name+'.outlog',md.miscellaneous.name+'.errlog']
+	if md.qmu.isdakota:
+		filelist.append(md.miscellaneous.name+'.qmu.err')
+		filelist.append(md.miscellaneous.name+'.qmu.out')
+		if 'tabular_graphics_data' in md.qmu.params:
+			if md.qmu.params['tabular_graphics_data']:
+				filelist.append('dakota_tabular.dat')
+		filelist.append(md.miscellaneous.name+'.outbin')
+	Download(cluster,md.private.runtimename,filelist)
+
+	#If we are here, no errors in the solution sequence, call loadresultsfromdisk.
+	md=loadresultsfromdisk(md,md.miscellaneous.name+'.outbin')
+
+	#erase the log and output files
+	if md.qmu.isdakota:
+		os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.outlog'))
+		os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.errlog'))
+	else:
+		os.remove(md.miscellaneous.name+'.outlog')
+		os.remove(md.miscellaneous.name+'.errlog')
+		os.remove(md.miscellaneous.name+'.outbin')
+		if not 'Windows' in platform.system():
+			os.remove(md.private.runtimename+'.tar.gz')
+
+	#erase input file if run was carried out on same platform.
+	hostname=socket.gethostname().lower().split('.')[0]
+	if strcmpi(hostname,cluster.name):
+		if md.qmu.isdakota:
+			os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.bin'))
+			os.remove(os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name+'.queue'))
+		else:
+			os.remove(md.miscellaneous.name+'.bin')
+			os.remove(md.miscellaneous.name+'.petsc')
+			if not 'Windows' in platform.system():
+				os.remove(md.miscellaneous.name+'.queue')
+			else:
+				os.remove(md.miscellaneous.name+'.bat')
+
+	return md
+
Index: /issm/branches/trunk-jpl-damage/src/m/model/loadresultsfromdisk.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/loadresultsfromdisk.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/loadresultsfromdisk.m	(revision 12878)
@@ -59,4 +59,3 @@
 	md=postqmu(md);
 	cd ..
-
 end
Index: /issm/branches/trunk-jpl-damage/src/m/model/loadresultsfromdisk.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/loadresultsfromdisk.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/loadresultsfromdisk.py	(revision 12878)
@@ -0,0 +1,60 @@
+import os
+
+def loadresultsfromdisk(md,filename):
+	"""
+	LOADRESULTSFROMDISK - load results of solution sequence from disk file "filename"            
+ 
+	    Usage:
+	       md=loadresultsfromdisk(md=False,filename=False);
+	"""
+
+	#check number of inputs/outputs
+	if not md or not filename:
+		raise ValueError("loadresultsfromdisk: error message.")
+
+	if not md.qmu.isdakota:
+
+		#Check that file exists
+		if not os.path.exists(filename):
+			raise ValueError("binary file '%s' not found." % filename)
+
+		#initialize md.results if not a structure yet
+		if not isinstance(md.results,dict):
+			md.results={}
+
+		#load results onto model
+		structure=parseresultsfromdisk(filename,~md.settings.io_gather)
+		if not len(structure):
+			raise RuntimeError("No result found in binary file '%s'. Check for solution crash." % filename)
+		end
+		md.results[structure[1]['SolutionType']]=structure;
+
+		#recover solution_type from results
+		md.private.solution=structure[1]['SolutionType']
+
+		#read log files onto fields
+		if os.path.exists(md.miscellaneous.name+'.errlog'):
+			with open(md.miscellaneous.name+'.errlog','r') as f:
+				md.results[structure[1]['SolutionType']]['errlog']=[line[:-1] for line in f]
+		else:
+			md.results[structure[1]['SolutionType']]['errlog']=[]
+
+		if os.path.exists(md.miscellaneous.name+'.outlog'):
+			with open(md.miscellaneous.name+'.outlog','r') as f:
+				md.results[structure[1]['SolutionType']]['outlog']=[line[:-1] for line in f]
+		else:
+			md.results[structure[1]['SolutionType']]['outlog']=[]
+
+		if len(md.results[structure[1]['SolutionType']]['errlog']):
+			print ("loadresultsfromcluster info message: error during solution. Check your errlog and outlog model fields.")
+
+	#post processes qmu results if necessary
+	else:
+
+		if not isinstance(md.private.solution,str):
+			md.private.solution=EnumToString(md.private.solution)
+		md=postqmu(md)
+		os.chdir('..')
+
+	return md
+
Index: /issm/branches/trunk-jpl-damage/src/m/model/marshall.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/marshall.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/marshall.m	(revision 12878)
@@ -16,5 +16,5 @@
 end
 
-%First, right MaximumNumberOfEnum to make sure that the Enums are synchronized
+%First, write MaximumNumberOfEnum to make sure that the Enums are synchronized
 WriteData(fid,'enum',MaximumNumberOfEnums(),'data',true,'format','Boolean');
 
@@ -31,5 +31,5 @@
 	%Check that current field is an object
 	if ~isobject(md.(field))
-		checkmessage(['field ''' char(field) ''' is not an object']);
+		error(['field ''' char(field) ''' is not an object']);
 	end
 
Index: /issm/branches/trunk-jpl-damage/src/m/model/marshall.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/marshall.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/marshall.py	(revision 12878)
@@ -0,0 +1,47 @@
+from WriteData import *
+
+def marshall(md):
+	"""
+	MARSHALL - outputs a compatible binary file from @model md, for certain solution type.
+
+	    The routine creates a compatible binary file from @model md
+	    This binary file will be used for parallel runs in JPL-package
+
+	    Usage:
+	       marshall(md)
+	"""
+
+	print "marshalling file '%s.bin'." % md.miscellaneous.name
+
+	#open file for binary writing
+	try:
+		fid=open(md.miscellaneous.name+'.bin','wb')
+	except IOError as e:
+		raise IOError("marshall error message: could not open '%s.bin' file for binary writing." % md.miscellaneous.name)
+
+	#First, write MaximumNumberOfEnum to make sure that the Enums are synchronized
+	WriteData(fid,'enum',MaximumNumberOfEnums(),'data',true,'format','Boolean')
+
+	#Go through all model fields: check that it is a class and call checkconsistency
+	fields=vars(md)
+
+	for field in fields.interkeys():
+
+		#Some properties do not need to be marshalled
+		if field in ['results','radaroverlay','solver','cluster','flaim','private']:
+			continue
+
+		#Check that current field is an object
+		if not hasattr(getattr(md,field),'marshall'):
+			raise TypeError("field '%s' is not an object." % field)
+
+		#Marshall current object
+		#print "marshalling %s ..." % field
+		exec("md.%s.marshall(fid)" % field)
+
+	#close file
+	try:
+		f.close(fid)
+	except IOError as e:
+		raise IOError("marshall error message: could not close file '%s.bin'." % md.miscellaneous.name)
+
Index: /issm/branches/trunk-jpl-damage/src/m/model/mesh/bamg.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/mesh/bamg.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/mesh/bamg.m	(revision 12878)
@@ -58,5 +58,5 @@
 bamg_mesh=bamgmesh;
 
-% Bamg Geometry parameters {{{1
+% Bamg Geometry parameters {{{
 if exist(options,'domain'),
 
@@ -259,5 +259,5 @@
 end
 %}}}
-% Bamg Mesh parameters {{{1
+% Bamg Mesh parameters {{{
 if (~exist(options,'domain') & md.mesh.numberofvertices~=0 & md.mesh.dimension==2),
 
@@ -274,5 +274,5 @@
 end
 %}}}
-% Bamg Options {{{1
+% Bamg Options {{{
 bamg_options.Crack=getfieldvalue(options,'Crack',0);
 bamg_options.anisomax=getfieldvalue(options,'anisomax',10^30);
Index: /issm/branches/trunk-jpl-damage/src/m/model/modelextract.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/modelextract.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/modelextract.m	(revision 12878)
@@ -166,5 +166,5 @@
 	if size(md2.mesh.edges,2)>1, %do not use ~isnan because there are some NaNs...
 		%renumber first two columns
-		pos=find(~isnan(md2.mesh.edges(:,4)));
+		pos=find(md2.mesh.edges(:,4)~=-1);
 		md2.mesh.edges(:  ,1)=Pnode(md2.mesh.edges(:,1)); 
 		md2.mesh.edges(:  ,2)=Pnode(md2.mesh.edges(:,2)); 
@@ -173,18 +173,18 @@
 		%remove edges when the 2 vertices are not in the domain.
 		md2.mesh.edges=md2.mesh.edges(find(md2.mesh.edges(:,1) & md2.mesh.edges(:,2)),:);
-		%Replace all zeros by NaN in the last two columns;
+		%Replace all zeros by -1 in the last two columns;
 		pos=find(md2.mesh.edges(:,3)==0);
-		md2.mesh.edges(pos,3)=NaN;
+		md2.mesh.edges(pos,3)=-1;
 		pos=find(md2.mesh.edges(:,4)==0);
-		md2.mesh.edges(pos,4)=NaN;
-		%Invert NaN of the third column with last column (Also invert first two columns!!)
-		pos=find(isnan(md2.mesh.edges(:,3)));
+		md2.mesh.edges(pos,4)=-1;
+		%Invert -1 on the third column with last column (Also invert first two columns!!)
+		pos=find(md2.mesh.edges(:,3)==-1);
 		md2.mesh.edges(pos,3)=md2.mesh.edges(pos,4);
-		md2.mesh.edges(pos,4)=NaN;
+		md2.mesh.edges(pos,4)=-1;
 		values=md2.mesh.edges(pos,2);
 		md2.mesh.edges(pos,2)=md2.mesh.edges(pos,1);
 		md2.mesh.edges(pos,1)=values;
 		%Finally remove edges that do not belong to any element
-		pos=find(isnan(md2.mesh.edges(:,3)) & isnan(md2.mesh.edges(:,4)));
+		pos=find(md2.mesh.edges(:,3)==-1 & md2.mesh.edges(:,4)==-1);
 		md2.mesh.edges(pos,:)=[];
 	end
@@ -210,4 +210,14 @@
 		md2.mesh.segments=contourenvelope(md2);
 		md2.mesh.vertexonboundary=zeros(numberofvertices2,1); md2.mesh.vertexonboundary(md2.mesh.segments(:,1:2))=1;
+	else
+		%First do the connectivity for the contourenvelope in 2d
+		md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements2d,md2.mesh.numberofvertices2d);
+		md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements2d,md2.mesh.vertexconnectivity);
+		md2.mesh.segments=contourenvelope(md2);
+		md2.mesh.vertexonboundary=zeros(numberofvertices2/md2.mesh.numberoflayers,1); md2.mesh.vertexonboundary(md2.mesh.segments(:,1:2))=1;
+		md2.mesh.vertexonboundary=repmat(md2.mesh.vertexonboundary,md2.mesh.numberoflayers,1);
+		%Then do it for 3d as usual
+		md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices);
+		md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity);
 	end
 
Index: /issm/branches/trunk-jpl-damage/src/m/model/parameterization/parameterize.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/parameterization/parameterize.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/parameterization/parameterize.m	(revision 12878)
@@ -4,5 +4,5 @@
 %   from a parameter matlab file, start filling in all the @model fields that were not 
 %   filled in by the mesh.m and mask.m @model methods.
-%   Warning: the paramter file must be able to be run in Matlab
+%   Warning: the parameter file must be able to be run in Matlab
 %
 %   Usage:
@@ -14,5 +14,5 @@
 %some checks
 if ~exist(parametername),
-	error(['parameterize error message: file ' parametername ' not found !']);
+	error(['parameterize error message: file ' parametername ' not found!']);
 end
 
Index: /issm/branches/trunk-jpl-damage/src/m/model/parameterization/parameterize.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/parameterization/parameterize.py	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/parameterization/parameterize.py	(revision 12878)
@@ -1,27 +1,34 @@
 import os
-def  parameterize(md,parametername):
-	#PARAMETERIZE - parameterize a model
-	#
-	#   from a parameter matlab file, start filling in all the model fields that were not 
-	#   filled in by the mesh.py and setmask.py model methods.
-	#   Warning: the parameter file must be able to be run in Python
-	#
-	#   Usage:
-	#      md=parameterize(md,parametername)
-	#
-	#   Example:
-	#      md=parameterize(md,'Square.par');
+import datetime
+from addnote import *
+
+def parameterize(md,parametername):
+	"""
+	PARAMETERIZE - parameterize a model
+	 
+	    from a parameter python file, start filling in all the model fields that were not 
+	    filled in by the mesh.py and mask.py model methods.
+	    Warning: the parameter file must be able to be run in Python
+	 
+	    Usage:
+	       md=parameterize(md,parametername)
+	 
+	    Example:
+	       md=parameterize(md,'Square.par');
+	"""
 
 	#some checks
-	if not os.path.isfile(parametername):
-		print 'parameterize error message: file '+parametername+' not found.'
-		return []
+	if not os.path.exists(parametername):
+		raise IOError("parameterize error message: file '%s' not found!" % parametername)
 
 	#Try and run parameter file.
 	execfile(parametername)
-	
-	#ame and notes
-	if len(md.miscellaneous.name)==0:
-		md.miscellaneous.name=os.path.basename(parametername)
-	
-	md=addnote(md,'Model created by using parameter file: '+parametername+' on: '+str(datetime.datetime.now()))
+
+	#Name and notes
+	if not md.miscellaneous.name:
+		md.miscellaneous.name=os.path.basename(parametername).split('.')[0]
+
+	md=addnote(md,"Model created by using parameter file: '%s' on: %s." % (parametername,datetime.datetime.strftime(datetime.datetime.now(),'%c') ))
+
+	return md
+
Index: /issm/branches/trunk-jpl-damage/src/m/model/parseresultsfromdisk.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/parseresultsfromdisk.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/parseresultsfromdisk.m	(revision 12878)
@@ -172,5 +172,5 @@
 % }}}
 function result=ReadDataDimensions(fid) % {{{
-%READDATA - read data dimensions, step and time, but not the data itself.
+%READDATADIMENSIONS - read data dimensions, step and time, but not the data itself.
 %
 %   Usage:
Index: /issm/branches/trunk-jpl-damage/src/m/model/parseresultsfromdisk.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/parseresultsfromdisk.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/parseresultsfromdisk.py	(revision 12878)
@@ -0,0 +1,235 @@
+import struct
+import numpy
+from MatlabFuncs import *
+from MatlabProcessPatch import *
+
+def parseresultsfromdisk(filename,iosplit):
+	"""
+	PARSERESULTSFROMDISK - ...
+	 
+	    Usage:
+	       results=parseresultsfromdisk(filename,iosplit)
+	"""
+
+	if iosplit:
+		results=parseresultsfromdiskiosplit(filename)
+	else:
+		results=parseresultsfromdiskioserial(filename)
+
+	#process patch if necessary
+	results=MatlabProcessPatch(results)
+
+	return results
+
+def parseresultsfromdiskioserial(filename):    # {{{
+	"""
+	PARSERESULTSFROMDISK - ...
+	 
+	    Usage:
+	       results=parseresultsfromdiskioserial(filename)
+	"""
+
+	#Open file
+	try:
+		fid=open(filename,'rb')
+	except IOError as e:
+		raise IOError("loadresultsfromdisk error message: could not open '%s' for binary reading." % filename)
+
+	results={}
+
+	#Read fields until the end of the file.
+	result=ReadData(fid)
+	while result:
+		#Get time and step
+		if not result['step'] in results:
+			results[result['step']]={}
+			results[result['step']]['step']=result['step']
+			results[result['step']]['time']=result['time'] 
+	
+		#Add result
+		if result['step'] in results and \
+		   result['fieldname'] in results[result['step']] and \
+		   not strcmp(result['fieldname'],'SolutionType'):
+			results[result['step']][result['fieldname']]=numpy.concatenate((results[result['step']][result['fieldname']],result['field']),axis=0)
+		else:
+			results[result['step']][result['fieldname']]=result['field']
+
+		#read next result
+		result=ReadData(fid)
+
+	fid.close()
+
+	return results
+	# }}}
+
+def parseresultsfromdiskiosplit(filename):    # {{{
+	"""
+	PARSERESULTSFROMDISKIOSPLIT - ...
+	 
+	    Usage:
+	       results=parseresultsfromdiskiosplit(filename)
+	"""
+
+	#Open file
+	try:
+		fid=open(filename,'rb')
+	except IOError as e:
+		raise IOError("loadresultsfromdisk error message: could not open '%s' for binary reading." % filename)
+
+	results={}
+
+	#if we have done split I/O, ie, we have results that are fragmented across patches, 
+	#do a first pass, and figure out the structure of results
+	result=ReadDataDimensions(fid)
+	while result:
+
+		#Get time and step
+		if not result['step'] in results:
+			results[result['step']]={}
+			results[result['step']]['step']=result['step']
+			results[result['step']]['time']=result['time'] 
+
+		#Add result
+		if strcmpi(result['fieldname'],'Patch'):
+			results[result['step']][result['fieldname']]=[0,result['N']]
+		else:
+			results[result['step']][result['fieldname']]=float('NaN')
+
+		#read next result
+		result=ReadDataDimensions(fid)
+
+	#do a second pass, and figure out the size of the patches
+	fid.seek(0)    #rewind
+	result=ReadDataDimensions(fid)
+	while result:
+
+		#Add result
+		if strcmpi(result['fieldname'],'Patch'):
+			patchdimensions=results[result['step']][result['fieldname']]
+			results[result['step']][result['fieldname']]=[patchdimensions[0]+result['M'],result['N']]
+
+		#read next result
+		result=ReadDataDimensions(fid)
+
+	#allocate patches
+	for result in results.itervalues():
+		if 'Patch' in result:
+			result['Patch']=numpy.zeros(shape=(result['Patch'][0],result['Patch'][1]),dtype=float)
+			result['counter']=0    #use to index into the patch
+
+	#third pass, this time to read the real information
+	fid.seek(0)    #rewind
+	result=ReadData(fid)
+	while result:
+
+		#Get time and step
+		if not result['step'] in results:
+			results[result['step']]={}
+			results[result['step']]['step']=result['step']
+			results[result['step']]['time']=result['time'] 
+
+		#Add result
+		if strcmpi(result['fieldname'],'Patch'):
+			counter=results[result['step']]['counter']
+			counter2=counter+result['field'].shape[0]-1
+			results[result['step']][result['fieldname']][counter:counter2,:]=result['field']
+
+			#increment counter: 
+			results[result['step']]['counter']=counter2+1
+		else:
+			results[result['step']][result['fieldname']]=result['field']
+
+		#read next result
+		result=ReadData(fid)
+
+	#close file
+	fid.close()
+
+	return results
+	# }}}
+
+def ReadData(fid):    # {{{
+	"""
+	READDATA - ...
+	 
+	    Usage:
+	       field=ReadData(fid)
+	"""
+
+	#read field
+	try:
+		length=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+
+		fieldname=struct.unpack('%ds' % length,fid.read(length))[0][:-1]
+		time=struct.unpack('d',fid.read(struct.calcsize('d')))[0]
+		step=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+
+		type=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+		M=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+		if   type==1:
+			field=numpy.array(struct.unpack('%dd' % M,fid.read(M*struct.calcsize('d'))),dtype=float)
+		elif type==2:
+			field=struct.unpack('%ds' % M,fid.read(M))[0][:-1]
+		elif type==3:
+			N=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+#			field=transpose(fread(fid,[N M],'double'));
+			field=numpy.zeros(shape=(M,N),dtype=float)
+			for i in xrange(M):
+				field[i,:]=struct.unpack('%dd' % N,fid.read(N*struct.calcsize('d')))
+		else:
+			raise TypeError("cannot read data of type %d" % type)
+
+		result={}
+		result['fieldname']=fieldname
+		result['time']=time
+		result['step']=step
+		result['field']=field
+
+	except struct.error as e:
+		result={}
+
+	return result
+	# }}}
+
+def ReadDataDimensions(fid):    # {{{
+	"""
+	READDATADIMENSIONS - read data dimensions, step and time, but not the data itself.
+	 
+	    Usage:
+	       field=ReadDataDimensions(fid)
+	"""
+
+	#read field
+	try:
+		length=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+
+		fieldname=struct.unpack('%ds' % length,fid.read(length))[0][:-1]
+		time=struct.unpack('d',fid.read(struct.calcsize('d')))[0]
+		step=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+
+		type=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+		M=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+		N=1    #default
+		if   type==1:
+			fid.seek(M*8,1)
+		elif type==2:
+			fid.seek(M,1)
+		elif type==3:
+			N=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
+			fid.seek(N*M*8,1)
+		else:
+			raise TypeError("cannot read data of type %d" % type)
+
+		result={}
+		result['fieldname']=fieldname
+		result['time']=time
+		result['step']=step
+		result['M']=M
+		result['N']=N
+
+	except struct.error as e:
+		result={}
+
+	return result
+	# }}}
+
Index: /issm/branches/trunk-jpl-damage/src/m/model/petscversion.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/petscversion.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/petscversion.py	(revision 12878)
@@ -0,0 +1,34 @@
+import os
+from issmdir import *
+from MatlabFuncs import *
+
+def petscversion():
+	"""
+	PETSCVERSION - recover petsc version number, inside config.h file
+ 
+	    Usage:
+	        PETSC_VERSION=petscversion();
+	"""
+
+	#default
+	PETSC_VERSION=3
+
+	configfile=os.path.join(issmdir(),'config.h')
+	if not os.path.exists(configfile):
+		raise RuntimeError("File '%s' not found. ISSM has not been configured yet!" % configfile)
+
+	#go through the file, and recover the line we want
+	try:
+		fid=open(configfile,'r')
+	except IOError as e:
+		raise IOerror("could not open file: '%s'" % configfile)
+
+	for tline in fid:
+		if strncmp(tline,'#define _PETSC_MAJOR_',21):
+			PETSC_VERSION=int(tline[22])
+			break
+
+	fid.close()
+
+	return PETSC_VERSION
+
Index: /issm/branches/trunk-jpl-damage/src/m/model/plot/applyoptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/plot/applyoptions.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/plot/applyoptions.m	(revision 12878)
@@ -31,20 +31,16 @@
 end
 
-%xlabel
+%xlabel, ylabel and zlabel
 if exist(options,'xlabel');
 	xlabel(getfieldvalue(options,'xlabel'),'FontSize',fontsize,'FontWeight',fontweight);
 end
-
-%ylabel
 if exist(options,'ylabel');
 	ylabel(getfieldvalue(options,'ylabel'),'FontSize',fontsize,'FontWeight',fontweight);
 end
-
-%zlabel
 if exist(options,'zlabel');
 	zlabel(getfieldvalue(options,'zlabel'),'FontSize',fontsize,'FontWeight',fontweight);
 end
 
-%xtikcs
+%xticks, yticks and zticks
 if exist(options,'xtick'), set(gca,'XTick',getfieldvalue(options,'xtick')); end
 if exist(options,'ytick'), set(gca,'YTick',getfieldvalue(options,'ytick')); end
@@ -75,5 +71,5 @@
 end
 
-%xlim
+%xlim, ylim and zlim
 if exist(options,'xlim');
 	xlim(getfieldvalue(options,'xlim'));
@@ -83,4 +79,7 @@
 if exist(options,'ylim');
 	ylim(getfieldvalue(options,'ylim'));
+end
+if exist(options,'zlim');
+	zlim(getfieldvalue(options,'zlim'));
 end
 
@@ -92,10 +91,4 @@
 end
 
-
-%zlim
-if exist(options,'zlim');
-	zlim(getfieldvalue(options,'zlim'));
-end
-
 %Basinzoom
 if exist(options,'basin');
@@ -107,5 +100,4 @@
 	showbasins(options);
 end
-
 
 %Caxis
@@ -127,16 +119,6 @@
 
 %colormap
-if exist(options,'colormap'),
-	cname=getfieldvalue(options,'colormap');
-	if strcmpi(cname,'Ala'),
-		c = jet(64);
-		c = c (32:end,:);
-	elseif strcmpi(cname,'redblue'),
-		%m = 30;
-		%n = fix(0.5*m);
-		%r = [(0:1:n-1)/n,ones(1,n)];
-		%g = [(0:n-1)/n, (n-1:-1:0)/n];
-		%b = [ones(1,n),(n-1:-1:0)/n];
-		%c = [r(:), g(:), b(:)]; 
+c = getcolormap(options);
+h = colormap(c);
 
 		c = hsv(64);
@@ -302,5 +284,5 @@
 		textpositioni=textposition{i};
 		textrotationi=textrotation{i};
-		h=text(textpositioni(1),textpositioni(2),textstringi,'FontSize',textsizei,'FontWeight',textweighti,'Color',textcolori,'Rotation',textrotationi);
+		h=text(textpositioni(1),textpositioni(2),10,textstringi,'FontSize',textsizei,'FontWeight',textweighti,'Color',textcolori,'Rotation',textrotationi);
 		set(h,'Clipping','on'); %prevent text from appearing outside of the box
 	end
@@ -359,4 +341,5 @@
 if exist(options,'axispos'),
 	Axis=getfieldvalue(options,'axispos');
+	hold on
 	set(gca,'pos',Axis);
 end
@@ -384,4 +367,8 @@
 			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
 			set(gcf,'Position',fix([left bott widt/2 heig]));
+		elseif strcmpi(figposition,'square'),
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=min(screen(3)-25,screen(4)-25);
+			set(gcf,'Position',fix([left+(screen(3)-widt) bott widt widt]));
 		elseif strcmpi(figposition,'portrait'),
 			%reformat with letter paper size (8.5" x 11")
@@ -426,4 +413,6 @@
 		A=expread([ jplsvn() '/projects/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']);
@@ -444,5 +433,5 @@
 	line(A.x,A.y,ones(size(A.x)),'color','b');
 	patch([Ax(1)  Ax(2)  Ax(2)  Ax(1) Ax(1)],[Ay(1)  Ay(1)  Ay(2)  Ay(2) Ay(1)],[1 1 1],'EdgeColor',[0 0 0],'LineWidth',1,'FaceLighting','none')
-	patch( [mdx(1) mdx(2) mdx(2) mdx(1)],[mdy(1) mdy(1) mdy(2) mdy(2)],ones(4,1),'EdgeColor',[0 0 0],'FaceColor','r','FaceAlpha',0.5)
+	patch([mdx(1) mdx(2) mdx(2) mdx(1)],[mdy(1) mdy(1) mdy(2) mdy(2)],ones(4,1),'EdgeColor',[0 0 0],'FaceColor','r','FaceAlpha',0.5)
 	colorbar('off');
 	%back to main gca
@@ -452,13 +441,20 @@
 %flag edges of a partition
 if exist(options,'partitionedges')
-[xsegments ysegments]=flagedges(md.mesh.elements,md.mesh.x,md.mesh.y,md.qmu.partition);
-xsegments=xsegments*getfieldvalue(options,'unit',1);
-ysegments=ysegments*getfieldvalue(options,'unit',1);
-color=getfieldvalue(options,'partitionedgescolor','r-');
-linewidth=getfieldvalue(options,'linewidth',1);
-hold on;
-for i=1:length(xsegments),
-	plot(xsegments(i,:),ysegments(i,:),color,'LineWidth',linewidth);
-end
+	[xsegments ysegments]=flagedges(md.mesh.elements,md.mesh.x,md.mesh.y,md.qmu.partition);
+	xsegments=xsegments*getfieldvalue(options,'unit',1);
+	ysegments=ysegments*getfieldvalue(options,'unit',1);
+	color=getfieldvalue(options,'partitionedgescolor','r-');
+	linewidth=getfieldvalue(options,'linewidth',1);
+	hold on;
+	for i=1:length(xsegments),
+		plot(xsegments(i,:),ysegments(i,:),color,'LineWidth',linewidth);
+	end
+end
+
+%Scatter
+if exist(options,'scatter')
+	data=getfieldvalue(options,'scatter');
+	hold on
+	plot_scatter(data(:,1),data(:,2),getfieldvalue(options,'scattersize',3),data(:,3),options);
 end
 
Index: /issm/branches/trunk-jpl-damage/src/m/model/plot/colormaps/getcolormap.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/plot/colormaps/getcolormap.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/plot/colormaps/getcolormap.m	(revision 12878)
@@ -0,0 +1,55 @@
+function map = getcolormap(options)
+%GETCOLORMAP - get colormap from options
+%
+%   Usage:
+%      map = getcolormap(options)
+
+%default is jet
+if ~exist(options,'colormap'),
+	map = jet;
+	return
+end
+
+map = getfieldvalue(options,'colormap');
+if isnumeric(map);
+	%user provided a full colormap
+	return;
+end
+
+%OK this is an in-house colormap
+if ~ischar(map), error('colormap format not supported'); end
+
+if strcmpi(map,'Ala'),
+	map = jet(256);
+	map = map(128:end,:);
+elseif strcmpi(map,'redblue'),
+	map = hsv(256);
+	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 = hsv2rgb(map);
+elseif strcmpi(map,'Rignot'),
+	alpha=getfieldvalue(options,'alpha',1);
+	map = hsv(256);
+	map = rgb2hsv(map);
+	map(:,2) = max(min( (0.1+map(:,1)).^(1/alpha) ,1),0);
+	map = hsv2rgb(map);
+elseif strcmpi(map,'Rignot2'),
+	alpha=getfieldvalue(options,'alpha',1);
+	map = hsv(256);
+	map = rgb2hsv(map);
+	map(:,2) = max(min( (0.1+map(:,1)).^(1/alpha) ,1),0);
+	map = hsv2rgb(map);
+	map=flipud(map);
+elseif strcmpi(map,'Seroussi'),
+	alpha=getfieldvalue(options,'alpha',1);
+	map = hsv(256);
+	map = flipud(map);
+	map = map(1:floor(0.7*size(map,1)),:);
+	map = rgb2hsv(map);
+	map(:,2) = max(min( (0.1+map(:,1)).^(1/alpha) ,1),0);
+	map = hsv2rgb(map);
+else
+	eval(['map = ' map ';']);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/model/plot/colormaps/haxby.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/plot/colormaps/haxby.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/plot/colormaps/haxby.m	(revision 12878)
@@ -0,0 +1,36 @@
+function map = haxby(m);
+%HAXBY - Haxby color map
+%   HAXBY(M) returns an M-by-3 matrix containing a colormap with Haxby's
+%   colors, commonly used for displaying bathymetry data.
+%   HAXBY, by itself, is the same length as the current colormap.
+%
+%   Colormap is based on the colors used by W. F. Haxby's Gravity
+%   field of World's oceans, 1985, developed for geoid and gravity maps.
+%   The version used here is formed from a linear interpolation of
+%   the GMT color table used by MB-System by David W. Caress and Dale N. Chayes.
+%   <http://www.ldeo.columbia.edu/res/pi/MB-System>
+
+if nargin < 1, m = size(get(gcf,'colormap'),1); end
+
+ncolors=11;
+c=[...
+	37     57   175
+	40    127   251
+	50    190   255
+	106   235   255
+	138   236   174
+	205   255   162
+	240   236   121
+	255   189    87
+	255   161    68
+	255   186   133
+	255   255   255];
+
+pp=1:(m-1)/(ncolors-1):m;
+r=interp1(pp,c(:,1),1:m);
+g=interp1(pp,c(:,2),1:m);
+b=interp1(pp,c(:,3),1:m);
+map=[r' g' b']/255;
+
+%Fix bug of interp1 (M. Morlighem)
+map(find(map>1))=1;
Index: /issm/branches/trunk-jpl-damage/src/m/model/plot/colormaps/lbmap.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/plot/colormaps/lbmap.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/plot/colormaps/lbmap.m	(revision 12878)
@@ -0,0 +1,109 @@
+function map = lbmap(n,scheme)
+%LBMAP Returns specified Light-Bertlein colormap.
+%
+%   LBMAP(N,SCHEME) returns an Nx3 colormap. SCHEME can be one of the
+%   following strings:
+%
+%       'Blue'       Single-hue progression to purlish-blue (default)
+%       'BlueGray'   Diverging progression from blue to gray
+%       'BrownBlue'  Orange-white-purple diverging scheme
+%       'RedBlue'    Modified spectral scheme
+%
+%   If N is not specified, the size of the colormap is determined by the
+%   current figure. If no figure exists, MATLAB creates one.
+%
+%Example 1: 7-color single-hue blue (default)
+%   load penny
+%   imagesc(P)
+%   colormap(lbmap(7))
+%   colorbar
+%
+%Example 2: 11-color modified spectrum
+%   load penny
+%   imagesc(P)
+%   colormap(lbmap(11,'RedBlue'))
+%   colorbar
+%
+%   See also HSV, GRAY, HOT, BONE, COPPER, PINK, FLAG, COLORMAP, RGBPLOT.
+
+% Reference:
+% A. Light & P.J. Bartlein, "The End of the Rainbow? Color Schemes for
+% Improved Data Graphics," Eos,Vol. 85, No. 40, 5 October 2004.
+% http://geography.uoregon.edu/datagraphics/EOS/Light&Bartlein_EOS2004.pdf
+
+% Copyright 2007-2010 The MathWorks, Inc.
+
+%defensive programming
+error(nargchk(0,2,nargin))
+error(nargoutchk(0,1,nargout))
+
+%defaults
+if nargin<2
+	scheme = 'Blue';
+end
+if nargin<1
+	n = size(get(gcf,'colormap'),1);
+end
+
+%valid schemes
+switch lower(scheme)
+	case 'blue'
+		baseMap = BlueMap;
+	case 'bluegray'
+		baseMap = BlueGrayMap;
+	case 'brownblue'
+		baseMap = BrownBlueMap;
+	case 'redblue'
+		baseMap = RedBlueMap;
+	otherwise
+		error(['Invalid scheme ' scheme])
+	end
+	idx1 = linspace(0,1,size(baseMap,1));
+	idx2 = linspace(0,1,n);
+	map = interp1(idx1,baseMap,idx2);
+
+function baseMap = BlueMap
+	baseMap = [243 246 248;
+	224 232 240;
+	171 209 236;
+	115 180 224;
+	35 157 213;
+	0 142 205;
+	0 122 192]/255;
+
+function baseMap = BlueGrayMap
+	%DivergingBlueGray
+	baseMap = [  0 170 227;
+	53 196 238;
+	133 212 234;
+	190 230 242;
+	217 224 230;
+	146 161 170;
+	109 122 129;
+	65  79  81]/255;
+
+function baseMap = BrownBlueMap
+	baseMap = [144 100  44;
+	187 120  54;
+	225 146  65;
+	248 184 139;
+	244 218 200;
+	241 244 245;
+	207 226 240;
+	160 190 225;
+	109 153 206;
+	70  99 174;
+	24  79 162]/255;
+
+function baseMap = RedBlueMap
+	baseMap = [175  53  71;
+	216  82  88;
+	239 133 122;
+	245 177 139;
+	249 216 168;
+	242 238 197;
+	216 236 241;
+	154 217 238;
+	68 199 239;
+	0 170 226;
+	0 116 188]/255;
Index: /issm/branches/trunk-jpl-damage/src/m/model/plot/plot_gridded.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/plot/plot_gridded.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/plot/plot_gridded.m	(revision 12878)
@@ -6,6 +6,4 @@
 %
 %   See also: PLOTMODEL
-
-whitepos=getfieldvalue(options,'whitepos',2); %1: up, 2: down, else: none
 
 %process mesh and data
@@ -29,4 +27,10 @@
 end
 
+%Get and change colormap
+map    = getcolormap(options);
+lenmap = size(map,1);
+map    = [1 1 1; map];
+options=changefieldvalue(options,'colormap',map);
+
 %Process data_grid: add white in NaN and correct caxis accordingly
 if exist(options,'caxis'),
@@ -40,27 +44,14 @@
 	data_max=max(data_grid(:));
 end
-options=changefieldvalue(options,'cbYLim',[data_min data_max]);
-if whitepos==1,
-	white  =data_max + (data_max-data_min)/55;
-	options=changefieldvalue(options,'caxis',[data_min white]);
-	data_grid(isnan(data_grid))=white;
-elseif whitepos==2,
-	white  =data_min - (data_max-data_min)/55;
-	options=changefieldvalue(options,'caxis',[white data_max]);
-	data_grid(isnan(data_grid))=white;
-end
+options = changefieldvalue(options,'cbYLim',[data_min data_max]);
+white   = data_min - (data_max-data_min)/(lenmap);
+options = changefieldvalue(options,'caxis',[white data_max]);
+data_grid(isnan(data_grid))=white;
 
 %Select plot area 
-subplot(plotlines,plotcols,i);
+subplotmodel(plotlines,plotcols,i,options);
 
 %shading interp;
 h=imagesc(xlim,ylim,data_grid);set(gca,'YDir','normal');
-map=getfieldvalue(options,'colormap',jet);
-if whitepos==1,
-	map(end,:)=[1 1 1];
-elseif whitepos==2,
-	map(1,:)=[1 1 1];
-end
-options=changefieldvalue(options,'colormap',map);
 
 %last step: mesh gridded?
Index: /issm/branches/trunk-jpl-damage/src/m/model/plot/plot_manager.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/plot/plot_manager.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/plot/plot_manager.m	(revision 12878)
@@ -165,4 +165,10 @@
 if exist(options,'sectionvalue')
 	plot_section(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a Profile plot
+if exist(options,'profile')
+	plot_profile(md,data,options,nlines,ncols,i);
 	return;
 end
Index: /issm/branches/trunk-jpl-damage/src/m/model/plot/plot_overlay.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/plot/plot_overlay.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/plot/plot_overlay.m	(revision 12878)
@@ -41,4 +41,8 @@
 	md=radarpower(md,options);
 end
+contrast = getfieldvalue(options,'contrast',1);  
+radar = (md.radaroverlay.pwr).^(contrast);
+radar = radar./max(radar(:));
+%radar(find(radar==0))=1; %Change background from black to white
 
 %InterpFromMeshToGrid
@@ -50,8 +54,14 @@
 ncols =length(md.radaroverlay.x);
 disp('Interpolating data on grid...');
-[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);
+if radaronly,
+	x_m=xmin:xspacing:xmin+ncols*xspacing;
+	y_m=ymax-nlines*yspacing:yspacing:ymax;
+	data_grid=NaN*ones(nlines,ncols);
+else
+	[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);
+end
 
-%Process data_grid
+%Process data_grid (For processing, it is better not to have nan)
 pos=find(isinf(data_grid));
 if ~isempty(pos),
@@ -70,55 +80,57 @@
 end
 data_nan=find(isnan(data_grid));
-
-%Generate HSV image
-contrast=getfieldvalue(options,'contrast',1);  
-transparency=getfieldvalue(options,'alpha',1);
 data_grid(data_nan)=data_min; 
 
+%Special colormaps that require hsv treatment
 colorm=getfieldvalue(options,'colormap','Rignot');
-if strcmpi(colorm,'Rignot'),
-	%hue (H)
-	h_data=(data_grid-data_min)/(data_max-data_min+eps);
-	if radaronly, h_data(:)=0; end
-	%saturation (S)
-	s_data=max(min((0.1+h_data).^(1/transparency),1),0);
-elseif strcmpi(colorm,'Seroussi'),
-	%hue (H)
-	h_data=1-(data_grid-data_min)/(data_max-data_min+eps)*0.7;
-	%h_data=(data_grid-data_min)/(data_max-data_min)*2/3;
-	if radaronly, h_data(:)=0; end
-	%saturation (S)
-	s_data=max(min((0.1+h_data).^(1/transparency),1),0);
-elseif strcmpi(colorm,'redblue')
-	data_mean=data_min+(data_max-data_min)/2;
-	%hue (H)
-	%h_data=0.7*ones(size(data_grid));
-	%h_data(find(data_grid>data_mean))=1;
-	h_data=1*ones(size(data_grid));
-	h_data(find(data_grid<data_mean))=0.7;
-	%saturation (S)
-	s_data=max(min(abs(data_grid-data_mean)/(data_max-data_mean) ,1),0);
+if strcmpi(colorm,'Rignot') | strcmpi(colorm,'Seroussi') | strcmpi(colorm,'redblue')
+	if strcmpi(colorm,'Rignot'),
+		transparency=getfieldvalue(options,'alpha',1);
+		h=(data_grid-data_min)/(data_max-data_min+eps);
+		if radaronly, h(:)=0; end
+		s=max(min((0.1+h).^(1/transparency),1),0);
+	elseif strcmpi(colorm,'Seroussi'),
+		transparency=getfieldvalue(options,'alpha',1);
+		h=1-(data_grid-data_min)/(data_max-data_min+eps)*0.7;
+		if radaronly, h(:)=0; end
+		s=max(min((0.1+h).^(1/transparency),1),0);
+	elseif strcmpi(colorm,'redblue')
+		data_mean=data_min+(data_max-data_min)/2;
+		h=1*ones(size(data_grid));
+		h(find(data_grid<data_mean))=0.7;
+		s=max(min(abs(data_grid-data_mean)/(data_max-data_mean) ,1),0);
+	else
+		error('colormap not supported yet. (''Rignot'' and ''redblue'' are the only cupported colormaps)');
+	end
+	%(S) Saturation is 0 in NaNs
+	s(data_nan)=0;
+	%(V) intensity is based on radar image
+	v=radar; %use radar power as intensity
+
+	%Transform HSV to RGB
+	image_hsv=zeros(size(data_grid,1),size(data_grid,2),3);
+	image_hsv(:,:,1)=h; clear h;
+	image_hsv(:,:,2)=s; clear s;
+	image_hsv(:,:,3)=v; clear v;
+	image_rgb=hsv2rgb(image_hsv);
 else
-	error('colormap not supported yet. (''Rignot'' and ''redblue'' are the only cupported colormaps)');
+	colorm = getcolormap(options);
+	len    = size(colorm,1);
+
+	ind = ceil((len-1)*(data_grid-data_min)/(data_max - data_min + eps) +1);
+	ind(find(ind>len))=len;
+	image_rgb=zeros(size(data_grid,1),size(data_grid,2),3);
+	r=colorm(:,1); image_rgb(:,:,1)=r(ind); clear r;
+	g=colorm(:,2); image_rgb(:,:,2)=g(ind); clear g;
+	b=colorm(:,3); image_rgb(:,:,3)=b(ind); clear b;
+
+	%Now add radarmap
+	r = image_rgb(:,:,1).*radar;  r(data_nan) = radar(data_nan);  image_rgb(:,:,1) = r;  clear r;
+	g = image_rgb(:,:,2).*radar;  g(data_nan) = radar(data_nan);  image_rgb(:,:,2) = g;  clear g;
+	b = image_rgb(:,:,3).*radar;  b(data_nan) = radar(data_nan);  image_rgb(:,:,3) = b;  clear b;
 end
 
-%Saturation is 0 in NaNs
-s_data(data_nan)=0;
-%intensity (V)
-radar=(md.radaroverlay.pwr).^(contrast);
-v_data=radar/max(radar(:)); %use radar power as intensity
-
-%Change background from black to white
-%pos=find(v_data==0);v_data(pos)=1;
-
-%Transform HSV to RGB
-image_hsv=zeros(size(data_grid,1),size(data_grid,2),3);
-image_hsv(:,:,1)=h_data;
-image_hsv(:,:,2)=s_data;
-image_hsv(:,:,3)=v_data;
-image_rgb=hsv2rgb(image_hsv);
-
 %Select plot area 
-subplot(plotlines,plotcols,i);
+subplotmodel(plotlines,plotcols,i,options);
 
 %Plot: 
@@ -134,8 +146,9 @@
 
 %Apply options, without colorbar and without grid
-options=changefieldvalue(options,'colormap',colorm);           %We used an HSV colorbar
+options=changefieldvalue(options,'colormap',colorm);              % We used an HSV colorbar
 if ~isnan(data_min),
-	options=changefieldvalue(options,'caxis',[data_min data_max]); %force caxis so that the colorbar is ready
+	options=changefieldvalue(options,'caxis',[data_min data_max]); % force caxis so that the colorbar is ready
 end
-options=addfielddefault(options,'axis','equal off');           %default axis
+options=addfielddefault(options,'axis','equal off');              % default axis
 applyoptions(md,data,options);
+drawnow
Index: /issm/branches/trunk-jpl-damage/src/m/model/plot/plot_profile.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/plot/plot_profile.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/plot/plot_profile.m	(revision 12878)
@@ -0,0 +1,55 @@
+function plot_profile(md,data,options,nlines,ncols,ii)
+%PLOT_SECTION - plot a given field on a profile
+%
+%   Usage:
+%      plot_profile(md,data,options,nlines,ncols,i)
+%
+%   See also: PLOTMODEL
+
+%process model
+[x_m y_m z_m elements_m is2d isplanet]=processmesh(md,[],options);
+if is2d, error('only 3d model supported'); end
+
+%Get number of curves and generate random colors
+numcurves=size(data,2);
+colorm=getfieldvalue(options,'colormap','lines');
+color=eval([ colorm '(numcurves);']);
+options=removefield(options,'colormap',0); %back to default colormap
+
+%Get coordinates
+location=getfieldvalue(options,'profile');
+if ~isnumeric(location) | numel(location)~=2,
+	error('location provided not supported (should be [x y])');
+end
+xprof=location(1);
+yprof=location(2);
+
+%Loop over number of curves
+for i=1:numcurves,
+
+	%Process data
+	[datai datatype]=processdata(md,data(:,i),options);
+
+	%resolution
+	if exist(options,'resolution'),
+		resolution=getfieldvalue(options,'resolution');
+	else %Default resolution
+		resolution=[100];
+		disp(['plot_profile warning: no resolution specified, using default: ' num2str(resolution) ]);
+	end
+
+	%Compute profile value
+	[z,data_interp]=ProfileValues(md,datai,xprof,yprof,resolution);
+
+	%plot profile
+	subplot(nlines,ncols,ii)
+	plot(data_interp,z,'color',color(i,:),'LineWidth',getfieldvalue(options,'linewidth',1),'LineStyle','-');
+	hold on;
+end
+
+%apply options
+options=addfielddefault(options,'title','Profile');
+options=addfielddefault(options,'colorbar',0);
+options=addfielddefault(options,'ylabel','z');
+options=addfielddefault(options,'view',2);
+applyoptions(md,[],options);
Index: /issm/branches/trunk-jpl-damage/src/m/model/plot/plotdoc.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/plot/plotdoc.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/plot/plotdoc.m	(revision 12878)
@@ -94,4 +94,5 @@
 disp('       ''showsection'': show section used by ''sectionvalue'' (string ''on'' or a number of labels)');
 disp('       ''sectionvalue'': give the value of data on a profile given by an Argus file (string ''Argusfile_name.exp'')');
+disp('       ''profile'': give the value of data along a vertical profile ([xlocation ylocation])');
 disp('       ''smooth'': smooth element data (string ''yes'' or integer)');
 disp('       ''title'': same as standard matlab option');
Index: /issm/branches/trunk-jpl-damage/src/m/model/plot/plotmodel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/plot/plotmodel.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/plot/plotmodel.m	(revision 12878)
@@ -48,5 +48,4 @@
 		for i=1:numberofplots,
 			plot_manager(getfieldvalue(options.list{i},'model',md),options.list{i},subplotwidth,nlines,ncols,i);
-			%cbfreeze;
 		end
 	catch me,
Index: /issm/branches/trunk-jpl-damage/src/m/model/plot/subplotmodel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/plot/subplotmodel.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/plot/subplotmodel.m	(revision 12878)
@@ -0,0 +1,35 @@
+function ha=subplotmodel(nlines,ncols,num,options);
+%SUBPLOTMODEL -  tight subplot that includes margins
+%
+%   Usage:
+%      h=subplotmodel(nlines,ncols,i,options)
+
+%Regular subplot
+if ~exist(options,'tightsubplot')
+	subplot(nlines,ncols,num);
+	return;
+end
+
+gap     = getfieldvalue(options,'gap',[.01 .01]);
+hmargin = getfieldvalue(options,'hmargin',[.01 .01]);
+vmargin = getfieldvalue(options,'vmargin',[.01 .01]);
+
+height = (1-sum(vmargin)-(nlines-1)*gap(1))/nlines; 
+width  = (1-sum(hmargin)-(ncols-1)*gap(2))/ncols;
+ymin   = 1-vmargin(2)-height; 
+
+for i = 1:nlines
+	xmin = hmargin(1);
+	for j = 1:ncols
+		if(((i-1)*ncols+j)==num)
+			ha = axes('Units','normalized', ...
+				'Position',[xmin ymin width height],'XTickLabel','','YTickLabel','','Visible','off');
+			return
+		end
+		xmin = xmin+width+gap(2);
+	end
+	ymin = ymin-height-gap(1);
+end
+
+%Activate new axes
+axes(ha);
Index: /issm/branches/trunk-jpl-damage/src/m/model/process_solve_options.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/process_solve_options.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/process_solve_options.py	(revision 12878)
@@ -0,0 +1,47 @@
+import os
+
+def process_solve_options(options):
+	"""
+	DEFAULT_SOLVE_OPTIONS - set up default options for solve phase
+ 
+	    Usage:
+	       options=process_solve_options(options)
+ 
+	    See also: SOLVE
+	"""
+
+	outoptions={}
+
+	#solution_type: check on this option, error out otherwise
+	solution_type=options.getfieldvalue('solution_type')
+	if solution_type in (DiagnosticSolutionEnum,PrognosticSolutionEnum,ThermalSolutionEnum,\
+			SteadystateSolutionEnum,TransientSolutionEnum,EnthalpySolutionEnum,\
+			BalancethicknessSolutionEnum,BedSlopeSolutionEnum,SurfaceSlopeSolutionEnum,HydrologySolutionEnum,FlaimSolutionEnum):
+		raise ValueError("process_solve_options error message: solution_type '%s' not supported yet!" % EnumToString(solution_type))
+	outoptions['solution_type']=solution_type
+
+	outoptions['upload']=options.getfieldvalue('upload','off')
+	outoptions['batch']=options.getfieldvalue('batch','no')
+	outoptions['loadonly']=options.getfieldvalue('loadonly',False)
+	outoptions['directory']=options.getfieldvalue('directory','')
+
+	#  process qmu arguments
+	outoptions['qmudir']=options.getfieldvalue('qmudir','qmu'+str(os.getpid()))
+	outoptions['qmufile']=options.getfieldvalue('qmufile','qmu')    # qmufile cannot be changed unless ????script.sh is also changed
+	outoptions['overwrite']=options.getfieldvalue('overwrite','n')
+	outoptions['keep']=options.getfieldvalue('keep','n')
+	outoptions['ivar']=options.getfieldvalue('ivar',1)
+	outoptions['iresp']=options.getfieldvalue('iresp',1)
+	outoptions['imethod']=options.getfieldvalue('imethod',1)
+	outoptions['iparams']=options.getfieldvalue('iparams',1)
+	outoptions['runmpi']=options.getfieldvalue('runmpi',False)
+
+	#  process flaim arguments
+	outoptions['fmdir']=options.getfieldvalue('fmdir','fm'+str(os.getpid()))
+	outoptions['overwrite']=options.getfieldvalue('overwrite','n')
+	outoptions['keep']=options.getfieldvalue('keep','y')
+	outoptions['latsgn']=options.getfieldvalue('latsgn',0)
+	outoptions['cmap']=options.getfieldvalue('cmap',None)
+
+	return outoptions
+
Index: /issm/branches/trunk-jpl-damage/src/m/model/radarpower.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/radarpower.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/radarpower.m	(revision 12878)
@@ -37,11 +37,14 @@
 			error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MOG/mog150_greenland_map.jpg not found.']);
 		end
-		jpgim=[jplsvn() '/projects/ModelData/MOG/mog150_greenland_map.jpg'];
-		geom=load([jplsvn() '/projects/ModelData/MOG/mog150_greenland_map.jpgw'],'ascii');
+		name = 'mog150_greenland_map';
+		%name = 'mog100_hp1_v10';
+		%name = 'mog500_hp1_v10';
+		jpgim=[jplsvn() '/projects/ModelData/MOG/' name '.jpg'];
+		geom=load([jplsvn() '/projects/ModelData/MOG/' name '.jpgw'],'ascii');
 
 		%geom:   xposting nbcols nbrows yposting xmin ymax
 		xmin=max(geom(5),x0);
 		xmax=min(geom(5)+geom(1)*geom(2),x1);
-		ymin=max(geom(6)-geom(4)*geom(3),y0);
+		ymin=max(geom(6)-geom(3)*geom(4),y0);
 		ymax=min(geom(6),y1);
 
@@ -106,5 +109,4 @@
 	toplefty=floor((overlay_ylim(2)-y1)/overlay_yposting); % y max
 
-
 	%Read and crop file
 	disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
Index: /issm/branches/trunk-jpl-damage/src/m/model/regionaltransient2d.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/regionaltransient2d.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/regionaltransient2d.m	(revision 12878)
@@ -106,5 +106,5 @@
 			thickness=PatchToVec(md1.results.TransientSolution(t).Thickness);
 			spcx=[spcx InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,vx,md2.mesh.x,md2.mesh.y)];
-			spcy=[spcy InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,vx,md2.mesh.x,md2.mesh.y)];
+			spcy=[spcy InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,vy,md2.mesh.x,md2.mesh.y)];
 			spct=[spct InterpFromMeshToMesh2d(md1.mesh.elements,md1.mesh.x,md1.mesh.y,thickness,md2.mesh.x,md2.mesh.y)];
 			steps=[steps t*md1.timestepping.time_step];
Index: /issm/branches/trunk-jpl-damage/src/m/model/setmask.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/setmask.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/setmask.m	(revision 12878)
@@ -25,5 +25,5 @@
 elements=md.mesh.elements;
 
-%Assign elementonfloatingice, elementongroundedice, vertexongroundedice and vertexonfloatingice. Only change at your own peril! This is synchronized heavily with the GroundingLineMigration module. {{{1
+%Assign elementonfloatingice, elementongroundedice, vertexongroundedice and vertexonfloatingice. Only change at your own peril! This is synchronized heavily with the GroundingLineMigration module. {{{
 elementonfloatingice=FlagElements(md,floatingicename);
 elementongroundedice=FlagElements(md,groundedicename);
Index: /issm/branches/trunk-jpl-damage/src/m/model/setmask.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/setmask.py	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/setmask.py	(revision 12878)
@@ -22,5 +22,5 @@
 	elements = md.mesh.elements
 
-	#Assign elementonfloatingice, elementongroundedice, vertexongroundedice and vertexonfloatingice. Only change at your own peril! This is synchronized heavily with the GroundingLineMigration module. {{{1
+	#Assign elementonfloatingice, elementongroundedice, vertexongroundedice and vertexonfloatingice. Only change at your own peril! This is synchronized heavily with the GroundingLineMigration module. {{{
 	elementonfloatingice = fe.FlagElements(md, floatingicename)
 	elementongroundedice = fe.FlagElements(md, groundedicename) 
Index: /issm/branches/trunk-jpl-damage/src/m/model/solve.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/solve.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/solve.m	(revision 12878)
@@ -24,21 +24,20 @@
 %      md=solve(md,DiagnosticSolutionEnum);
 
-%recover options
+%recover and process solve options
 options=pairoptions(varargin{:},'solution_type',solutionenum);
-
-%add default options
 options=process_solve_options(options);
 
 %recover some fields
 md.private.solution=options.solution_type;
+cluster=md.cluster;
 
 %check model consistency
 disp('checking model consistency');
 if (solutionenum == FlaimSolutionEnum)
-	modelconsistency(true);
-	md.mesh.checkconsistency(md,solutionenum);
-	md.flaim.checkconsistency(md,solutionenum);
-	if ~modelconsistency()
-		error(' ');
+	md.private.isconsistent=true;
+	md=checkconsistency(md.mesh,md,solutionenum);
+	md=checkconsistency(md.flaim,md,solutionenum);
+	if md.private.isconsistent==false,
+		error('Model not consistent, see messages above');
 	end
 else
@@ -46,15 +45,16 @@
 end
 
-%if running qmu analysis, some preprocessing of dakota files using 
-%models fields needs to be carried out. 
+%First, build a runtime name that is unique
+c=clock;
+md.private.runtimename=sprintf('%s-%02i-%02i-%04i-%02i-%02i-%02i-%i',md.miscellaneous.name,c(2),c(3),c(1),c(4),c(5),floor(c(6)),feature('GetPid'));
+
+%if running qmu analysis, some preprocessing of dakota files using models
+%fields needs to be carried out. 
 if md.qmu.isdakota,
 	md=preqmu(md,options);
 end
 
-%Save model as is (in case of a crash)
-assignin('base',inputname(1),md);
-
 %flaim analysis
-if (md.private.solution == FlaimSolutionEnum)
+if (options.solution_type == FlaimSolutionEnum)
 	md=flaim_sol(md,options);
 	md.private.solution=EnumToString(options.solution_type);
@@ -62,29 +62,58 @@
 end
 
-%Marshall model data into a binary file.
-marshall(md);
-
-%write a template file for issm to use, in parallel
-PetscFile(md.solver,[md.miscellaneous.name '.petsc']);
-
-%If running in parallel, we have a different way of launching the solution
-%sequences. 
-if ~strcmpi(md.cluster.name,'none'),
-	md=solveparallel(md,options);
+%Do we load results only?
+if options.loadonly,  
+	md=loadresultsfromcluster(md);
 	return;
 end
 
-%Launch correct solution sequence
-md=issm(md,md.private.solution);
+%Wite all input files
+marshall(md);                                          % bin file
+PetscFile(md.solver,[md.miscellaneous.name '.petsc']); % petsc file
+BuildQueueScript(cluster,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 ~ispetsc,
+	disp('PETSC support not included, running on 1 cpu only!');
+	cluster.np=1;
+end
+
+%Stop here if batch mode
+if strcmpi(options.batch,'yes')
+	disp('batch mode requested: not launching job interactively');
+	disp('launch solution sequence on remote cluster by hand');
+	return;
+end
+
+%Launch job
+modelname = md.miscellaneous.name;
+filelist  = {[modelname '.bin '] [modelname '.petsc '] [modelname '.queue ']};
+if md.qmu.isdakota,
+	filelist{end+1} = [modelname '.qmu.in'];
+end
+LaunchQueueJob(cluster,md.miscellaneous.name,md.private.runtimename,filelist);
+
+%did we even try to run? if so, wait on lock
+if strcmpi(options.upload,'on'),
+	disp('solve done uploading test decks');
+	return;
+end
+
+%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');
+		md=loadresultsfromcluster(md);
+	end
+end
 
 %post processes qmu results if necessary
 if md.qmu.isdakota,
-	md=postqmu(md);
-	cd ..
 	if ~strncmpi(options.keep,'y',1)
 		system(['rm -rf qmu' num2str(feature('GetPid'))]);
 	end
 end
-
-%convert analysis type to string finally
-md.private.solution=EnumToString(options.solution_type);
Index: /issm/branches/trunk-jpl-damage/src/m/model/solve.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/solve.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/solve.py	(revision 12878)
@@ -0,0 +1,115 @@
+import datetime
+import os
+import shutil
+
+def solve(md,solutionenum,*args):
+	"""
+	SOLVE - apply solution sequence for this model
+ 
+	    Usage:
+	       md=solve(md,solutionenum,varargin)
+	       where varargin is a list of paired arguments of string OR enums
+ 
+	    solution types available comprise:
+	 		 - DiagnosticSolutionEnum
+	 		 - PrognosticSolutionEnum
+	 		 - ThermalSolutionEnum
+	 		 - SteadystateSolutionEnum
+	 		 - TransientSolutionEnum...
+	 		 - BalancethicknessSolutionEnum
+	 		 - BedSlopeSolutionEnum
+	 		 - SurfaceSlopeSolutionEnum
+	 		 - HydrologySolutionEnum
+	 		 - FlaimSolutionEnum
+ 
+	   extra options:
+	       - loadonly : does not solve. only load results
+ 
+	    Examples:
+	       md=solve(md,DiagnosticSolutionEnum);
+	"""
+
+	#recover and process solve options
+	options=pairoptions('solution_type',solutionenum,*args)
+	options=process_solve_options(options)
+
+	#recover some fields
+	md.private.solution=options['solution_type']
+	cluster=md.cluster
+
+	#check model consistency
+	print "checking model consistency"
+	if solutionenum == FlaimSolutionEnum:
+		md.private.isconsistent=True
+		md.mesh.checkconsistency(md,solutionenum)
+		md.flaim.checkconsistency(md,solutionenum)
+		if not md.private.isconsistent:
+			raise RuntimeError("Model not consistent, see messages above.")
+	else:
+		ismodelselfconsistent(md)
+
+	#First, build a runtime name that is unique
+	c=datetime.datetime.now()
+	md.private.runtimename="%s-%02i-%02i-%04i-%02i-%02i-%02i-%i" % (md.miscellaneous.name,c.month,c.day,c.year,c.hour,c.minute,c.second,os.getpid())
+
+	#if running qmu analysis, some preprocessing of dakota files using models
+	#fields needs to be carried out. 
+	if md.qmu.isdakota:
+		md=preqmu(md,options)
+
+	#flaim analysis
+	if options['solution_type'] == FlaimSolutionEnum:
+		md=flaim_sol(md,options)
+		md.private.solution=EnumToString(options['solution_type'])
+		return md
+
+	#Do we load results only?
+	if options['loadonly']:  
+		md=loadresultsfromcluster(md)
+		return md
+
+	#Wite all input files
+	marshall(md)                                           # bin file
+	md.solver.PetscFile(md.miscellaneous.name+'.petsc')    # petsc file
+	cluster.BuildQueueScript(md.miscellaneous.name,md.private.runtimename,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
+	if strcmpi(options['batch'],'yes'):
+		print 'batch mode requested: not launching job interactively'
+		print 'launch solution sequence on remote cluster by hand'
+		return md
+
+	#Launch job
+	modelname = md.miscellaneous.name
+	filelist  = [modelname+'.bin ',modelname+'.petsc ',modelname+'.queue ']
+	if md.qmu.isdakota:
+		filelist.append(modelname+'.qmu.in')
+	cluster.LaunchQueueJob(md.miscellaneous.name,md.private.runtimename,filelist)
+
+	#did we even try to run? if so, wait on lock
+	if strcmpi(options['upload'],'on'):
+		print 'solve done uploading test decks'
+		return md
+
+	#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
+			print 'The results must be loaded manually with md=loadresultsfromcluster(md).'
+		else:            #load results
+			print 'loading results from cluster'
+			md=loadresultsfromcluster(md)
+
+	#post processes qmu results if necessary
+	if md.qmu.isdakota:
+		if not strncmpi(options['keep'],'y',1):
+			shutil.rmtree('qmu'+str(os.getpid()))
+
+	return md
+
Index: sm/branches/trunk-jpl-damage/src/m/model/solveparallel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/solveparallel.m	(revision 12877)
+++ 	(revision )
@@ -1,58 +1,0 @@
-function md=solveparallel(md,options)
-%SOLVEPARALLEL - solution sequence using a cluster in parallel mode
-%
-%   Usage:
-%      md=solveparallel(md);
-
-%retrieve cluster: otherwise, we can't call its methods (subsref bug)
-cluster=md.cluster;
-
-if options.loadonly,  
-	md=loadresultsfromcluster(md);
-else
-
-	%In parallel mode, 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
-
-	%First, build a runtime name that is unique, that we will use to create 
-	%directories, name jobs, etc ...
-	c=clock; md.private.runtimename=sprintf('%s-%02i-%02i-%04i-%02i-%02i-%02i-%i',md.miscellaneous.name,c(2),c(3),c(1),c(4),c(5),floor(c(6)),feature('GetPid'));
-
-	if verLessThan('matlab', '7.6')
-		BuildQueueScript(cluster,md);
-		LaunchQueueJob(cluster,md,options);
-	else
-		cluster.BuildQueueScript(md);
-		cluster.LaunchQueueJob(md,options);
-	end
-
-	if ~strcmpi(options.upload,'on'), %did we even try to run? if so, wait on lock
-
-		%Do we return, or just wait for results?
-		if (md.settings.waitonlock>0 &  ~strcmpi(options.batch,'yes')),
-			%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');
-				md=loadresultsfromcluster(md);
-			end
-		end
-
-		%post processes qmu results if necessary
-		if md.qmu.isdakota,
-			if ~strncmpi(options.keep,'y',1)
-				system(['rm -rf qmu' num2str(feature('GetPid'))]);
-			end
-		end
-	else
-		error('solveparallel done uploading test decks');
-	end
-
-end
Index: /issm/branches/trunk-jpl-damage/src/m/model/solvers/stokesoptions.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/solvers/stokesoptions.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/model/solvers/stokesoptions.m	(revision 12878)
@@ -6,5 +6,5 @@
 
 %retrieve options provided in varargin
-arguments=pairoptions(varargin{:});
+options=pairoptions(varargin{:});
 stokes=struct();
 
Index: /issm/branches/trunk-jpl-damage/src/m/model/waitonlock.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/model/waitonlock.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/model/waitonlock.py	(revision 12878)
@@ -0,0 +1,64 @@
+import os
+import socket
+import time
+from MatlabFuncs import *
+
+def waitonlock(md,executionpath,login,port):
+	"""
+	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(md,executionpath)
+	"""
+
+	#Get filename (lock file) and options
+	executionpath=md.cluster.executionpath
+	cluster=md.cluster.name
+	login=md.cluster.login
+	port=md.cluster.port
+	timelimit=md.settings.waitonlock
+	filename=os.path.join(executionpath,md.private.runtimename,md.miscellaneous.name+'.lock')
+
+	#waitonlock will work if the lock is on the same machine only: 
+	if not strcmpi(socket.gethostname().lower().split('.')[0],cluster):
+
+		print 'solution launched on remote cluster. log in to detect job completion.'
+		choice=raw_input('Is the job successfully completed? (y/n) ')
+		if not strcmp(choice,'y'): 
+			print 'Results not loaded... exiting' 
+			flag=0
+		else:
+			flag=1
+
+	#job is running on the same machine
+	else:
+
+		if 'interactive' in vars(md.cluster) and md.cluster.interactive:
+			#We are in interactive mode, no need to check for job completion
+			flag=1
+			return flag
+		#initialize time and file presence test flag
+		etime=0
+		ispresent=0
+		print "waiting for '%s' hold on... (Ctrl+C to exit)" % filename
+
+		#loop till file .lock exist or time is up
+		while ispresent==0 and etime<timelimit:
+			ispresent=os.path.exist(filename)
+			time.sleep(1)
+			etime+=1/60
+
+		#build output
+		if etime>timelimit:
+			print 'Time limit exceeded. Increase md.settings.waitonlock'
+			print 'The results must be loaded manually with md=loadresultsfromcluster(md).'
+			raise RuntimeError('waitonlock error message: time limit exceeded.')
+			flag=0
+		else:
+			flag=1
+
+	return flag
+
Index: /issm/branches/trunk-jpl-damage/src/m/qmu/preqmu.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/qmu/preqmu.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/qmu/preqmu.m	(revision 12878)
@@ -44,5 +44,5 @@
 responses=expandresponses(md,responses);
 
-%go through variables and responses, and check they don't have more than md.qmu.numberofpartitions values. Also determine numvariables and numresponses{{{1
+%go through variables and responses, and check they don't have more than md.qmu.numberofpartitions values. Also determine numvariables and numresponses{{{
 numvariables=0;
 variable_fieldnames=fieldnames(variables);
@@ -76,5 +76,5 @@
 system(['rm -rf ' md.miscellaneous.name '.m']);
 
-%build a list of variables and responses descriptors. the list is not expanded. {{{1
+%build a list of variables and responses descriptors. the list is not expanded. {{{
 variabledescriptors={};
 variable_fieldnames=fieldnames(md.qmu.variables(options.ivar));
Index: /issm/branches/trunk-jpl-damage/src/m/utils/BC/SetIceShelfBC.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/BC/SetIceShelfBC.py	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/BC/SetIceShelfBC.py	(revision 12878)
@@ -1,44 +1,47 @@
-from numpy import *
+import os
+import numpy
+
 def SetIceShelfBC(md,icefrontfile=''):
-	#SETICESHELFBC - Create the boundary conditions for diagnostic and thermal models for a  Ice Shelf with Ice Front
-	#
-	#   Neumann BC are used on the ice front (an ANRGUS contour around the ice front
-	#   must be given in input)
-	#   Dirichlet BC are used elsewhere for diagnostic
-	#
-	#   Usage:
-	#      md=SetIceShelfBC(md,varargin)
-	#
-	#   Example:
-	#      md=SetIceShelfBC(md);
-	#      md=SetIceShelfBC(md,'Front.exp');
-	#
-	#   See also: SETICESHEETBC, SETMARINEICESHEETBC
+	"""
+	SETICESHELFBC - Create the boundary conditions for diagnostic and thermal models for a  Ice Shelf with Ice Front
+	 
+	    Neumann BC are used on the ice front (an ANRGUS contour around the ice front
+	    must be given in input)
+	    Dirichlet BC are used elsewhere for diagnostic
+	 
+	    Usage:
+	       md=SetIceShelfBC(md,varargin)
+	 
+	    Example:
+	       md=SetIceShelfBC(md);
+	       md=SetIceShelfBC(md,'Front.exp');
+	 
+	    See also: SETICESHEETBC, SETMARINEICESHEETBC
+	"""
 
 	#node on Dirichlet (boundary and ~icefront)
-	if not icefrontfile:
-		nodeonicefront=zeros(md.mesh.numberofvertices)
+	if icefrontfile:
+		if not os.path.exists(icefrontfile):
+			raise IOError("SetIceShelfBC error message: ice front file '%s' not found." % icefrontfile)
+		nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
+		nodeonicefront=double(md.mesh.vertexonboundary and nodeinsideicefront)
 	else:
-		if not os.path.isfile(icefrontfile):
-			print 'SetIceShelfBC error message: ice front file '+icefrontfile+ ' not found'
-			return []
-		nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
-		nodeonicefront=double(md.mesh.vertexonboundary.astype(bool) and nodeinsideicefront.astype(bool))
-	
-	pos=argwhere(logical_and(md.mesh.vertexonboundary.astype(bool),~nodeonicefront.astype(bool)))
-	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices);
-	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices);
-	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices);
-	md.diagnostic.spcvx[pos]=0;
-	md.diagnostic.spcvy[pos]=0;
-	md.diagnostic.spcvz[pos]=0;
-	md.diagnostic.referential=float('NaN')*ones((md.mesh.numberofvertices,6),float);
+		nodeonicefront=numpy.zeros(md.mesh.numberofvertices)
+
+#	pos=find(md.mesh.vertexonboundary & ~nodeonicefront);
+	pos=[i for i,(vob,noif) in enumerate(zip(md.mesh.vertexonboundary,nodeonicefront)) if vob and not noif]
+	md.diagnostic.spcvx=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+	md.diagnostic.spcvy=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+	md.diagnostic.spcvz=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+	md.diagnostic.spcvx[pos]=0
+	md.diagnostic.spcvy[pos]=0
+	md.diagnostic.spcvz[pos]=0
+	md.diagnostic.referential=float('NaN')*numpy.ones((md.mesh.numberofvertices,6))
 
 	#Dirichlet Values
-	if ~isnan(md.inversion.vx_obs) and ~isnan(md.inversion.vy_obs):
-		if (len(md.inversion.vx_obs)==md.mesh.numberofvertices) and (len(md.inversion.vy_obs)==md.mesh.numberofvertices):
-			print '      boundary conditions for diagnostic model: spc set as observed velocities'
-			md.diagnostic.spcvx[pos]=md.inversion.vx_obs[pos]
-			md.diagnostic.spcvy[pos]=md.inversion.vy_obs[pos]
+	if numpy.size(md.inversion.vx_obs)==md.mesh.numberofvertices and numpy.size(md.inversion.vy_obs)==md.mesh.numberofvertices:
+		print '      boundary conditions for diagnostic model: spc set as observed velocities'
+		md.diagnostic.spcvx[pos]=md.inversion.vx_obs[pos]
+		md.diagnostic.spcvy[pos]=md.inversion.vy_obs[pos]
 	else:
 		print '      boundary conditions for diagnostic model: spc set as zero'
@@ -46,46 +49,50 @@
 	#segment on Ice Front
 	#segment on Neumann (Ice Front)
-	segs1=md.mesh.segments[:,0].astype(int)-1
-	segs2=md.mesh.segments[:,1].astype(int)-1
-
-	pos=argwhere(logical_and(nodeonicefront[segs1].astype(bool),nodeonicefront[segs2].astype(bool)))
-	if (md.mesh.dimension==2):
-		pressureload=md.mesh.segments[pos,:];
+#	pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2)));
+	pos=[i for i,(noif1,noif2) in enumerate(zip(nodeonicefront[md.mesh.segments[:,0].astype('int')-1],nodeonicefront[md.mesh.segments[:,1].astype('int')-1])) if noif1 or noif2]
+	if   md.mesh.dimension==2:
+		pressureload=md.mesh.segments[pos,:]
 	elif md.mesh.dimension==3:
-		pressureload_layer=[md.mesh.segments[pos,0:2],md.mesh.segments[pos,1]+md.mesh.numberofvertices2d,md.mesh.segments[pos,0]+md.mesh.numberofvertices2d, md.mesh.segments[pos,2]];
-		pressureload=[];
-		for i in range(1,md.mesh.numberoflayers-1):
-			pressureload=[pressureload ,pressureload_layer1[:,1:4]+(i-1)*md.mesh.numberofvertices2d, pressureload_layer1[:,5]+(i-1)*md.mesh.numberofelements2d ];
+#		pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
+		pressureload_layer1=numpy.concatenate((md.mesh.segments[pos,0:2],md.mesh.segments[pos,1]+md.mesh.numberofvertices2d,md.mesh.segments[pos,0]+md.mesh.numberofvertices2d,md.mesh.segments[pos,2]),axis=1)
+		pressureload=numpy.zeros((0,5))
+		for i in xrange(1,md.mesh.numberoflayers):
+#			pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
+			pressureload=numpy.concatenate((pressureload,numpy.concatenate((pressureload_layer1[:,0:3]+(i-1)*md.mesh.numberofvertices2d,pressureload_layer1[:,4]+(i-1)*md.mesh.numberofelements2d),axis=1)),axis=0)
 
 	#Add water or air enum depending on the element
-	pressureload=[pressureload, 1*md.mask.elementonfloatingice(pressureload[:,end])];
+#	pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))];
+	pressureload=numpy.concatenate((pressureload,1*md.mask.elementonfloatingice[pressureload[:,-1].astype('int')-1].reshape((-1,1))),axis=1)
 
 	#plug onto model
-	md.diagnostic.icefront=pressureload;
+	md.diagnostic.icefront=pressureload
 
 	#Create zeros basalforcings and surfaceforcings
-	if isnan(md.surfaceforcings.precipitation):
-		md.surfaceforcings.precipitation=zeros(md.mesh.numberofvertices);
+	if numpy.isnan(md.surfaceforcings.precipitation).all():
+		md.surfaceforcings.precipitation=numpy.zeros(md.mesh.numberofvertices)
 		print '      no surfaceforcings.precipitation specified: values set as zero'
-	if isnan(md.surfaceforcings.mass_balance):
-		md.surfaceforcings.mass_balance=zeros(md.mesh.numberofvertices);
+	if numpy.isnan(md.surfaceforcings.mass_balance).all():
+		md.surfaceforcings.mass_balance=numpy.zeros(md.mesh.numberofvertices)
 		print '      no surfaceforcings.mass_balance specified: values set as zero'
-	if isnan(md.basalforcings.melting_rate):
-		md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices)
+	if numpy.isnan(md.basalforcings.melting_rate).all():
+		md.basalforcings.melting_rate=numpy.zeros(md.mesh.numberofvertices)
 		print '      no basalforcings.melting_rate specified: values set as zero'
-	if isnan(md.balancethickness.thickening_rate):
-		md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices);
+	if numpy.isnan(md.balancethickness.thickening_rate).all():
+		md.balancethickness.thickening_rate=numpy.zeros(md.mesh.numberofvertices)
 		print '      no balancethickness.thickening_rate specified: values set as zero'
 
-	md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices);
-	md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices);
+	md.prognostic.spcthickness=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+	md.balancethickness.spcthickness=float('NaN')*numpy.ones(md.mesh.numberofvertices)
 
-	if (len(md.initialization.temperature)==md.mesh.numberofvertices):
-		md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices);
-		pos=argwhere(md.mesh.vertexonsurface); md.thermal.spctemperature[pos]=md.initialization.temperature[pos]; #impose observed temperature on surface
-		if (len(md.basalforcings.geothermalflux) !=md.mesh.numberofvertices):
-			md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices);
+	if numpy.size(md.initialization.temperature)==md.mesh.numberofvertices:
+		md.thermal.spctemperature=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+#		pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+		pos=[i for i,vos in enumerate(md.mesh.vertexonsurface) if vos]
+		md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    # impose observed temperature on surface
+		if not numpy.size(md.basalforcings.geothermalflux)==md.mesh.numberofvertices:
+			md.basalforcings.geothermalflux=numpy.zeros(md.mesh.numberofvertices)
 	else:
 		print '      no thermal boundary conditions created: no observed temperature found'
 
 	return md
+
Index: /issm/branches/trunk-jpl-damage/src/m/utils/Basins/isbasin.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/Basins/isbasin.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/Basins/isbasin.m	(revision 12878)
@@ -9,5 +9,5 @@
 
 %First, load basin names:
-load([issmdir '/projects/ModelData/Names/Names.mat']);
+load([jplsvn '/projects/ModelData/Names/Names.mat']);
 
 
Index: /issm/branches/trunk-jpl-damage/src/m/utils/Cluster/parallelrange.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/Cluster/parallelrange.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/Cluster/parallelrange.py	(revision 12878)
@@ -0,0 +1,25 @@
+#! /usr/bin/env python
+def parallelrange(rank,numprocs,globalsize):
+	"""
+	PARALLELRANGE - from a rank, and a number of processors, figure out a range, for parallel tasks.
+ 
+	    Usage: 
+	       i1,i2=parallelrange(rank,numprocs,globalsize)
+	"""
+
+	#We use floor. we under distribute rows. The rows left are then redistributed, therefore resulting in a more even distribution.
+	num_local_rows=[int(globalsize/numprocs) for i in xrange(numprocs)]
+
+	#There may be some rows left. Distribute evenly.
+	row_rest=globalsize - numprocs*int(globalsize/numprocs)
+
+	for i in xrange(row_rest):
+		num_local_rows[i]=num_local_rows[i]+1
+
+	i1=0
+	for i in xrange(rank-1):
+		i1+=num_local_rows[i]
+	i2=i1+num_local_rows[rank-1]-1
+
+	return i1,i2
+
Index: /issm/branches/trunk-jpl-damage/src/m/utils/DataProcessing/gamv.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/DataProcessing/gamv.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/DataProcessing/gamv.m	(revision 12878)
@@ -0,0 +1,70 @@
+function output = gamv(x,y,data,varargin);
+%GAMV - use gslib for Kriging
+%
+%   Usage:
+%      output = gamv(x,y,data,varargin)
+
+options=pairoptions(varargin{:});
+
+nlag = getfieldvalue(options,'nlag', 20);
+dlag = getfieldvalue(options,'dlag', 1000);
+
+%Write data file
+fid=fopen('cluster.dat','w');
+fprintf(fid,'%s\n','Data file');
+fprintf(fid,'%i\n',3);
+fprintf(fid,'%s\n','Xlocation');
+fprintf(fid,'%s\n','Ylocation');
+fprintf(fid,'%s\n','Data');
+fprintf(fid,'%g %g %g\n',[x y data]');
+fclose(fid);
+
+%Write parameter file
+fid=fopen('gamv.par','w');
+fprintf(fid,'\t\t\t\t%s\n','Parameters for GAMV');
+fprintf(fid,'\t\t\t\t%s\n','*******************');
+fprintf(fid,'\n');
+fprintf(fid,'%s\n','START OF PARAMETERS:');
+fprintf(fid,'%-30s %s\n','./cluster.dat'              ,'\file with data');
+fprintf(fid,'%-30s %s\n','1 2 0'                      ,'\columns for X, Y, Z coordinates');
+fprintf(fid,'%-30s %s\n','1 3  '                      ,'\number of variables, column number');
+fprintf(fid,'%-30s %s\n','-1.0e21 1.0e21'             ,'\trimming limits');
+fprintf(fid,'%-30s %s\n','gamv.out'                   ,'\file for variogram output');
+fprintf(fid,'%-30s %s\n',num2str(nlag,'%i')           ,'\number of lags');
+fprintf(fid,'%-30s %s\n',num2str(dlag,'%g')           ,'\lag separation distance');
+fprintf(fid,'%-30s %s\n',num2str(dlag/2,'%g')         ,'\lag tolerance');
+fprintf(fid,'%-30s %s\n','3'                          ,'\number of directions');
+fprintf(fid,'%-30s %s\n','0.0 90.0 50.0 0.0 90.0 50.0','\azm, atol, bandh, dip, dtol, bandv');
+fprintf(fid,'%-30s %s\n','0.0 22.5 25.0 0.0 22.5 25.0','\azm, atol, bandh, dip, dtol, bandv');
+fprintf(fid,'%-30s %s\n','90. 22.5 25.0 0.0 22.5 25.0','\azm, atol, bandh, dip, dtol, bandv');
+fprintf(fid,'%-30s %s\n','0'                          ,'\standardize sill? (0=no, 1=yes)');
+fprintf(fid,'%-30s %s\n','2'                          ,'\number of variograms');
+fprintf(fid,'%-30s %s\n','1 1 1'                      ,'\tail var., head vars., variogram type');
+fprintf(fid,'%-30s %s\n','1 1 3'                      ,'\tail var., head vars., variogram type');
+fclose(fid);
+
+%Call gamv
+system([issmdir() '/externalpackages/gslib/install/gamv gamv.par']);
+delete('gamv.par');
+
+%Read output
+output   = struct('Semivariogram',[],'Covariance',[]);
+counter1 = 1;
+counter2 = 1;
+fid=fopen('gamv.out','r');
+while (~feof(fid)),
+	A=fscanf(fid,'%s',1);
+	if strcmp(A,'Covariance');
+		A=fscanf(fid,'%s',4); %Read tail:Data head:Data direction  2
+		output(counter1).Covariance=fscanf(fid,'%i %g %g %i %g %g',[6 nlag+2])';
+		counter1=counter1+1;
+	elseif strcmp(A,'Semivariogram'),
+		A=fscanf(fid,'%s',4); %Read tail:Data head:Data direction  2
+		output(counter2).Semivariogram=fscanf(fid,'%i %g %g %i %g %g',[6 nlag+2])';
+		counter2=counter2+1;
+	else
+		%do nothing
+	end
+end
+fclose(fid);
+delete('gamv.out')
Index: /issm/branches/trunk-jpl-damage/src/m/utils/DataProcessing/gslib.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/DataProcessing/gslib.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/DataProcessing/gslib.m	(revision 12878)
@@ -0,0 +1,112 @@
+function output = gslib(x,y,data,varargin);
+%GSLIB - use gslib for Kriging
+%
+%   Usage:
+%      output = gslib(x,y,data,varargin)
+
+%Output Matrix
+xmin   = xl(1);
+ymin   = yl(1);
+nx     = 101;
+ny     = 101;
+deltax = 5000;
+deltay = 5000;
+
+%Variogram
+nugget=10;
+sill  =164;
+range =25763;
+
+%Kriging options
+mindata = 1;
+maxdata = 50;
+maxsearchradius = 50000;
+
+%Some intermediaries (Convert to gslib's parameters);
+c = (sill-nugget);
+a = sqrt(3)*range;
+
+%Write data file
+fid=fopen('cluster.dat','w');
+fprintf(fid,'%s\n','Data file');
+fprintf(fid,'%i\n',3);
+fprintf(fid,'%s\n','Xlocation');
+fprintf(fid,'%s\n','Ylocation');
+fprintf(fid,'%s\n','Data');
+fprintf(fid,'%g %g %g\n',[x y data]');
+fclose(fid);
+
+if 0, %GAMV
+	%Write parameter file
+	fid=fopen('gamv.par','w');
+	fprintf(fid,'\t\t\t\t%s\n','Parameters for GAMV');
+	fprintf(fid,'\t\t\t\t%s\n','*******************');
+	fprintf(fid,'\n');
+	fprintf(fid,'%s\n','START OF PARAMETERS:');
+	fprintf(fid,'%-30s %s\n','./cluster.dat'              ,'\file with data');
+	fprintf(fid,'%-30s %s\n','1 2 0'                      ,'\columns for X, Y, Z coordinates');
+	fprintf(fid,'%-30s %s\n','1 3  '                      ,'\number of variables, column number');
+	fprintf(fid,'%-30s %s\n','-1.0e21 1.0e21'             ,'\trimming limits');
+	fprintf(fid,'%-30s %s\n','gamv.out'                   ,'\file for variogram output');
+	fprintf(fid,'%-30s %s\n','20'                         ,'\number of lags');
+	fprintf(fid,'%-30s %s\n','5.0'                        ,'\lag separation distance');
+	fprintf(fid,'%-30s %s\n','3.0'                        ,'\lag tolerance');
+	fprintf(fid,'%-30s %s\n','3'                          ,'\number of directions');
+	fprintf(fid,'%-30s %s\n','0.0 90.0 50.0 0.0 90.0 50.0','\azm, atol, bandh, dip, dtol, bandv');
+	fprintf(fid,'%-30s %s\n','0.0 22.5 25.0 0.0 22.5 25.0','\azm, atol, bandh, dip, dtol, bandv');
+	fprintf(fid,'%-30s %s\n','90. 22.5 25.0 0.0 22.5 25.0','\azm, atol, bandh, dip, dtol, bandv');
+	fprintf(fid,'%-30s %s\n','0'                          ,'\standardize sill? (0=no, 1=yes)');
+	fprintf(fid,'%-30s %s\n','2'                          ,'\number of variograms');
+	fprintf(fid,'%-30s %s\n','1 1 1'                      ,'\tail var., head vars., variogram type');
+	fprintf(fid,'%-30s %s\n','1 1 3'                      ,'\tail var., head vars., variogram type');
+	fclose(fid);
+
+	%Call gamv
+	system([issmdir() '/externalpackages/gslib/install/gamv gamv.par']);
+
+else, %Kriging KB2D
+	%Write parameter file
+	fid=fopen('kb2d.par','w');
+	fprintf(fid,'\t\t\t\t%s\n','Parameters for KB2D');
+	fprintf(fid,'\t\t\t\t%s\n','*******************');
+	fprintf(fid,'\n');
+	fprintf(fid,'%s\n','START OF PARAMETERS:');
+	fprintf(fid,'%-30s %s\n','./cluster.dat'                  ,'\file with data');
+	fprintf(fid,'%-30s %s\n','1 2 3'                          ,'\columns for X, Y and variable');
+	fprintf(fid,'%-30s %s\n','-1.0e21 1.0e21'                 ,'\trimming limits');
+	fprintf(fid,'%-30s %s\n','0'                              ,'\debugging level: 0,1,2,3');
+	fprintf(fid,'%-30s %s\n','kb2d.dbg'                       ,'\file for debuggging output');
+	fprintf(fid,'%-30s %s\n','kb2d.out'                       ,'\file for kriged output');
+	fprintf(fid,'%-30s %s\n',num2str([nx xmin deltax],'%i %10g %6g')  ,'\nx, xmn, xsiz');
+	fprintf(fid,'%-30s %s\n',num2str([ny ymin deltay],'%i %10g %6g')  ,'\nx, xmn, xsiz');
+	fprintf(fid,'%-30s %s\n','1 1'                            ,'\x and y block discretization');
+	fprintf(fid,'%-30s %s\n',num2str([mindata maxdata],'%6g') ,'\min and max data for kriging');
+	fprintf(fid,'%-30s %s\n',num2str(maxsearchradius,'%6g')   ,'\max search radius');
+	fprintf(fid,'%-30s %s\n','1 2.302'                        ,'\0=SK, 1=OK, (mean if SK)');
+	fprintf(fid,'%-30s %s\n',['1 ' num2str(nugget)]           ,'\nst, nugget effect');
+	fprintf(fid,'%-30s %s\n',['3 ' num2str([c 0.0 a a],'%10g')],'\it, c, azm, a_max, a_min');
+	fclose(fid);
+
+	tic;system([issmdir() '/externalpackages/gslib/install/kb2d kb2d.par']);toc;
+	delete('kb2d.par');
+
+	%Read output
+	fid=fopen('kb2d.out','r');
+	while (~feof(fid)),
+		A=fscanf(fid,'%s',1);
+		if strcmp(A,'KB2D');
+			A=fscanf(fid,'%s',1); %Read output
+			params=fscanf(fid,'%i %i %i %i %g %g %g %g %g %g %1',[11 1]);
+		elseif strcmp(A,' Estimate'),
+			continue;
+		elseif strcmp(A,'Estimation'),
+			A=fscanf(fid,'%s',1); %Read Variance
+			A=fscanf(fid,'%g %g',[params(1) params(2)*params(3)]);
+			B=A(1,:); B=reshape(B,[params(3),params(2)])';
+			E=A(2,:); E=reshape(E,[params(3),params(2)])';
+		else
+			%do nothing
+		end
+	end
+	fclose(fid);
+end
Index: /issm/branches/trunk-jpl-damage/src/m/utils/DataProcessing/pkriging.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/DataProcessing/pkriging.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/DataProcessing/pkriging.m	(revision 12878)
@@ -0,0 +1,55 @@
+function [B E]=pkriging(x,y,observations,x_interp,y_interp,varargin);
+%PKRIGING - parallel Kriging
+%
+%   Usage:
+%      [B E]=pkriging(x,y,observations,x_interp,y_interp,varargin);
+
+options=pairoptions(varargin{:});
+cluster=getfieldvalue(options,'cluster',generic('np',10));
+options=removefield(options,'cluster',0);
+name   = ['krig' num2str(feature('GetPid'))];
+
+% =========================================   MARSHALL.m =================================================
+disp(['marshalling file ' name '.bin']);
+fid=fopen([name '.bin'],'wb');
+if fid==-1,
+	error(['marshall error message: could not open ' name '.bin file for binary writing']);
+end
+
+%First, write MaximumNumberOfEnum to make sure that the Enums are synchronized
+WriteData(fid,'enum',MaximumNumberOfEnums(),'data',true,'format','Boolean');
+
+%Write all data
+WriteData(fid,'enum',0,'data',x,'format','DoubleMat');
+WriteData(fid,'enum',1,'data',y,'format','DoubleMat');
+WriteData(fid,'enum',2,'data',observations,'format','DoubleMat');
+WriteData(fid,'enum',3,'data',x_interp,'format','DoubleMat');
+WriteData(fid,'enum',4,'data',y_interp,'format','DoubleMat');
+options.marshall(fid,5);
+st=fclose(fid);
+if st==-1,
+	error(['marshall error message: could not close file ' name '.bin']);
+end
+% =========================================   MARSHALL.m =================================================
+
+%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');
+Download(cluster,name,{[name '.outbin']});
+structure=parseresultsfromdisk([name '.outbin'],0);
+delete([name '.outlog']);
+delete([name '.errlog']);
+delete([name '.outbin']);
+delete([name '.bin']);
+if ~ispc,
+	delete([name '.tar.gz']);
+end
+
+%Process results
+B=structure.AutodiffForward;
+B=reshape(B,size(x_interp,2),size(x_interp,1))';
+E=structure.AutodiffIsautodiff;
+E=reshape(E,size(x_interp,2),size(x_interp,1))';
Index: /issm/branches/trunk-jpl-damage/src/m/utils/DataProcessing/varmap.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/DataProcessing/varmap.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/DataProcessing/varmap.m	(revision 12878)
@@ -0,0 +1,55 @@
+function output = varmap(x,y,data,varargin);
+%VARMAP - use gslib for Kriging
+%
+%   Usage:
+%      output = varmap(x,y,data,varargin)
+
+options=pairoptions(varargin{:});
+
+nxlag = getfieldvalue(options,'nxlag', 20);
+nylag = getfieldvalue(options,'nylag', 20);
+dxlag = getfieldvalue(options,'dxlag', 1000);
+dylag = getfieldvalue(options,'dylag', 1000);
+
+%Write data file
+fid=fopen('cluster.dat','w');
+fprintf(fid,'%s\n','Data file');
+fprintf(fid,'%i\n',3);
+fprintf(fid,'%s\n','Xlocation');
+fprintf(fid,'%s\n','Ylocation');
+fprintf(fid,'%s\n','Data');
+fprintf(fid,'%g %g %g\n',[x y data]');
+fclose(fid);
+
+%Write parameter file
+fid=fopen('varmap.par','w');
+fprintf(fid,'\t\t\t\t%s\n','Parameters for GAMV');
+fprintf(fid,'\t\t\t\t%s\n','*******************');
+fprintf(fid,'\n');
+fprintf(fid,'%s\n','START OF PARAMETERS:');
+fprintf(fid,'%-30s %s\n','./cluster.dat'              ,'\file with data');
+fprintf(fid,'%-30s %s\n','1 3  '                      ,'\number of variables, column number');
+fprintf(fid,'%-30s %s\n','-1.0e21 1.0e21'             ,'\trimming limits');
+fprintf(fid,'%-30s %s\n','0    '                      ,'\1=regular grid, 0=scattered values');
+fprintf(fid,'%-30s %s\n','50 50 1'                    ,'\if =1: nx, ny, nz');
+fprintf(fid,'%-30s %s\n','1.0 1.0 1.0'                ,'\       xsiz, ysiz, zsiz if igrid=1');
+fprintf(fid,'%-30s %s\n','1 2 0'                      ,'\if =0: columns for x, y and z coordinates');
+fprintf(fid,'%-30s %s\n','varmap.out'                 ,'\file for variogram output');
+fprintf(fid,'%-30s %s\n',num2str([nxlag nylag 0],'%i '),'\nxlag, nylag, nzlag');
+fprintf(fid,'%-30s %s\n',num2str([dxlag dylag 1],'%g %g %i'),'\dxlag, dylag, dzlag');
+fprintf(fid,'%-30s %s\n','5'                          ,'\minimum number of pairs');
+fprintf(fid,'%-30s %s\n','0'                          ,'\standardize sill? (0=no, 1=yes)');
+fprintf(fid,'%-30s %s\n','1'                          ,'\number of variograms');
+fprintf(fid,'%-30s %s\n','1 1 1'                      ,'\tail, head, variogram type');
+fclose(fid);
+
+%Call varmap
+system([issmdir() '/externalpackages/gslib/install/varmap varmap.par']);
+delete('varmap.par');
+
+%Read output
+fid=fopen('varmap.out','r');
+A = textscan(fid,'%f %f %f %f %f %f','headerlines',8);
+fclose(fid);
+delete('varmap.out')
+output = reshape(A{1},[2*nxlag+1 2*nylag+1]);
Index: /issm/branches/trunk-jpl-damage/src/m/utils/Exp/expcoarsen.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/Exp/expcoarsen.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/Exp/expcoarsen.m	(revision 12878)
@@ -26,5 +26,5 @@
 %Get exp oldfile
 [path root ext ver]=fileparts(oldfile);
-A=expread(oldfile,1);
+A=expread(oldfile);
 numprofiles=size(A,2);
 
Index: /issm/branches/trunk-jpl-damage/src/m/utils/Exp/expcontract.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/Exp/expcontract.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/Exp/expcontract.m	(revision 12878)
@@ -8,5 +8,5 @@
 
 
-contour=expread(oldfile,1);
+contour=expread(oldfile);
 num=numel(contour.x);
 
Index: /issm/branches/trunk-jpl-damage/src/m/utils/Exp/manipulation/cutarea.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/Exp/manipulation/cutarea.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/Exp/manipulation/cutarea.m	(revision 12878)
@@ -87,8 +87,10 @@
 									A(selection).x=x(1:p1);
 									A(selection).y=y(1:p1);
+									closed(selection)=0;
 									A(end+1).x=x(p2:end);
 									A(end).y=y(p2:end);
 									A(end).density=A(selection).density;
 									A(end).name=A(selection).name;
+									closed(end+1)=0;
 									numprofiles=numprofiles+1;
 									numpoints=numpoints-(p2-p1-1);
@@ -113,4 +115,5 @@
 								else
 									%cut in 2 profiles
+									closed(selection)=0;
 									A(selection).x=x(1:p2);
 									A(selection).y=y(1:p2);
@@ -119,4 +122,5 @@
 									A(end).density=A(selection).density;
 									A(end).name=A(selection).name;
+									closed(end+1)=0;
 									numprofiles=numprofiles+1;
 									numpoints=numpoints-(p1-p2-1);
Index: /issm/branches/trunk-jpl-damage/src/m/utils/Geometry/find_point.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/Geometry/find_point.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/Geometry/find_point.m	(revision 12878)
@@ -8,4 +8,7 @@
 %      f=find_point(tabx,taby,pointx,pointy)
 
+%Compute distance between point and cloud of points
 distance=sqrt((tabx-pointx).^2+(taby-pointy).^2);
-f=find(distance==min(min(distance)));
+
+%find index of the minimum distance and return the first one only
+f=find(distance==min(min(distance)),1);
Index: /issm/branches/trunk-jpl-damage/src/m/utils/Kml/exp2kml.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/Kml/exp2kml.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/Kml/exp2kml.m	(revision 12878)
@@ -8,5 +8,5 @@
 
 %First, read exp file
-domain=expread(input,1);
+domain=expread(input);
 
 
Index: /issm/branches/trunk-jpl-damage/src/m/utils/Miscellaneous/issmdoc.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/Miscellaneous/issmdoc.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/Miscellaneous/issmdoc.m	(revision 12878)
@@ -9,7 +9,7 @@
 disp(sprintf('%s','	   md=model;                                %creates a new empty model structure'));
 disp(sprintf('%s','	   md=triangle(md,''DomainOutline.exp'',50000);   %creates a mesh of the domain outline with a resolution of 50000m'));
-disp(sprintf('%s','	   md=geography(md,''all'','''');               %defines the glacier system as an ice shelf (no island)'));
+disp(sprintf('%s','	   md=setmask(md,''all'','''');               %defines the glacier system as an ice shelf (no island)'));
 disp(sprintf('%s','	   md=parameterize(md,''Square.par'');        %fills all the other fields of the model'));
-disp(sprintf('%s','	   md=setelementstype(md,''macayeal'',''all''); %defines all elements as MacAyeal''s'));
+disp(sprintf('%s','	   md=setflowequation(md,''macayeal'',''all''); %defines all elements as MacAyeal''s'));
 disp(sprintf('%s','	   md=solve(md,DiagnosticSolutionEnum);   %generate the velocity field'));
 disp(sprintf('%s','	   plotmodel(md,''data'',md.results.DiagnosticSolution.Vel);    %displays the velocity (type plotdoc for plotmodel help)'));
Index: /issm/branches/trunk-jpl-damage/src/m/utils/Model/loadmodel.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/Model/loadmodel.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/Model/loadmodel.m	(revision 12878)
@@ -12,6 +12,12 @@
 	error('loadmodel usage error: md=loadmodel(path)');
 end
+
 %check existence
-if ~exist(path)
+if exist(path,'file')
+	%do nothing
+elseif exist([path '.mat'],'file')
+	%add extension
+	path = [path '.mat'];
+else
 	error(['loadmodel error message: file ' path ' does not exist']);
 end
Index: /issm/branches/trunk-jpl-damage/src/m/utils/Numerics/cfl_step.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/Numerics/cfl_step.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/Numerics/cfl_step.m	(revision 12878)
@@ -8,5 +8,5 @@
 %
 %   Example:
-%      dt=cfl_step(md,md,md.results.DiagnosticSolution.Vx,md.results.DiagnosticSolution.Vy)
+%      dt=cfl_step(md,md.results.DiagnosticSolution.Vx,md.results.DiagnosticSolution.Vy)
 
 %Check length of velocities 
Index: /issm/branches/trunk-jpl-damage/src/m/utils/OS/ismumps.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/OS/ismumps.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/OS/ismumps.py	(revision 12878)
@@ -0,0 +1,37 @@
+import os
+from issmdir import *
+from MatlabFuncs import *
+
+def ismumps():
+	"""
+	ISMUMPS - figure out if MUMPS package was compiled with ISSM
+ 
+	    Usage:
+	        flag=ismumps();
+	"""
+
+	configfile=os.path.join(issmdir(),'bin','config.h')    #should find it in the install target
+	if not os.path.exists(configfile):
+		raise RuntimeError("File '%s' not found. ISSM has not been configured yet!" % configfile)
+
+	#go through the file, and recover the line we want
+	flag=2
+	try:
+		fid=open(configfile,'r')
+	except IOError as e:
+		raise IOError("could not open file: '%s'" % configfile)
+
+	for tline in fid:
+		if strncmp(tline,'/* #undef _HAVE_MUMPS_ */',25):
+			flag=0
+			break
+		if  strncmp(tline,'#define _HAVE_MUMPS_',20):
+			flag=1
+			break
+
+	fid.close()
+	if flag==2:
+		raise RuntimeError("could not determine whether MUMPS was or was not compiled.")
+
+	return flag
+
Index: /issm/branches/trunk-jpl-damage/src/m/utils/OS/ispetsc.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/OS/ispetsc.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/OS/ispetsc.py	(revision 12878)
@@ -0,0 +1,37 @@
+import os
+from issmdir import *
+from MatlabFuncs import *
+
+def ispetsc():
+	"""
+	ISPETSC - figure out if PETSC package was compiled with ISSM
+ 
+	    Usage:
+	        flag=ispetsc();
+	"""
+
+	configfile=os.path.join(issmdir(),'bin','config.h')    #should find it in the install target
+	if not os.path.exists(configfile):
+		raise RuntimeError("File '%s' not found. ISSM has not been configured yet!" % configfile)
+
+	#go through the file, and recover the line we want
+	flag=2
+	try:
+		fid=open(configfile,'r')
+	except IOError as e:
+		raise IOError("could not open file: '%s'" % configfile)
+
+	for tline in fid:
+		if strncmp(tline,'/* #undef _HAVE_PETSC_ */',25):
+			flag=0
+			break
+		if  strncmp(tline,'#define _HAVE_PETSC_',20):
+			flag=1
+			break
+
+	fid.close()
+	if flag==2:
+		raise RuntimeError("could not determine whether PETSC was or was not compiled.")
+
+	return flag
+
Index: /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmscpin.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmscpin.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmscpin.m	(revision 12878)
@@ -35,5 +35,5 @@
 		[status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
 		if status, 
-			error('scpin error message: could not find ISSM_DIR_WIN envirnoment variable');
+			error('scpin error message: could not find ISSM_DIR_WIN environment variable');
 		end
 		ISSM_DIR=ISSM_DIR(2:end-2);
Index: /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmscpin.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmscpin.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmscpin.py	(revision 12878)
@@ -0,0 +1,78 @@
+import socket
+import platform
+import subprocess
+import os
+import shutil
+from MatlabFuncs import *
+
+def scpin(host, login,port,path, packages):
+	"""
+	SCPIN get packages from host, using scp on unix, and pscp on windows
+ 
+	    usage: scpin(host,packages,path)
+ 
+ 
+	"""
+
+	#first get hostname
+	hostname=socket.gethostname().lower().split('.')[0]
+
+	#first be sure packages are not in the current directory, this could conflict with pscp on windows. 
+	#remove warnings in case the files do not exist
+	for package in packages:
+		try:
+			os.remove(package)
+		except OSError as e:
+			pass
+
+	#if hostname and host are the same, do a simple copy
+	if strcmpi(hostname,host):
+
+		for package in packages:
+			try:
+				shutil.copy(os.path.join(path,package),os.getcwd())    #keep going, even if success=0
+			except OSError as e:
+				pass
+
+	else:
+
+		if 'Windows' in platform.system():
+			#use the putty project pscp.exe: it should be in the path.
+		
+			#get ISSM_DIR variable
+			if 'ISSM_DIR_WIN' in os.environ:
+				ISSM_DIR=os.environ['ISSM_DIR_WIN'][1:-2]
+			else:
+				raise OSError("scpin error message: could not find ISSM_DIR_WIN environment variable.")
+
+			username=raw_input('Username: (quoted string) ')
+			key=raw_input('Key: (quoted string) ')
+
+			for package in packages:
+				try:
+					subprocess.check_call('%s/externalpackages/ssh/pscp.exe -l "%s" -pw "%s" %s:%s %s' % (ISSM_DIR,username,key,host,os.path.join(path,package),os.getcwd()),shell=True)
+				except CalledProcessError as e:
+					raise CalledProcessError("scpin error message: could not call putty pscp.")
+
+		else:
+			#just use standard unix scp
+			#string to copy multiple files using scp: 
+			if len(packages)==1:
+				string=packages[0]
+			else:
+				string='{'
+				for package in packages:
+					string+=packages[i]+','
+				string=string[:-1]+'}'
+
+
+			if port:
+				subprocess.call('scp -P %d %s@localhost:%s %s' % (port,login,os.path.join(path,string),os.getcwd),shell=True)
+			else:
+				subprocess.call('scp %s@%s:%s %s' % (login,host,os.path.join(path,string),os.getcwd),shell=True)
+		
+			#check scp worked
+			for package in packages:
+				if not os.path.exists(os.path.join('.',package)):
+					raise OSError("scpin error message: could not call scp on *nix system.")
+
Index: /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmscpout.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmscpout.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmscpout.m	(revision 12878)
@@ -26,5 +26,5 @@
 		[status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
 		if status, 
-			error('scpout error message: could not find ISSM_DIR_WIN envirnoment variable');
+			error('scpout error message: could not find ISSM_DIR_WIN environment variable');
 		end
 		ISSM_DIR=ISSM_DIR(2:end-2);
Index: /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmscpout.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmscpout.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmscpout.py	(revision 12878)
@@ -0,0 +1,60 @@
+import socket
+import platform
+import subprocess
+import os
+import shutil
+from MatlabFuncs import *
+
+def issmscpout(host,path,login,port,packages):
+	"""
+	SCPOUT send packages to a host, using scp on unix, and pscp on windows
+ 
+	    usage: scpout(host,path,packages)
+ 
+ 
+	"""
+
+	#get hostname
+	hostname=socket.gethostname().lower().split('.')[0]
+
+	#if hostname and host are the same, do a simple copy
+
+	if strcmpi(host,hostname):
+		for package in packages:
+			here=os.getcwd()
+			os.chdir(path)
+			shutil.rmtree(package)
+			subprocess.call('ln -s %s %s' % (os.path.join(here,package),path),shell=True)
+			os.chdir(here)
+	else:
+		if 'Windows' in platform.system():
+			#use the putty project pscp.exe: it should be in the path.
+		
+			#get ISSM_DIR variable
+			if 'ISSM_DIR_WIN' in os.environ:
+				ISSM_DIR=os.environ['ISSM_DIR_WIN'][1:-2]
+			else:
+				raise OSError("scpout error message: could not find ISSM_DIR_WIN environment variable.")
+
+			username=raw_input('Username: (quoted string) ')
+			key=raw_input('Key: (quoted string) ')
+
+			for package in packages:
+				try:
+					subprocess.check_call('%s/externalpackages/ssh/pscp.exe -l "%s" -pw "%s" %s %s:%s' % (ISSM_DIR,username,key,package,host,path),shell=True)
+				except CalledProcessError as e:
+					raise CalledProcessError("scpout error message: could not call putty pscp.")
+
+		else:
+			#just use standard unix scp
+			#create string of packages being sent
+			string=''
+			for package in packages:
+				string+=' '+package
+			string+=' '
+		
+			if port:
+				subprocess.call('scp -P %d %s %s@localhost:%s' % (port,string,login,path),shell=True)
+			else:
+				subprocess.call('scp %s %s@%s:%s' % (string,login,host,path),shell=True)
+
Index: /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmssh.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmssh.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmssh.m	(revision 12878)
@@ -18,5 +18,5 @@
 		[status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
 		if status, 
-			error('issmssh error message: could not find ISSM_DIR_WIN envirnoment variable');
+			error('issmssh error message: could not find ISSM_DIR_WIN environment variable');
 		end
 		ISSM_DIR=ISSM_DIR(2:end-2);
Index: /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmssh.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmssh.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/OS/issmssh.py	(revision 12878)
@@ -0,0 +1,42 @@
+import socket
+import platform
+import subprocess
+import os
+from MatlabFuncs import *
+
+def issmssh(host,login,port,command):
+	"""
+	ISSMSSH - wrapper for OS independent ssh command.
+ 
+	    usage: 
+	       issmssh(host,command)
+	"""
+
+	#first get hostname 
+	hostname=socket.gethostname().lower().split('.')[0]
+
+	#if same as host, just run the command. 
+	if strcmpi(host,hostname):
+		subprocess.call(command,shell=True)
+	else:
+		if 'Windows' in platform.system():
+			#use the putty project plink.exe: it should be in the path.
+		
+			#get ISSM_DIR variable
+			if 'ISSM_DIR_WIN' in os.environ:
+				ISSM_DIR=os.environ['ISSM_DIR_WIN'][1:-2]
+			else:
+				raise OSError("issmssh error message: could not find ISSM_DIR_WIN environment variable.")
+
+			username=raw_input('Username: (quoted string) ')
+			key=raw_input('Key: (quoted string) ')
+
+			subprocess.call('%s/externalpackages/ssh/plink.exe -ssh -l "%s" -pw "%s" %s "%s"' % (ISSM_DIR,username,key,host,command),shell=True);
+
+		else:
+			#just use standard unix ssh
+			if port:
+				subprocess.call('ssh -l %s -p %d localhost "%s"' % (login,port,command),shell=True)
+			else:
+				subprocess.call('ssh -l %s %s "%s"' % (login,host,command),shell=True)
+
Index: /issm/branches/trunk-jpl-damage/src/m/utils/Shell/issmdir.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/Shell/issmdir.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/Shell/issmdir.py	(revision 12878)
@@ -0,0 +1,24 @@
+import platform
+import os
+from MatlabFuncs import *
+
+def issmdir():
+	"""
+	ISSMDIR - Get ISSM_DIR environment variable
+ 
+	    Usage:
+	       ISSM_DIR=issmdir()
+	"""
+
+	if not 'Windows' in platform.system():
+		ISSM_DIR =os.environ['ISSM_DIR']
+	else:
+		ISSM_DIR =os.environ['ISSM_DIR_WIN']
+		if strcmpi(ISSM_DIR[-1],'/') or strcmpi(ISSM_DIR[-1],'\\'):
+			ISSM_DIR = ISSM_DIR[:-1]    #shave off the last '/'
+
+	if not ISSM_DIR:
+		raise RuntimeError("issmdir error message: 'ISSM_DIR' environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!")
+
+	return ISSM_DIR
+
Index: /issm/branches/trunk-jpl-damage/src/m/utils/consistency/checkfield.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/consistency/checkfield.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/consistency/checkfield.m	(revision 12878)
@@ -1,3 +1,3 @@
-function checkfield(md,fieldname,varargin)
+function md = checkfield(md,fieldname,varargin)
 %CHECKFIELD - check field consistency
 %
@@ -19,10 +19,10 @@
 %
 %   Usage:
-%      checkfield(md,fieldname,options);
+%      md = checkfield(md,fieldname,options);
 %
 %   Example:
-%      checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements 1],'values',[0 1]);
-%      checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
-%      checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
+%      md = checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements 1],'values',[0 1]);
+%      md = checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
+%      md = checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
 
 %get options
@@ -35,5 +35,5 @@
 if exist(options,'empty')
 	if isempty(field),
-		checkmessage(getfieldvalue(options,'message',...
+		md = checkmessage(md,getfieldvalue(options,'message',...
 			['field ''' fieldname ''' is empty']));
 	end
@@ -45,15 +45,15 @@
 	if isnan(fieldsize(1)),
 		if (size(field,2)~=fieldsize(2)),
-			checkmessage(getfieldvalue(options,'message',...
+			md = checkmessage(md,getfieldvalue(options,'message',...
 				['field ''' fieldname ''' should have ' num2str(fieldsize(2)) ' columns']));
 		end
 	elseif isnan(fieldsize(2)),
 		if (size(field,1)~=fieldsize(1)),
-			checkmessage(getfieldvalue(options,'message',...
+			md = checkmessage(md,getfieldvalue(options,'message',...
 				['field ''' fieldname ''' should have ' num2str(fieldsize(1)) ' lines']));
 		end
 	else
-		if ((size(field)~=fieldsize(1)) |  (size(field,2)~=fieldsize(2)))
-			checkmessage(getfieldvalue(options,'message',...
+		if ((size(field,1)~=fieldsize(1)) |  (size(field,2)~=fieldsize(2)))
+			md = checkmessage(md,getfieldvalue(options,'message',...
 				['field ''' fieldname ''' size should be ' num2str(fieldsize(1)) ' x ' num2str(fieldsize(2))]));
 		end
@@ -66,11 +66,11 @@
 	if ~ismember(numel(field),fieldnumel),
 		if length(fieldnumel)==1
-			checkmessage(getfieldvalue(options,'message',...
+			md = checkmessage(md,getfieldvalue(options,'message',...
 				['field ''' fieldname ''' size should be ' sprintf('%g ',fieldnumel) ]));
 		elseif length(fieldnumel)==2
-			checkmessage(getfieldvalue(options,'message',...
+			md = checkmessage(md,getfieldvalue(options,'message',...
 				['field ''' fieldname ''' size should be ' num2str(fieldnumel(1)) ' or ' num2str(fieldnumel(2)) ]));
 		else
-			checkmessage(getfieldvalue(options,'message',...
+			md = checkmessage(md,getfieldvalue(options,'message',...
 				['field ''' fieldname ''' size should be ' sprintf('%g, ',fieldnumel(1:end-1)) ' or ' num2str(fieldnumel(end)) ]));
 		end
@@ -82,13 +82,13 @@
 	field2=reshape(field,prod(size(field)),1);
 	if any(isnan(field2)),
-		checkmessage(getfieldvalue(options,'message',...
+		md = checkmessage(md,getfieldvalue(options,'message',...
 			['NaN values found in field ''' fieldname '''']));
 	end
 end
 
-%check NaN
+%check cell
 if getfieldvalue(options,'cell',0);
 	if ~iscell(field),
-		checkmessage(getfieldvalue(options,'message',...
+		md = checkmessage(md,getfieldvalue(options,'message',...
 			['field ''' fieldname ''' should be a cell']));
 	end
@@ -99,32 +99,32 @@
 	fieldvalues=getfieldvalue(options,'values');
 	if iscell(fieldvalues), %strings
-	if ischar(field) | iscell(fieldvalues),
-		if any(~ismember(field,fieldvalues)),
-			if length(fieldvalues)==1
-				checkmessage(getfieldvalue(options,'message',...
-					['field ''' fieldname ''' value should be ' fieldvalues{1} ]));
-			elseif length(fieldvalues)==2
-				checkmessage(getfieldvalue(options,'message',...
-					['field ''' fieldname ''' values should be ' fieldvalues{1} ' or ' fieldvalues{2} ]));
-			else
-				checkmessage(getfieldvalue(options,'message',...
-					['field ''' fieldname ''' should have values in ' sprintf('''%s'', ',fieldvalues{1:end-1}) 'or ''' fieldvalues{end} '''']));
+		if ischar(field) | iscell(fieldvalues),
+			if any(~ismember(field,fieldvalues)),
+				if length(fieldvalues)==1
+					md = checkmessage(md,getfieldvalue(options,'message',...
+						['field ''' fieldname ''' value should be ''' fieldvalues{1} '''']));
+				elseif length(fieldvalues)==2
+					md = checkmessage(md,getfieldvalue(options,'message',...
+						['field ''' fieldname ''' values should be ''' fieldvalues{1} ''' or ''' fieldvalues{2} '''']));
+				else
+					md = checkmessage(md,getfieldvalue(options,'message',...
+						['field ''' fieldname ''' should have values in ' sprintf('''%s'', ',fieldvalues{1:end-1}) 'or ''' fieldvalues{end} '''']));
+				end
 			end
+		else
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should be one of the following strings: ' sprintf('''%s'', ',fieldvalues{1:end-1}) 'or ''' fieldvalues{end} '''']));
 		end
 	else
-		checkmessage(getfieldvalue(options,'message',...
-			['field ''' fieldname ''' should be one of the following strings: ' sprintf('''%s'', ',fieldvalues{1:end-1}) 'or ''' fieldvalues{end} '''']));
-	end
-else
-	field2=reshape(field,prod(size(field)),1);
-	if isnumeric(field),
-		if any(~ismember(field2,fieldvalues)),
-			checkmessage(getfieldvalue(options,'message',...
-				['field ''' fieldname ''' should have values in [' num2str(fieldvalues) ']']));
+		field2=reshape(field,prod(size(field)),1);
+		if isnumeric(field),
+			if any(~ismember(field2,fieldvalues)),
+				md = checkmessage(md,getfieldvalue(options,'message',...
+					['field ''' fieldname ''' should have values in [' num2str(fieldvalues) ']']));
+			end
+		else
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should be a number in [' num2str(fieldvalues) ']']));
 		end
-	else
-		checkmessage(getfieldvalue(options,'message',...
-			['field ''' fieldname ''' should be a number in [' num2str(fieldvalues) ']']));
-	end
 	end
 end
@@ -135,5 +135,5 @@
 	field2=reshape(field,prod(size(field)),1);
 	if any(field2<lowerbound),
-		checkmessage(getfieldvalue(options,'message',...
+		md = checkmessage(md,getfieldvalue(options,'message',...
 			['field ''' fieldname ''' should have values above ' num2str(lowerbound)]));
 	end
@@ -143,5 +143,5 @@
 	field2=reshape(field,prod(size(field)),1);
 	if any(field2<=lowerbound),
-		checkmessage(getfieldvalue(options,'message',...
+		md = checkmessage(md,getfieldvalue(options,'message',...
 			['field ''' fieldname ''' should have values above ' num2str(lowerbound)]));
 	end
@@ -153,5 +153,5 @@
 	field2=reshape(field,prod(size(field)),1);
 	if any(field2>upperbound),
-		checkmessage(getfieldvalue(options,'message',...
+		md = checkmessage(md,getfieldvalue(options,'message',...
 			['field ''' fieldname ''' should have values below ' num2str(upperbound)]));
 	end
@@ -161,6 +161,6 @@
 	field2=reshape(field,prod(size(field)),1);
 	if any(field2>=upperbound),
-		checkmessage(getfieldvalue(options,'message',...
-			['field ''' fieldname ''' should have values below ' num2str(upperbound(1))]));
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values below ' num2str(upperbound)]));
 	end
 end
@@ -169,5 +169,5 @@
 if getfieldvalue(options,'file',0),
 	if ~exist(field,'file')
-		checkmessage(['file profided in ''' fieldname ''': ''' field ''' does not exist']);
+		md = checkmessage(md,['file provided in ''' fieldname ''': ''' field ''' does not exist']);
 	end
 end
@@ -177,18 +177,18 @@
 	if size(field,1)==md.mesh.numberofvertices,
 		if ~size(field,2)==1,
-			checkmessage(getfieldvalue(options,'message',...
+			md = checkmessage(md,getfieldvalue(options,'message',...
 				['field ''' fieldname ''' should have only one column as there are md.mesh.numberofvertices lines']));
 		end
 	elseif size(field,1)==md.mesh.numberofvertices+1
 		if any(field(end,:)~=sort(field(end,:))),
-			checkmessage(getfieldvalue(options,'message',...
-				['field ''' fieldname ''' columns should be chronological']));
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' columns should be sorted chronologically']));
 		end
 		if any(field(end,1:end-1)==field(end,2:end)),
-			checkmessage(getfieldvalue(options,'message',...
+			md = checkmessage(md,getfieldvalue(options,'message',...
 				['field ''' fieldname ''' columns must not contain duplicate timesteps']));
 		end
 	else
-		checkmessage(getfieldvalue(options,'message',...
+		md = checkmessage(md,getfieldvalue(options,'message',...
 			['field ''' fieldname ''' should have md.mesh.numberofvertices or md.mesh.numberofvertices+1 lines']));
 	end
Index: /issm/branches/trunk-jpl-damage/src/m/utils/consistency/checkfield.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/consistency/checkfield.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/src/m/utils/consistency/checkfield.py	(revision 12878)
@@ -0,0 +1,150 @@
+import numpy
+import os
+from pairoptions import *
+from MatlabFuncs import *
+
+def checkfield(md,fieldname,*args):
+	"""
+	CHECKFIELD - check field consistency
+
+	    Used to check model consistency.
+	    Available options:
+	       - NaN: 1 if check that there is no NaN
+	       - size: [lines cols], NaN for non checked dimensions
+	       - >:  greater than provided value
+	       - >=: greater or equal to provided value
+	       - <:  smallerthan provided value
+	       - <=: smaller or equal to provided value
+	       - < vec:  smallerthan provided values on each vertex
+	       - forcing: 1 if check forcing consistency (size and time)
+	       - values: cell of strings or vector of acceptable values
+	       - numel: list of acceptable number of elements
+	       - cell: 1 if check that is cell
+	       - empty: 1 if check that non empty
+	       - message: overloaded error message
+
+	    Usage:
+	       md = checkfield(md,fieldname,options);
+
+	    Example:
+	       md = checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements 1],'values',[0 1]);
+	       md = checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
+	       md = checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
+	"""
+
+	#get options
+	options=pairoptions(*args)
+
+	#get field from model
+	field=getattr(md,fieldname)
+
+	#check empty
+	if 'empty' in options:
+		if not field:
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' is empty" % fieldname))
+
+	#Check size
+	if 'size' in options:
+		fieldsize=options.getfieldvalue('size')
+		if   numpy.isnan(fieldsize[0]):
+			if not numpy.size(field,1)==fieldsize[1]:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' should have %d columns" % (fieldname,fieldsize[1])))
+		elif numpy.isnan(fieldsize[1]):
+			if not numpy.size(field,0)==fieldsize[0]:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' should have %d lines" % (fieldname,fieldsize[0])))
+		else:
+			if (not numpy.size(field,0)==fieldsize[0]) or (not numpy.size(field,1)==fieldsize[1]):
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %d x %d" % (fieldname,fieldsize[0],fieldsize[1])))
+	
+	#Check numel
+	if 'numel' in options:
+		fieldnumel=options.getfieldvalue('numel')
+		if not numpy.size(field) in fieldnumel:
+			if   len(fieldnumel)==1:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %d" % (fieldname,fieldnumel)))
+			elif len(fieldnumel)==2:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %d or %d" % (fieldname,fieldnumel[0],fieldnumel[1])))
+			else:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %s" % (fieldname,fieldnumel)))
+
+	#check NaN
+	if options.getfieldvalue('NaN',0):
+		if True in numpy.isnan(field):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"NaN values found in field '%s'" % fieldname))
+
+	#check cell
+	if options.getfieldvalue('cell',0):
+		if not isinstance(field,(tuple,list,dict)):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should be a cell" % fieldname))
+
+	#check values
+	if 'values' in options:
+		fieldvalues=options.getfieldvalue('values')
+		if False in ismember(field,fieldvalues):
+			if   len(fieldvalues)==1:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' value should be '%s'"  % (fieldname,fieldvalues[0])))
+			elif len(fieldvalues)==2:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' values should be '%s' or '%s'"  % (fieldname,fieldvalues[0],fieldvalues[1])))
+			else:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' should have values in %s" % (fieldname,fieldvalues)))
+
+	#check greater
+	if '>=' in options:
+		lowerbound=options.getfieldvalue('>=')
+		if numpy.any(field<lowerbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values above %d" % (fieldname,lowerbound)))
+	if '>' in options:
+		lowerbound=options.getfieldvalue('>')
+		if numpy.any(field<=lowerbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values above %d" % (fieldname,lowerbound)))
+
+	#check smaller
+	if '<=' in options:
+		upperbound=options.getfieldvalue('<=')
+		if numpy.any(field>upperbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values below %d" % (fieldname,upperbound)))
+	if '<' in options:
+		upperbound=options.getfieldvalue('<')
+		if numpy.any(field>=upperbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values below %d" % (fieldname,upperbound)))
+
+	#check file
+	if options.getfieldvalue('file',0):
+		if not os.path.exists(field):
+			md = md.checkmessage("file provided in '%s': '%s' does not exist" % (fieldname,field))
+
+	#Check forcings (size and times)
+	if options.getfieldvalue('forcing',0):
+		if   numpy.size(field,0)==md.mesh.numberofvertices:
+			if not numpy.size(field,1)==1:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' should have only one column as there are md.mesh.numberofvertices lines" % fieldname))
+		elif numpy.size(field,0)==md.mesh.numberofvertices+1:
+			if not numpy.all(field[-1,:]==numpy.sort(field[-1,:])):
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' columns should be sorted chronologically" % fieldname))
+			if nump.any(field[-1,0:-1]==field[-1,1:]):
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' columns must not contain duplicate timesteps" % fieldname))
+		else:
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have md.mesh.numberofvertices or md.mesh.numberofvertices+1 lines" % fieldname))
+
+	return md
+
Index: sm/branches/trunk-jpl-damage/src/m/utils/consistency/checkmessage.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/consistency/checkmessage.m	(revision 12877)
+++ 	(revision )
@@ -1,10 +1,0 @@
-function checkmessage(string)
-%CHECKMESSAGE - checkmessage
-%
-%   Used to check model consistency
-%
-%   Usage:
-%      checkmessage(string);
-
-disp(['model not consistent: ' string]);
-modelconsistency(false);
Index: sm/branches/trunk-jpl-damage/src/m/utils/consistency/modelconsistency.m
===================================================================
--- /issm/branches/trunk-jpl-damage/src/m/utils/consistency/modelconsistency.m	(revision 12877)
+++ 	(revision )
@@ -1,23 +1,0 @@
-function flag=modelconsistency(flag_in)
-%MODELCONSISTENCY - return flag for model consistency
-%
-%   Used to check model consistency
-%
-%   Usage:
-%      flag=modelconsistency(flag_in)
-
-persistent consistency;
-
-if nargin==1 & nargout==0,
-	%OK model is inconsistent, set flag as false
-	consistency=flag_in;
-elseif nargin==0 & nargout==1,
-	if isempty(consistency),
-		%modelinconsistent has never been called, model is consistent
-		consistency=true;
-	end
-else
-	message('Bad usage');
-end
-
-flag=consistency;
Index: /issm/branches/trunk-jpl-damage/src/modules/AverageFilter/AverageFilter.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/AverageFilter/AverageFilter.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/AverageFilter/AverageFilter.cpp	(revision 12878)
@@ -53,10 +53,10 @@
 void AverageFilterUsage(void)
 {
-	printf("   AverageFilter usage:\n");
-	printf("   [image_out]=AverageFilter(image_in,pixels);\n\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");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/BamgConvertMesh/BamgConvertMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/BamgConvertMesh/BamgConvertMesh.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/BamgConvertMesh/BamgConvertMesh.cpp	(revision 12878)
@@ -4,25 +4,17 @@
 #include "./BamgConvertMesh.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
 
 	/*input: */
-	double* index=NULL;
-	int     index_rows;
-	double* x=NULL;
-	int     x_cols;
-	double* y=NULL;
-	int     y_rows;
-	int     y_cols;
+	int    *index      = NULL;
+	double *x          = NULL;
+	double *y          = NULL;
+	int     nods,nels,test1,test2;
 
 	/*Output*/
-	BamgMesh* bamgmesh=NULL;
-	BamgGeom* bamggeom=NULL;
-	mxArray* bamgmesh_mat=NULL;
-	mxArray* bamggeom_mat=NULL;
-
-	/*Intermediary*/
-	int nods;
-	int nels;
-	int verbose=0;
+	BamgMesh *bamgmesh     = NULL;
+	BamgGeom *bamggeom     = NULL;
+	mxArray  *bamgmesh_mat = NULL;
+	mxArray  *bamggeom_mat = NULL;
 
 	/*Boot module: */
@@ -37,28 +29,15 @@
 
 	/*Input datasets: */
-	if (verbose) printf("Fetching inputs\n");
-	FetchData(&index,&nels,&index_rows,INDEXHANDLE);
-	FetchData(&x,&nods,&x_cols,XHANDLE);
-	FetchData(&y,&y_rows,&y_cols,YHANDLE);
+	FetchData(&index,&nels,&test1,INDEXHANDLE);
+	FetchData(&x,&nods,XHANDLE);
+	FetchData(&y,&test2,YHANDLE);
 
 	/*Check inputs*/
-	if (nels<0){
-		_error_("Number of elements must be positive, check index number of lines");
-	}
-	if (nods<0){
-		_error_("Number of nods must be positive, check x and y sizes");
-	}
-	if (index_rows!=3){
-		_error_("index should have 3 columns");
-	}
-	if (y_rows!=nods){
-		_error_("x and y do not have the same length");
-	}
-	if (x_cols>1 || y_cols>1){
-		_error_("x and y should have only one column");
-	}
+	if(nels<0) _error2_("Number of elements must be positive, check index number of lines");
+	if(nods<0) _error2_("Number of nods must be positive, check x and y sizes");
+	if(test1!=3) _error2_("index should have 3 columns");
+	if(test2!=nods) _error2_("x and y do not have the same length");
 
 	/* Run core computations: */
-	if (verbose) printf("Call core\n");
 	BamgConvertMeshx(bamgmesh,bamggeom,index,x,y,nods,nels);
 
@@ -75,12 +54,11 @@
 }
 
-void BamgConvertMeshUsage(void)
-{
-	_printf_(true,"BAMGCONVERTMESH - convert [x y index] to a bamg geom and mesh geom");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      [bamggeom bamgmesh]=BamgConvertMesh(index,x,y);\n");
-	_printf_(true,"      index: index of the mesh\n");
-	_printf_(true,"      x,y: coordinates of the nodes\n");
-	_printf_(true,"\n");
+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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/BamgMesher/BamgMesher.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/BamgMesher/BamgMesher.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/BamgMesher/BamgMesher.cpp	(revision 12878)
@@ -51,6 +51,6 @@
 
 void BamgMesherUsage(void){
-	_printf_(true,"\n");
-	_printf_(true,"   usage: [bamgmesh,bamggeom]=%s(bamgmesh,bamggeom,bamgoptions);\n",__FUNCT__);
-	_printf_(true,"\n");
+	_pprintLine_("");
+	_pprintLine_("   usage: [bamgmesh,bamggeom]=" << __FUNCT__ << "(bamgmesh,bamggeom,bamgoptions);");
+	_pprintLine_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/BamgTriangulate/BamgTriangulate.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/BamgTriangulate/BamgTriangulate.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/BamgTriangulate/BamgTriangulate.cpp	(revision 12878)
@@ -27,15 +27,15 @@
 
 	/*Input datasets: */
-	if (verbose) printf("Fetching inputs\n");
+	if (verbose) _printLine_("Fetching inputs");
 	FetchData(&x,&nods,&x_cols,XHANDLE);
 	FetchData(&y,&y_rows,&y_cols,YHANDLE);
 
 	/*Check inputs*/
-	if(y_rows!=nods)         _error_("x and y do not have the same length");
-	if(x_cols>1 || y_cols>1) _error_("x and y should have only one column");
-	if(nods<3)               _error_("At least 3 points are required");
+	if(y_rows!=nods)         _error2_("x and y do not have the same length");
+	if(x_cols>1 || y_cols>1) _error2_("x and y should have only one column");
+	if(nods<3)               _error2_("At least 3 points are required");
 
 	/* Run core computations: */
-	if (verbose) printf("Call core\n");
+	if (verbose) _printLine_("Call core");
 	BamgTriangulatex(&index,&nels,x,y,nods);
 
@@ -49,10 +49,10 @@
 void BamgTriangulateUsage(void)
 {
-	_printf_(true,"BAMGTRIANGULATE - Delaunay Triangulation of a list of points");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      index=BamgTriangulate(x,y);\n");
-	_printf_(true,"      index: index of the triangulation\n");
-	_printf_(true,"      x,y: coordinates of the nodes\n");
-	_printf_(true,"\n");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/Chaco/Chaco.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Chaco/Chaco.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/Chaco/Chaco.cpp	(revision 12878)
@@ -42,5 +42,5 @@
 
 	#ifndef _HAVE_CHACO_ //only works if dakota library has been compiled in.
-	_error_(" Chaco not available! Cannot carry out Chaco partitioning!");
+	_error2_("Chaco not available! Cannot carry out Chaco partitioning!");
 	#endif
 
@@ -82,22 +82,22 @@
 	/*Some debugging print: {{{*/
 	#ifdef _DEBUG_
-	printf("nvtxs: %i\n",nvtxs);
-	printf("options: [");
-	for(i=0;i<10;i++)printf("%g|",options[i]);
-	printf("]\n");
-	printf("start: \n");
-	for (i=0; i<nvtxs+1;i++)printf("%i ",start[i]);
-	printf("\n");
-	printf("adjacency: \n");
-	for (i=0; i<mxGetNzmax(A_IN);i++)printf("%i ",adjacency[i]);
-	printf("\n");
-	printf("nedges: %i %p\n",nedges,ewgts);
-	if(ewgts) for (i = 0; i < nedges; i++)printf("%g ",ewgts[i]);
-	printf("\n");
-	printf("vwgts:\n");
-	for (i = 0; i < nvtxs; i++)printf("%g ",vwgts[i]);
-	printf("\n");
-	printf("nparts: %i\n",nparts[0]);
-	printf("goal: %p\n",goal);
+	_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);
 	#endif
 	/*}}}*/
@@ -132,6 +132,6 @@
 
 void ChacoUsage(void){
-	_printf_(true,"\n");
-	_printf_(true,"Usage: [assgn] = Chaco(A,vwgts,ewgts,x,y,z,options,nparts,goal);\n");
-	_printf_(true,"\n");
+	_pprintLine_("");
+	_pprintLine_("Usage: [assgn] = Chaco(A,vwgts,ewgts,x,y,z,options,nparts,goal);");
+	_pprintLine_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/ContourToMesh/ContourToMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/ContourToMesh/ContourToMesh.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/ContourToMesh/ContourToMesh.cpp	(revision 12878)
@@ -47,5 +47,5 @@
 	if(nlhs!=1 && nlhs!=2){
 		ContourToMeshUsage();
-		_error_(" usage. See above");
+		_error2_("usage. See above");
 	}
 	#endif
@@ -53,5 +53,5 @@
 	if(nrhs!=NRHS){
 		ContourToMeshUsage();
-		_error_(" usage. See above");
+		_error2_("usage. See above");
 	}
 
@@ -82,5 +82,5 @@
 		WriteData(PLHS1,in_elem);
 	}
-	else _error_(" wrong interpolation type");
+	else _error2_("wrong interpolation type");
 
 	/*end module: */
@@ -91,23 +91,23 @@
 void ContourToMeshUsage(void)//{{{1
 {
-	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\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");
+	_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_("");
 }
 //}}}
Index: /issm/branches/trunk-jpl-damage/src/modules/ContourToNodes/ContourToNodes.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/ContourToNodes/ContourToNodes.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/ContourToNodes/ContourToNodes.cpp	(revision 12878)
@@ -82,9 +82,9 @@
 	/* Debugging of contours :{{{1*/
 	/*for(i=0;i<numcontours;i++){
-		printf("\nContour echo: contour number  %i / %i\n",i+1,numcontours);
+		_printLine_("\nContour echo: contour number  " << i+1 << " / " << numcontours);
 		contouri=*(contours+i);
-		printf("   Number of nodes %i\n",contouri->nods);
+		_printLine_("   Number of nodes " << contouri->nods);
 		for (j=0;j<contouri->nods;j++){
-			printf("   %lf %lf\n",*(contouri->x+j),*(contouri->y+j));
+			_printLine_("   " << *(contouri->x+j) << "f " << *(contouri->y+j) << "f");
 		}
 	}*/
@@ -103,12 +103,12 @@
 
 void ContourToNodesUsage(void){
-	printf("   usage:\n");
-	printf("   [flags]=ContourToNodes(x,y,contourname,edgevalue);\n\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("      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("      flags: vector of flags (0 or 1), of size nods.\n");
-	printf("\n");
+	_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_("      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_("      flags: vector of flags (0 or 1), of size nods.");
+	_printLine_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/ElementConnectivity/ElementConnectivity.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/ElementConnectivity/ElementConnectivity.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/ElementConnectivity/ElementConnectivity.cpp	(revision 12878)
@@ -37,6 +37,6 @@
 
 void ElementConnectivityUsage(void) {
-	_printf_(true,"\n");
-	_printf_(true,"   usage: elementconnectivity = %s(elements, nodeconnectivity);\n",__FUNCT__);
-	_printf_(true,"\n");
+	_pprintLine_("");
+	_pprintLine_("   usage: elementconnectivity = " << __FUNCT__ << "(elements, nodeconnectivity);");
+	_pprintLine_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/EnumToString/EnumToString.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/EnumToString/EnumToString.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/EnumToString/EnumToString.cpp	(revision 12878)
@@ -12,5 +12,5 @@
 	/*checks on arguments on the matlab side: */
 	if(nrhs!=NRHS){
-		EnumToStringUsage(); _error_(" usage. See above");
+		EnumToStringUsage(); _error2_("usage. See above");
 	}
 
@@ -27,6 +27,6 @@
 void EnumToStringUsage(void)
 {
-	_printf_(true,"\n");
-	_printf_(true,"   usage: %sstring = EnumToString(enum);\n",__FUNCT__);
-	_printf_(true,"\n");
+	_pprintLine_("");
+	_pprintLine_("   usage: " << __FUNCT__ << "string = EnumToString(enum);");
+	_pprintLine_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/Exp2Kml/Exp2Kml.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Exp2Kml/Exp2Kml.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/Exp2Kml/Exp2Kml.cpp	(revision 12878)
@@ -25,8 +25,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		Exp2KmlUsage(); _error_("Exp2Kml usage error");
+		Exp2KmlUsage(); _error2_("Exp2Kml usage error");
 	}
 	if (nrhs < NRHS) {
-		Exp2KmlUsage(); _error_("Exp2Kml usage error");
+		Exp2KmlUsage(); _error2_("Exp2Kml usage error");
 	}
 
@@ -43,13 +43,13 @@
 	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
 		options->Get(&cm,"central_meridian");
-		if (verbose) printf("  cm=%g\n",cm);
+		if (verbose) _printLine_("  cm=" << cm);
 		options->Get(&sp,"standard_parallel");
-		if (verbose) printf("  sp=%g\n",sp);
+		if (verbose) _printLine_("  sp=" << sp);
 	}
 
 	/*some checks*/
-	if (sgn !=+1 && sgn !=-1) _error_("Hemisphere sgn=%d must be +1 (north) or -1 (south).",sgn);
-	if (fabs(cm)      > 180.) _error_("Central meridian cm=%g must be between -180 (west) and +180 (east) degrees.",cm);
-	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=%g must be between 0 and 90 degrees (in specified hemisphere).",sp);
+	if (sgn !=+1 && sgn !=-1) _error2_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
+	if (fabs(cm)      > 180.) _error2_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error2_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
 
 	/* Run core computations: */
@@ -73,26 +73,26 @@
 
 void Exp2KmlUsage(void){
-	_printf_(true,"Exp2Kml - exp to kml file conversion module:\n");
-	_printf_(true,"\n");
-	_printf_(true,"   This module converts a file from exp to kml format.\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      [ret]=Exp2Kml(filexp,filkml,sgn,'param name',param,...);\n");
-	_printf_(true,"\n");
-	_printf_(true,"      filexp      file name of exp file to be read (char)\n");
-	_printf_(true,"      filkml      file name of kml file to be written (char)\n");
-	_printf_(true,"      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
-	_printf_(true,"\n");
-	_printf_(true,"      central_meridian     central meridian (double, optional, but must specify with sp)\n");
-	_printf_(true,"      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
-	_printf_(true,"      holes       flag for treatment of multiple profiles (char, optional, 'yes' for holes))\n");
-	_printf_(true,"\n");
-	_printf_(true,"      ret         return code (non-zero for warning)\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Examples:\n");
-	_printf_(true,"      [ret]=Exp2Kml('file.exp','file.kml', 1);\n");
-	_printf_(true,"      [ret]=Exp2Kml('file.exp','file.kml', 1,'central_meridian',45,'standard_parallel',70,'holes','yes');\n");
-	_printf_(true,"      [ret]=Exp2Kml('file.exp','file.kml',-1,'central_meridian', 0,'standard_parallel',71,'holes','yes');\n");
-	_printf_(true,"\n");
+	_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_("");
 }
 
Index: /issm/branches/trunk-jpl-damage/src/modules/HoleFiller/HoleFiller.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/HoleFiller/HoleFiller.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/HoleFiller/HoleFiller.cpp	(revision 12878)
@@ -60,10 +60,10 @@
 void HoleFillerUsage(void)
 {
-	printf("   HoleFiller usage:\n");
-	printf("   [image_out]=HoleFiller(image_in,smooth);\n\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");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/InternalFront/InternalFront.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/InternalFront/InternalFront.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/InternalFront/InternalFront.cpp	(revision 12878)
@@ -26,11 +26,11 @@
 	/*Fetch required fields*/
 	FetchData(&numberofelements,mxGetAssignedField(MODEL,0,"numberofelements"));
-	if(numberofelements<=0) _error_("No elements found in the model");
+	if(numberofelements<=0) _error2_("No elements found in the model");
 	FetchData(&elements,&M,&N,mxGetAssignedField(MODEL,0,"elements"));
-	if(M!=numberofelements || N!=3) _error_("Field 'elements' should be of size [md.numberofelements 3]");
+	if(M!=numberofelements || N!=3) _error2_("Field 'elements' should be of size [md.numberofelements 3]");
 	FetchData(&elementonwater,&M,&N,mxGetAssignedField(MODEL,0,"elementonwater"));
-	if(M!=numberofelements || N!=1) _error_("Field 'elementonwater' should be of size [md.numberofelements 1]");
+	if(M!=numberofelements || N!=1) _error2_("Field 'elementonwater' should be of size [md.numberofelements 1]");
 	FetchData(&elementconnectivity,&M,&N,mxGetAssignedField(MODEL,0,"elementconnectivity"));
-	if(M!=numberofelements || N!=3) _error_("Field 'elementconnectivity' should be of size [md.numberofelements 3]");
+	if(M!=numberofelements || N!=3) _error2_("Field 'elementconnectivity' should be of size [md.numberofelements 3]");
 
 	/*Allocate and initialize all variables*/
@@ -94,6 +94,6 @@
 
 void InternalFrontUsage(void) {
-	_printf_(true,"\n");
-	_printf_(true,"   usage: icefront = %s(md);\n",__FUNCT__);
-	_printf_(true,"\n");
+	_pprintLine_("");
+	_pprintLine_("   usage: icefront = " << __FUNCT__ << "(md);");
+	_pprintLine_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/InterpFromGridToMesh/InterpFromGridToMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 12878)
@@ -46,5 +46,5 @@
 	if((nlhs!=NLHS) || (nrhs!=6 && nrhs!=7)){
 		InterpFromGridToMeshUsage();
-		_error_(" usage. See above");
+		_error2_("usage. See above");
 	}
 
@@ -75,21 +75,21 @@
 void InterpFromGridToMeshUsage(void)
 {
-	_printf_(true,"INTERPFROMGRIDTOMESH - interpolation from a grid onto a list of points\n");
-	_printf_(true,"\n");
-	_printf_(true,"   This function is a multi-threaded mex file that interpolates a field\n");
-	_printf_(true,"   defined on a grid onto a list of points\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      data_mesh=InterpFromGridToMesh(x,y,data,x_mesh,y_mesh,default_value);\n");
-	_printf_(true,"\n");
-	_printf_(true,"      data: matrix holding the data to be interpolated onto the mesh.\n");
-	_printf_(true,"      x,y: coordinates of matrix data. (x and y must be in increasing order)\n");
-	_printf_(true,"      x_mesh,y_mesh: coordinates of the points onto which we interpolate.\n");
-	_printf_(true,"      default_value: default value if no data is found (holes).\n");
-	_printf_(true,"      data_mesh: vector of mesh interpolated data.\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Example:\n");
-	_printf_(true,"      load('velocities.mat');\n");
-	_printf_(true,"      md.inversion.vx_obs=InterpFromGridToMesh(x_n,y_m,vx,md.mesh.x,md.mesh.y,0);\n");
-	_printf_(true,"\n");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/InterpFromMesh2d/InterpFromMesh2d.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 12878)
@@ -69,9 +69,9 @@
 	if(nlhs!=NLHS){
 		InterpFromMesh2dUsage();
-		_error_("InterpFromMeshToMesh2dUsage usage error");
+		_error2_("InterpFromMeshToMesh2dUsage usage error");
 	}
 	if((nrhs!=6) && (nrhs!=7) && (nrhs!=8)){
 		InterpFromMesh2dUsage();
-		_error_("InterpFromMeshToMesh2dUsage usage error");
+		_error2_("InterpFromMeshToMesh2dUsage usage error");
 	}
 
@@ -114,9 +114,9 @@
 		/* Debugging of contours :{{{1*/
 		/*for(i=0;i<numcontours;i++){
-		  printf("\nContour echo: contour number  %i / %i\n",i+1,numcontours);
+		  _printLine_("\nContour echo: contour number  " << i+1 << " / " << numcontours);
 		  contouri=*(contours+i);
-		  printf("   Number of vertices %i\n",contouri->nods);
+		  _printLine_("   Number of vertices " << contouri->nods);
 		  for (j=0;j<contouri->nods;j++){
-		  printf("   %lf %lf\n",*(contouri->x+j),*(contouri->y+j));
+		  _printLine_("   " << *(contouri->x+j) << "f " << *(contouri->y+j) << "f");
 		  }
 		  }*/
@@ -131,8 +131,8 @@
 	/*some checks*/
 	if (x_data_rows!=y_data_rows){
-		_error_("vectors x and y should have the same length!");
+		_error2_("vectors x and y should have the same length!");
 	}
 	if (x_prime_rows!=y_prime_rows){
-		_error_("vectors x_prime and y_prime should have the same length!");
+		_error2_("vectors x_prime and y_prime should have the same length!");
 	}
 	
@@ -154,16 +154,16 @@
 void InterpFromMesh2dUsage(void)
 {
-	_printf_(true,"   usage:\n");
-	_printf_(true,"         data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime);\n\n");
-	_printf_(true,"      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value);\n\n");
-	_printf_(true,"      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value,contourname);\n\n");
-	_printf_(true,"   where:\n");
-	_printf_(true,"      x,y: coordinates of the nodes where data is defined\n");
-	_printf_(true,"      index: index of the mesh where data is defined\n");
-	_printf_(true,"      data - vector holding the data to be interpolated onto the points.\n");
-	_printf_(true,"      x_prime,y_prime: coordinates of the mesh vertices onto which we interpolate.\n");
-	_printf_(true,"      default_value: a scalar or vector of size length(x_prime).\n");
-	_printf_(true,"      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");
-	_printf_(true,"      data_prime:  vector of prime interpolated data.\n");
-	_printf_(true,"\n");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 12878)
@@ -64,16 +64,16 @@
 void InterpFromMeshToGridUsage(void)
 {
-	_printf_(true,"INTERPFROMMESHTOGRID - interpolation of a data defined on a mesh onto a grid\n");
-	_printf_(true,"\n");
-	_printf_(true,"   This function is a multi-threaded mex file that interpolates a field\n");
-	_printf_(true,"   defined on a triangular mesh onto a regular grid\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      [x_m,y_m,griddata]=InterpFromMeshToGrid(index,x,y,data,xmin,ymax,xposting,yposting,nlines,ncols,default_value)\n");
-	_printf_(true,"\n");
-	_printf_(true,"      index,x,y: delaunay triangulation defining the mesh.\n");
-	_printf_(true,"      meshdata: vertex values of data to be interpolated.\n");
-	_printf_(true,"      xmin,ymax,posting,nlines,ncols: parameters that define the grid\n");
-	_printf_(true,"      default_value: value of points located out of the mesh.\n");
-	_printf_(true,"\n");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 12878)
@@ -7,28 +7,17 @@
 WRAPPER(InterpFromMeshToMesh2d){
 
-	/*input: */
-	double* index=NULL;
-	int     index_cols;
-	double* x_data=NULL;
-	int     x_data_rows;
-	double* y_data=NULL;
-	int     y_data_rows;
-	double* data=NULL; 
-	int     data_rows;
-	int     data_cols;
-	double* x_interp=NULL;
-	int     x_interp_rows;
-	double* y_interp=NULL;
-	int     y_interp_rows;
-	char*   contourname=NULL;
-	double* default_values=NULL;
-	int     num_default_values=0;
-	DataSet *contours = NULL;
-
-	/*Intermediary*/
-	int nels_data;
-
-	/* output: */
-	double* data_interp=NULL;
+	/*Intermediaties*/
+	int     *index              = NULL;
+	double  *x_data             = NULL;
+	double  *y_data             = NULL;
+	double  *data               = NULL;
+	int      nods_data,nels_data;
+	int      M_data,N_data;
+	double  *x_interp           = NULL;
+	double  *y_interp           = NULL;
+	int      N_interp;
+	Options *options   = NULL;
+	double  *data_interp = NULL;
+	int      test1,test2,test;
 
 	/*Boot module: */
@@ -39,50 +28,27 @@
 	if(nlhs!=NLHS){
 		InterpFromMeshToMesh2dUsage();
-		_error_("InterpFromMeshToMesh2dUsage usage error");
+		_error2_("InterpFromMeshToMesh2dUsage usage error");
 	}
 	#endif
 	/*check on input arguments: */
-	if((nrhs!=6) & (nrhs!=8)){
+	if(nrhs<NRHS){
 		InterpFromMeshToMesh2dUsage();
-		_error_("InterpFromMeshToMesh2dUsage usage error");
+		_error2_("InterpFromMeshToMesh2dUsage usage error");
 	}
 
-	/*Input datasets: */
-	FetchData(&index,&nels_data,&index_cols,INDEX);
-	FetchData(&x_data,&x_data_rows,NULL,X);
-	FetchData(&y_data,&y_data_rows,NULL,Y);
-	FetchData(&data,&data_rows,&data_cols,DATA);
-	FetchData(&x_interp,&x_interp_rows,XINTERP);
-	FetchData(&y_interp,&y_interp_rows,YINTERP);
+	/*Fetch inputs: */
+	FetchData(&index,&nels_data,&test,INDEX); if(test!=3) _error2_("index should have 3 columns");
+	FetchData(&x_data,&nods_data,X);          if(nods_data<3) _error2_("there should be at least three points");
+	FetchData(&y_data,&test,Y);               if(test!=nods_data) _error2_("vectors x and y should have the same length");
+	FetchData(&data,&M_data,&N_data,DATA);    if(M_data*N_data<1) _error2_("data is empty");
+	FetchData(&x_interp,&N_interp,XINTERP);   if(N_interp<1) _error2_("no interpolation requested");
+	FetchData(&y_interp,&test,YINTERP);       if(test!=N_interp) _error2_("vectors x_interp and y_interp should have the same length");
+	FetchData(&options,NRHS,nrhs,ARGUMENTS);
 
-	/*Figure out contours and default values: */
-	if(nrhs==8){
-		FetchData(&default_values,&num_default_values,DEFAULT);
-		FetchData(&contourname,CONTOURNAME);
-		contours=DomainOutlineRead(contourname);
-	}
-	else{
-		num_default_values=0;
-		default_values=NULL;
-		contours=new DataSet();
-	}
-
-
-	/*some checks*/
-	if (x_data_rows!=y_data_rows){
-		_error_("vectors x and y should have the same length!");
-	}
-	if (x_interp_rows!=y_interp_rows){
-		_error_("vectors x_interp and y_interp should have the same length!");
-	}
-	if (index_cols!=3){
-		_error_("index should have 3 columns (input provided has %i columns)",index_cols);
-	}
-
-	/* Run core computations: */
-	InterpFromMeshToMesh2dx(&data_interp,index,x_data,y_data,x_data_rows,nels_data,data,data_rows,data_cols,x_interp,y_interp,x_interp_rows,default_values,num_default_values,contours);
+	/*Run core computations*/
+	InterpFromMeshToMesh2dx(&data_interp,index,x_data,y_data,nods_data,nels_data,data,M_data,N_data,x_interp,y_interp,N_interp,options);
 
 	/*Write data: */
-	WriteData(DATAINTERP,data_interp,x_interp_rows,data_cols);
+	WriteData(DATAINTERP,data_interp,N_interp,N_data);
 
 	/*end module: */
@@ -90,30 +56,27 @@
 }
 
-void InterpFromMeshToMesh2dUsage(void)//{{{1
-
-{
-	_printf_(true,"INTERFROMMESHTOMESH2D - interpolation from a 2d triangular mesh onto a list of point\n");
-	_printf_(true,"\n");
-	_printf_(true,"   This function is a multi-threaded mex file that interpolates a field\n");
-	_printf_(true,"   defined on a triangular mesh onto a list of point\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"         data_interp=InterpFromMeshToMesh2d(index,x,y,data,x_interp,y_interp);\n");
-	_printf_(true,"      or data_interp=InterpFromMeshToMesh2d(index,x,y,data,x_interp,y_interp,default_value,contourname);\n");
-	_printf_(true,"\n");
-	_printf_(true,"      index: index of the mesh where data is defined\n");
-	_printf_(true,"      x,y: coordinates of the nodes where data is defined\n");
-	_printf_(true,"      data: matrix holding the data to be interpolated onto the mesh. (one column per field)\n");
-	_printf_(true,"      x_interp,y_interp: coordinates of the points onto which we interpolate.\n");
-	_printf_(true,"      if default_value and contourname not specified: linear interpolation will happen on all x_interp,y_interp.\n");
-	_printf_(true,"      if (default_value,contourname) specified: 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");
-	_printf_(true,"      note that default_value is either a scalar, or a vector of size  length(x_interp)\n");
-	_printf_(true,"      data_interp: vector of mesh interpolated data.\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Example:\n");
-	_printf_(true,"      load('temperature.mat');\n");
-	_printf_(true,"      md.initialization.temperature=InterpFromMeshToMesh2d(index,x,y,temperature,md.mesh.x,md.mesh.y);\n");
-	_printf_(true,"      md.initialization.temperature=InterpFromMeshToMesh2d(index,x,y,temperature,md.mesh.x,md.mesh.y,253,'Contour.exp');\n");
-	_printf_(true,"\n");
+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_("");
 }
-//}}}
+/*}}}*/
Index: /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h	(revision 12878)
@@ -12,5 +12,8 @@
 #endif
 
-/*Very important definition in case we are compiling a python module!: needs to come before header files inclusion*/
+/* local prototypes: */
+void InterpFromMeshToMesh2dUsage(void);
+
+/*If python: this macro needs to come before header files inclusion*/
 #ifdef _HAVE_PYTHON_
 #define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
@@ -28,4 +31,7 @@
 #include "../../c/EnumDefinitions/EnumDefinitions.h"
 
+#undef __FUNCT__ 
+#define __FUNCT__  "InterpFromMeshToMesh2d"
+
 #ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
@@ -36,6 +42,5 @@
 #define XINTERP prhs[4]
 #define YINTERP prhs[5]
-#define DEFAULT prhs[6]
-#define CONTOURNAME prhs[7]
+#define ARGUMENTS prhs
 
 /* serial output macros: */
@@ -51,12 +56,9 @@
 #define XINTERP PyTuple_GetItem(args,4)
 #define YINTERP PyTuple_GetItem(args,5)
-#define DEFAULT PyTuple_GetItem(args,6)
-#define CONTOURNAME PyTuple_GetItem(args,7)
+#define ARGUMENTS args
+
 /* serial output macros: */
 #define DATAINTERP output,0
 #endif
-
-#undef __FUNCT__ 
-#define __FUNCT__  "InterpFromMeshToMesh2d"
 
 /* serial arg counts: */
@@ -64,8 +66,5 @@
 #define NLHS  1
 #undef NRHS
-#define NRHS  6 //can be 8 though
-
-/* local prototypes: */
-void InterpFromMeshToMesh2dUsage(void);
+#define NRHS  6
 
 #endif
Index: /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 12878)
@@ -76,8 +76,8 @@
 	/*some checks*/
 	if (x_data_rows!=y_data_rows || x_data_rows!=z_data_rows){
-		_error_("vectors x, y and z should have the same length!");
+		_error2_("vectors x, y and z should have the same length!");
 	}
 	if (x_prime_rows!=y_prime_rows || x_prime_rows!=z_prime_rows){
-		_error_("vectors x_prime, y_prime and z_prime should have the same length!");
+		_error2_("vectors x_prime, y_prime and z_prime should have the same length!");
 	}
 	/*get number of elements and number of nodes in the data*/
@@ -98,22 +98,22 @@
 void InterpFromMeshToMesh3dUsage(void)
 {
-	_printf_(true,"INTERPFROMMESHTOMESH3D - interpolation from a 3d hexahedron mesh onto a list of point\n");
-	_printf_(true,"\n");
-	_printf_(true,"   This function is a multi-threaded mex file that interpolates a field\n");
-	_printf_(true,"   defined on a triangular mesh onto a list of point\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      data_prime=InterpFromMeshToMesh3d(index,x,y,z,data,x_prime,y_prime,z_prime,default_value);\n");
-	_printf_(true,"\n");
-	_printf_(true,"      index: index of the mesh where data is defined\n");
-	_printf_(true,"      x,y,z: coordinates of the nodes where data is defined\n");
-	_printf_(true,"      data: matrix holding the data to be interpolated onto the mesh.\n");
-	_printf_(true,"      x_prime,y_prime,z_prime: coordinates of the points onto which we interpolate.\n");
-	_printf_(true,"      default_value: default value if no data is found (holes).\n");
-	_printf_(true,"      data_prime: vector of mesh interpolated data.\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Example:\n");
-	_printf_(true,"      load('temperature.mat');\n");
-	_printf_(true,"      md.initialization.temperature=InterpFromMeshToMesh3d(index,x,y,z,temperature,md.mesh.x,md.mesh.y,md.mesh.z,253);\n");
-	_printf_(true,"\n");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/KMLFileRead/KMLFileRead.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/KMLFileRead/KMLFileRead.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/KMLFileRead/KMLFileRead.cpp	(revision 12878)
@@ -45,8 +45,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		KMLFileReadUsage(); _error_("KMLFileRead usage error");
+		KMLFileReadUsage(); _error2_("KMLFileRead usage error");
 	}
 	if (nrhs < NRHS) {
-		KMLFileReadUsage(); _error_("KMLFileRead usage error");
+		KMLFileReadUsage(); _error2_("KMLFileRead usage error");
 	}
 
@@ -63,12 +63,12 @@
 	if (!strlen(filnam)) strcpy(filnam,"stdout");
 
-	if (verbose) printf("Opening file \"%s\".\n",filnam);
+	if (verbose) _printLine_("Opening file \"" << filnam << "\".");
 	fidi=fopen(filnam,"r");
 
 	/* Run core computations: */
-	if (verbose) printf("Calling core:\n");
+	if (verbose) _printLine_("Calling core:");
 	kobj=KMLFileReadx(fidi);
 
-	if (verbose) printf("Closing file \"%s\".\n",filnam);
+	if (verbose) _printLine_("Closing file \"" << filnam << "\".");
 	fclose(fidi);
 
@@ -83,8 +83,8 @@
 			}
 			else {
-				if (verbose) printf("Opening file \"%s\".\n",write);
+				if (verbose) _printLine_("Opening file \"" << write << "\".");
 				fido=fopen(write,"w");
 				kobj->Write(fido,"");
-				if (verbose) printf("Closing file \"%s\".\n",write);
+				if (verbose) _printLine_("Closing file \"" << write << "\".");
 				ierror=fclose(fido);
 			}
@@ -107,23 +107,23 @@
 
 void KMLFileReadUsage(void){
-	_printf_(true,"KMLFileRead - KML file reader module:\n");
-	_printf_(true,"\n");
-	_printf_(true,"   This module reads a KML file.\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      [ierror]=KMLFileRead(kmlfile,'param name',param,...);\n");
-	_printf_(true,"\n");
-	_printf_(true,"      kmlfile      file name of kml file to be read (char)\n");
-	_printf_(true,"\n");
-	_printf_(true,"      echo         echo command (char, optional, 'off'/'on')\n");
-	_printf_(true,"      deepecho     deep echo command (char, optional, 'off'/'on')\n");
-	_printf_(true,"      write        write command (char, optional, 'off'/'stdout'/kmlfile)\n");
-	_printf_(true,"\n");
-	_printf_(true,"      ierror       return code (non-zero for error)\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Examples:\n");
-	_printf_(true,"      [ierror]=KMLFileRead('file.kml','deepecho','on');\n");
-	_printf_(true,"      [ierror]=KMLFileRead('filin.kml','echo','on','write','filout.kml');\n");
-	_printf_(true,"\n");
+	_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_("");
 }
 
Index: /issm/branches/trunk-jpl-damage/src/modules/KMLMeshWrite/KMLMeshWrite.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/KMLMeshWrite/KMLMeshWrite.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/KMLMeshWrite/KMLMeshWrite.cpp	(revision 12878)
@@ -40,8 +40,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		KMLMeshWriteUsage(); _error_("KMLMeshWrite usage error");
+		KMLMeshWriteUsage(); _error2_("KMLMeshWrite usage error");
 	}
 	if (nrhs < NRHS) {
-		KMLMeshWriteUsage(); _error_("KMLMeshWrite usage error");
+		KMLMeshWriteUsage(); _error2_("KMLMeshWrite usage error");
 	}
 
@@ -87,15 +87,15 @@
 
 	if (nodecon && (mncon != nnodes))
-		_error_("Nodal connectivity table, if supplied, must be supplied for all nodes.");
+	  {_error2_("Nodal connectivity table, if supplied, must be supplied for all nodes.");}
 	else if (!nodecon)
 		mncon=nnodes;
 	if ((llat != nnodes) || (llng != nnodes) || (llat != llng))
-		_error_("Latitude and longitude vectors must be supplied for all nodes.");
+		_error2_("Latitude and longitude vectors must be supplied for all nodes.");
 	if (part && (lprt != nnodes))
-		_error_("Partitioning vector, if supplied, must be supplied for all nodes.");
+		_error2_("Partitioning vector, if supplied, must be supplied for all nodes.");
 	if (data && !((mdata == nnodes) || (mdata == melem)))
-		_error_("Data matrix, if supplied, must be supplied for all nodes or all elements.");
+		_error2_("Data matrix, if supplied, must be supplied for all nodes or all elements.");
 	if (cmap && (ncmap != 3))
-		_error_("Colormap matrix, if supplied, must have three columns for rgb.");
+		_error2_("Colormap matrix, if supplied, must have three columns for rgb.");
 	if (!strlen(filnam))
 		strcpy(filnam,"stdout");
@@ -118,26 +118,26 @@
 
 void KMLMeshWriteUsage(void){
-	_printf_(true,"KMLMeshWrite - KML mesh writer module:\n");
-	_printf_(true,"\n");
-	_printf_(true,"   This module writes the mesh of a model as KML polygons into the specified KML file.\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      ierror=KMLMeshWrite(name,notes,elem,nodecon,lat,long,part,data,cmap,kmlfile);\n");
-	_printf_(true,"\n");
-	_printf_(true,"      name       model name (string, may be empty)\n");
-	_printf_(true,"      notes      model notes (string or cell array of strings, may be empty)\n");
-	_printf_(true,"      elem       elements (double array)\n");
-	_printf_(true,"      nodecon    nodal connectivity array (double array, may be empty)\n");
-	_printf_(true,"      lat        nodal latititudes (double vector)\n");
-	_printf_(true,"      long       nodal longitudes (double vector)\n");
-	_printf_(true,"      part       nodal partitions (double vector, may be empty)\n");
-	_printf_(true,"      data       nodal or element data (double vector, may be empty)\n");
-	_printf_(true,"      cmap       color map (double nx3 array, may be empty)\n");
-	_printf_(true,"      kmlfile    KML file name (string)\n");
-	_printf_(true,"\n");
-	_printf_(true,"      ierror     error flag (double, non-zero for error)\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Example:\n");
-	_printf_(true,"      KMLMeshWrite(md.name,md.notes,md.elements,md.nodeconnectivity,md.lat,md.long,md.part,md.fm_criterion,options.cmap,filekml);\n");
-	_printf_(true,"\n");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/KMLOverlay/KMLOverlay.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/KMLOverlay/KMLOverlay.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/KMLOverlay/KMLOverlay.cpp	(revision 12878)
@@ -31,8 +31,8 @@
 	/*checks on arguments on the matlab side: */
 	if(nlhs>NLHS){
-		KMLOverlayUsage(); _error_("KMLOverlay usage error");
+		KMLOverlayUsage(); _error2_("KMLOverlay usage error");
 	}
 	if(nrhs<NRHS){
-		KMLOverlayUsage(); _error_("KMLOverlay usage error");
+		KMLOverlayUsage(); _error2_("KMLOverlay usage error");
 	}
 
@@ -42,16 +42,16 @@
 
 	options->Get(&lataxis ,&nlat ,"lataxis" );
-	if (verbose && lataxis) for (i=0; i<nlat; i++) printf("  lataxis [%d]=%g\n",i,lataxis[i]);
+	if (verbose && lataxis) for (i=0; i<nlat; i++) _printLine_("  lataxis [" << i << "]=" << lataxis[i]);
 	options->Get(&longaxis,&nlong,"longaxis");
-	if (verbose && longaxis) for (i=0; i<nlong; i++) printf("  longaxis[%d]=%g\n",i,longaxis[i]);
+	if (verbose && longaxis) for (i=0; i<nlong; i++) _printLine_("  longaxis[" << i << "]=" << longaxis[i]);
 	options->Get(&pimages,&nimages,"images");
-	if (verbose && pimages) for (i=0; i<nimages; i++) printf("  pimages[%d]=\"%s\"\n",i,pimages[i]);
+	if (verbose && pimages) for (i=0; i<nimages; i++) _printLine_("  pimages[" << i << "]=\"" << pimages[i] << "\"");
 	options->Get(&dzip,"zip",0.);
-	if (verbose) printf("  dzip=%g\n",dzip);
+	if (verbose) _printLine_("  dzip=" << dzip);
 
 	/*some checks*/
-	if (nlat !=2) _error_("Latitudinal axes \"lataxis\" require two double values, not %d.",nlat);
-	if (nlong!=2) _error_("Longitudinal axes \"longaxis\" require two double values, not %d.",nlong);
-	if (!nimages) _error_("No image files provided.");
+	if (nlat !=2) _error2_("Latitudinal axes \"lataxis\" require two double values, not " << nlat << ".");
+	if (nlong!=2) _error2_("Longitudinal axes \"longaxis\" require two double values, not " << nlong << ".");
+	if (!nimages) _error2_("No image files provided.");
 
 	if ((int)dzip){
@@ -63,12 +63,12 @@
 	if(!strlen(filkml)) strcpy(filkml,"stdout");
 
-	if(verbose) printf("Opening kml overlay file \"%s\".\n",filkml);
+	if(verbose) _printLine_("Opening kml overlay file \"" << filkml << "\".");
 	fid=fopen(filkml,"w");
 
 	/* Run core computations: */
-	if (verbose) printf("Calling core:\n");
+	if (verbose) _printLine_("Calling core:");
 	KMLOverlayx(&ierror,lataxis,longaxis,nimages,pimages,fid);
 
-	if (verbose) printf("Closing file \"%s\".\n",filkml);
+	if (verbose) _printLine_("Closing file \"" << filkml << "\".");
 	fclose(fid);
 
@@ -87,8 +87,8 @@
 				strcat(czip,pimages[i]);
 			}
-		if (verbose) printf("Zipping file \"%s\".\n",filkmz);
-		if (verbose) printf("%s\n",czip);
+		if (verbose) _printLine_("Zipping file \"" << filkmz << "\".");
+		if (verbose) _printLine_(czip);
 
-		if (mexEvalString(czip)) _error_("Error zipping file \"%s\".",filkmz);
+		if (mexEvalString(czip)) _error2_("Error zipping file \"" << filkmz << "\".");
 		xfree((void**)&czip);
 		xfree((void**)&filkmz);
@@ -113,22 +113,22 @@
 
 void KMLOverlayUsage(void){
-	_printf_(true,"KMLOverlay - KML file overlay module:\n");
-	_printf_(true,"\n");
-	_printf_(true,"   This module reads a list of image files and writes a KML or KMZ overlay file.\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      ierror=KMLOverlay(kmlfile,'param name',param,...);\n");
-	_printf_(true,"\n");
-	_printf_(true,"      kmlfile     KML or KMZ file name (string)\n");
-	_printf_(true,"\n");
-	_printf_(true,"      lataxis     latitude axis (double vector [south north], required)\n");
-	_printf_(true,"      longaxis    longitude axis (double vector [west east], required)\n");
-	_printf_(true,"      images      relative or http image file names (string or array of strings or cell array of strings, required)\n");
-	_printf_(true,"      zip         flag to zip the doc.kml and image files into kmzfile (double, non-zero for kmz)\n");
-	_printf_(true,"\n");
-	_printf_(true,"      ierror     error flag (double, non-zero for error)\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Example:\n");
-	_printf_(true,"      KMLOverlay(kmlfile,'lataxis',[south north],'longaxis',[west east],'images',{'file1.png','http://issm/file2.png'},'zip',1);\n");
-	_printf_(true,"\n");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/Kml2Exp/Kml2Exp.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Kml2Exp/Kml2Exp.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/Kml2Exp/Kml2Exp.cpp	(revision 12878)
@@ -22,8 +22,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		Kml2ExpUsage(); _error_("Kml2Exp usage error");
+		Kml2ExpUsage(); _error2_("Kml2Exp usage error");
 	}
 	if (nrhs < NRHS) {
-		Kml2ExpUsage(); _error_("Kml2Exp usage error");
+		Kml2ExpUsage(); _error2_("Kml2Exp usage error");
 	}
 
@@ -37,13 +37,13 @@
 	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
 		options->Get(&cm,"central_meridian");
-		if (verbose) printf("  cm=%g\n",cm);
+		if (verbose) _printLine_("  cm=" << cm);
 		options->Get(&sp,"standard_parallel");
-		if (verbose) printf("  sp=%g\n",sp);
+		if (verbose) _printLine_("  sp=" << sp);
 	}
 
 	/*some checks*/
-	if (sgn !=+1 && sgn!= -1) _error_("Hemisphere sgn=%d must be +1 (north) or -1 (south).",sgn);
-	if (fabs(cm)      > 180.) _error_("Central meridian cm=%g must be between -180 (west) and +180 (east) degrees.",cm);
-	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=%g must be between 0 and 90 degrees (in specified hemisphere).",sp);
+	if (sgn !=+1 && sgn!= -1) _error2_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
+	if (fabs(cm)      > 180.) _error2_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error2_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
 
 	/* Run core computations: */
@@ -66,25 +66,25 @@
 
 void Kml2ExpUsage(void){
-	_printf_(true,"Kml2Exp - kml to exp file conversion module:\n");
-	_printf_(true,"\n");
-	_printf_(true,"   This module converts a file from kml to exp format.\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      [ret]=Kml2Exp(filexp,filkml,sgn,'param name',param,...);\n");
-	_printf_(true,"\n");
-	_printf_(true,"      filkml      file name of kml file to be read (char)\n");
-	_printf_(true,"      filexp      file name of exp file to be written (char)\n");
-	_printf_(true,"      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
-	_printf_(true,"\n");
-	_printf_(true,"      central_meridian     central meridian (double, optional, but must specify with sp)\n");
-	_printf_(true,"      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
-	_printf_(true,"\n");
-	_printf_(true,"      ret         return code (non-zero for warning)\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Examples:\n");
-	_printf_(true,"      [ret]=Kml2Exp('file.kml','file.exp', 1);\n");
-	_printf_(true,"      [ret]=Kml2Exp('file.kml','file.exp', 1,'central_meridian',45,'standard_parallel',70);\n");
-	_printf_(true,"      [ret]=Kml2Exp('file.kml','file.exp',-1,'central_meridian', 0,'standard_parallel',71);\n");
-	_printf_(true,"\n");
+	_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_("");
 }
 
Index: /issm/branches/trunk-jpl-damage/src/modules/Kriging/Kriging.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Kriging/Kriging.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/Kriging/Kriging.cpp	(revision 12878)
@@ -22,13 +22,13 @@
 	/*checks on arguments on the matlab side: */
 	if (nrhs<NRHS || nlhs>NLHS){
-		KrigingUsage(); _error_("Kriging usage error");
+		KrigingUsage(); _error2_("Kriging usage error");
 	}
 
 	/*Fetch inputs: */
 	FetchData(&x,&n_obs,X);
-	FetchData(&y,&N,Y);                       if(n_obs!=N) _error_("x and y should have the same size");
-	FetchData(&observations,&N,OBSERVATIONS); if(n_obs!=N) _error_("x and observations should have the same size");
+	FetchData(&y,&N,Y);                       if(n_obs!=N) _error2_("x and y should have the same size");
+	FetchData(&observations,&N,OBSERVATIONS); if(n_obs!=N) _error2_("x and observations should have the same size");
 	FetchData(&x_interp,&M_interp,&N_interp,XINTERP);
-	FetchData(&y_interp,&M,&N,YINTERP);       if(N!=N_interp || M!=M_interp) _error_("x_interp and y_interp should have the same size");
+	FetchData(&y_interp,&M,&N,YINTERP);       if(N!=N_interp || M!=M_interp) _error2_("x_interp and y_interp should have the same size");
 	FetchData(&options,NRHS,nrhs,prhs);
 
@@ -54,6 +54,20 @@
 
 void KrigingUsage(void){
-	_printf_(true,"\n");
-	_printf_(true,"   usage: predictions=%s(x,y,observations,x_interp,y_interp);\n",__FUNCT__);
-	_printf_(true,"\n");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/Ll2xy/Ll2xy.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Ll2xy/Ll2xy.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/Ll2xy/Ll2xy.cpp	(revision 12878)
@@ -25,8 +25,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		Ll2xyUsage(); _error_("Ll2xy usage error");
+		Ll2xyUsage(); _error2_("Ll2xy usage error");
 	}
 	if (nrhs < NRHS) {
-		Ll2xyUsage(); _error_("Ll2xy usage error");
+		Ll2xyUsage(); _error2_("Ll2xy usage error");
 	}
 
@@ -40,16 +40,16 @@
 	if(options->GetOption("central_meridian") || options->GetOption("standard_parallel")){
 		options->Get(&cm,"central_meridian");
-		if (verbose) printf("  cm=%g\n",cm);
+		if (verbose) _printLine_("  cm=" << cm);
 		options->Get(&sp,"standard_parallel");
-		if (verbose) printf("  sp=%g\n",sp);
+		if (verbose) _printLine_("  sp=" << sp);
 	}
 
 	/*some checks*/
-	if (verbose) printf("Checking inputs:\n");
-	if (nlat != nlon) _error_("Must have same number of lat[%d] and lon[%d] coordinates.",nlat,nlon);
+	if (verbose) _printLine_("Checking inputs:");
+	if (nlat != nlon){_error2_("Must have same number of lat[" << nlat << "] and lon[" << nlon << "] coordinates.");}
 	else                ncoord=nlat;
-	if (sgn != +1 && sgn != -1) _error_("Hemisphere sgn=%d must be +1 (north) or -1 (south).",sgn);
-	if (fabs(cm)      > 180.) _error_("Central meridian cm=%g must be between -180 (west) and +180 (east) degrees.",cm);
-	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=%g must be between 0 and 90 degrees (in specified hemisphere).",sp);
+	if (sgn != +1 && sgn != -1) _error2_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
+	if (fabs(cm)      > 180.) _error2_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error2_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
 
 	x=(double*)mxMalloc(ncoord*sizeof(double));
@@ -74,25 +74,25 @@
 
 void Ll2xyUsage(void){
-	_printf_(true,"Ll2xy - lat/long to x/y coordinate transformation module:\n");
-	_printf_(true,"\n");
-	_printf_(true,"   This module transforms lat/long to x/y coordinates.\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      [x,y]=Ll2xy(lat,lon,sgn,'param name',param,...);\n");
-	_printf_(true,"\n");
-	_printf_(true,"      lat         latitude coordinates (double vector)\n");
-	_printf_(true,"      lon         longitude coordinates (double vector)\n");
-	_printf_(true,"      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
-	_printf_(true,"\n");
-	_printf_(true,"      central_meridian     central meridian (double, optional, but must specify with sp)\n");
-	_printf_(true,"      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
-	_printf_(true,"\n");
-	_printf_(true,"      x           x coordinates (double vector)\n");
-	_printf_(true,"      y           y coordinates (double vector)\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Examples:\n");
-	_printf_(true,"      [x,y]=Ll2xy(lat,lon, 1);\n");
-	_printf_(true,"      [x,y]=Ll2xy(lat,lon, 1,'central_meridian',45,'standard_parallel',70);\n");
-	_printf_(true,"      [x,y]=Ll2xy(lat,lon,-1,'central_meridian', 0,'standard_parallel',71);\n");
-	_printf_(true,"\n");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/MeshPartition/MeshPartition.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/MeshPartition/MeshPartition.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/MeshPartition/MeshPartition.cpp	(revision 12878)
@@ -96,9 +96,9 @@
 
 void MeshPartitionUsage(void){
-	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");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/MeshProfileIntersection/MeshProfileIntersection.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 12878)
@@ -54,5 +54,5 @@
 	//index
 	FetchData(&double_index,&nel,&dummy,INDEX);
-	if(dummy!=3 && dummy!=6)_error_(" element triangulation should be of 3 or 6 column width!");
+	if(dummy!=3 && dummy!=6)_error2_("element triangulation should be of 3 or 6 column width!");
 	index=(int*)xmalloc(nel*3*sizeof(int));
 	for(i=0;i<nel;i++){
@@ -81,9 +81,9 @@
 	/* Debugging of contours :{{{1*/
 	/*for(i=0;i<numcontours;i++){
-		printf("\nContour echo: contour number  %i / %i\n",i+1,numcontours);
+		_printLine_("\nContour echo: contour number  " << i+1 << " / " << numcontours);
 		contouri=*(contours+i);
-		printf("   Number of vertices %i\n",contouri->nods);
+		_printLine_("   Number of vertices " << contouri->nods);
 		for (j=0;j<contouri->nods;j++){
-			printf("   %lf %lf\n",*(contouri->x+j),*(contouri->y+j));
+			_printLine_("   " << *(contouri->x+j) << "f " << *(contouri->y+j) << "f");
 		}
 	}*/
@@ -102,13 +102,13 @@
 
 void MeshProfileIntersectionUsage(void){
-	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 extremitis 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");
+	_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 extremitis 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.");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/NodeConnectivity/NodeConnectivity.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/NodeConnectivity/NodeConnectivity.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/NodeConnectivity/NodeConnectivity.cpp	(revision 12878)
@@ -37,6 +37,6 @@
 
 void NodeConnectivityUsage(void) {
-	_printf_(true,"\n");
-	_printf_(true,"   usage: connectivity = %s(elements, numnodes);\n",__FUNCT__);
-	_printf_(true,"\n");
+	_pprintLine_("");
+	_pprintLine_("   usage: connectivity = " << __FUNCT__ << "(elements, numnodes);");
+	_pprintLine_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp	(revision 12878)
@@ -42,11 +42,11 @@
 
 void PointCloudFindNeighborsUsage(void){
-	printf("   usage:\n");
-	printf("   [flags]=PointCloudFindNeighbors(x,y,mindistance,multithread);\n\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");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp	(revision 12878)
@@ -42,6 +42,6 @@
 
 void PropagateFlagsFromConnectivityUsage(void) {
-	printf("\n");
-	printf("   usage: [pool] = %s(connectivity,pool,index,flags);\n",__FUNCT__);
-	printf("\n");
+	_printLine_("");
+	_printLine_("   usage: [pool] = " << __FUNCT__ << "(connectivity,pool,index,flags);");;
+	_printLine_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/Scotch/Scotch.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Scotch/Scotch.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/Scotch/Scotch.cpp	(revision 12878)
@@ -25,5 +25,5 @@
 
 #ifndef _HAVE_SCOTCH_ //only works if scotch library has been compiled in.
-	_error_(" Scotch not available! Cannot carry out Scotch partitioning!");
+	_error2_("Scotch not available! Cannot carry out Scotch partitioning!");
 	#else
 
Index: /issm/branches/trunk-jpl-damage/src/modules/Shp2Kml/Shp2Kml.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Shp2Kml/Shp2Kml.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/Shp2Kml/Shp2Kml.cpp	(revision 12878)
@@ -25,5 +25,5 @@
 
 	#ifndef _HAVE_SHAPELIB_ //only works if shapelib library has been compiled in.
-	_error_(" Shapelib not available! Cannot carry out shp file translation!");
+	_error2_("Shapelib not available! Cannot carry out shp file translation!");
 	#endif
 
@@ -33,8 +33,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		Shp2KmlUsage(); _error_("Shp2Kml usage error");
+		Shp2KmlUsage(); _error2_("Shp2Kml usage error");
 	}
 	if (nrhs < NRHS) {
-		Shp2KmlUsage(); _error_("Shp2Kml usage error");
+		Shp2KmlUsage(); _error2_("Shp2Kml usage error");
 	}
 
@@ -48,13 +48,13 @@
 	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
 		options->Get(&cm,"central_meridian");
-		if (verbose) printf("  cm=%g\n",cm);
+		if (verbose) _printLine_("  cm=" << cm);
 		options->Get(&sp,"standard_parallel");
-		if (verbose) printf("  sp=%g\n",sp);
+		if (verbose) _printLine_("  sp=" << sp);
 	}
 
 	/*some checks*/
-	if (sgn < -1 || sgn > +1) _error_("Hemisphere sgn=%d must be +1 (north), -1 (south), or 0 (no translation).",sgn);
-	if (fabs(cm)      > 180.) _error_("Central meridian cm=%g must be between -180 (west) and +180 (east) degrees.",cm);
-	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=%g must be between 0 and 90 degrees (in specified hemisphere).",sp);
+	if (sgn < -1 || sgn > +1) _error2_("Hemisphere sgn=" << sgn << " must be +1 (north), -1 (south), or 0 (no translation).");
+	if (fabs(cm)      > 180.) _error2_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error2_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
 
 	/* Run core computations: */
@@ -77,24 +77,24 @@
 
 void Shp2KmlUsage(void){
-	_printf_(true,"Shp2Kml - shp to kml file conversion module:\n");
-	_printf_(true,"\n");
-	_printf_(true,"   This module converts a file from shp to kml format.\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      [ret]=Shp2Kml(filshp,filkml,sgn,'param name',param,...);\n");
-	_printf_(true,"\n");
-	_printf_(true,"      filshp      file name of shp file to be read (char, extension optional)\n");
-	_printf_(true,"      filkml      file name of kml file to be written (char)\n");
-	_printf_(true,"      sgn         sign for hemisphere (double, +1 (north); -1 (south); or 0 (no translation))\n");
-	_printf_(true,"\n");
-	_printf_(true,"      central_meridian     central meridian (double, optional, but must specify with sp)\n");
-	_printf_(true,"      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
-	_printf_(true,"\n");
-	_printf_(true,"      ret         return code (non-zero for warning)\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Examples:\n");
-	_printf_(true,"      [ret]=Shp2Kml('file.shp','file.kml', 0);\n");
-	_printf_(true,"      [ret]=Shp2Kml('file.shp','file.kml', 1,'central_meridian',45,'standard_parallel',70);\n");
-	_printf_(true,"      [ret]=Shp2Kml('file.shp','file.kml',-1,'central_meridian', 0,'standard_parallel',71);\n");
-	_printf_(true,"\n");
+	_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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/StringToEnum/StringToEnum.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/StringToEnum/StringToEnum.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/StringToEnum/StringToEnum.cpp	(revision 12878)
@@ -12,5 +12,5 @@
 	/*checks on arguments on the matlab side: */
 	if(nrhs!=NRHS){
-		StringToEnumUsage(); _error_(" usage. See above");
+		StringToEnumUsage(); _error2_("usage. See above");
 	}
 
@@ -27,6 +27,6 @@
 void StringToEnumUsage(void)
 {
-	_printf_(true,"\n");
-	_printf_(true,"   usage: %senum = StringToEnum(string);\n",__FUNCT__);
-	_printf_(true,"\n");
+	_pprintLine_("");
+	_pprintLine_("   usage: " << __FUNCT__ << "enum = StringToEnum(string);");
+	_pprintLine_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/TriMesh/TriMesh.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/TriMesh/TriMesh.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/TriMesh/TriMesh.cpp	(revision 12878)
@@ -51,9 +51,9 @@
 	delete domain;
 	delete rifts;
-	xdelete_module(&index);
-	xdelete_module(&x);
-	xdelete_module(&y);
-	xdelete_module(&segments);
-	xdelete_module(&segmentmarkerlist);
+	delete index;
+	delete x;
+	delete y;
+	delete segments;
+	delete segmentmarkerlist;
 
 	/*end module: */
@@ -63,11 +63,11 @@
 void TriMeshUsage(void) //{{{1
 {
-	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");
+	_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_("");
 }
 //}}}
Index: /issm/branches/trunk-jpl-damage/src/modules/TriMeshProcessRifts/TriMeshProcessRifts.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 12878)
@@ -66,6 +66,5 @@
 		mexPrintf("   %s format error.\n", __FUNCT__);
 		TriMeshProcessRiftsUsage();
-		printf("   ");
-		mexErrMsgTxt(" ");
+		_error_("bad usage");
 	}
 
@@ -82,6 +81,5 @@
 	}
 	else{
-		printf("%s%s\n",__FUNCT__," error message: first argument should be the element list!");
-		mexErrMsgTxt(" ");
+		_error_("first argument should be the element list");
 	}
 
@@ -96,6 +94,5 @@
 	}
 	else{
-		printf("%s%s\n",__FUNCT__," error message: second argument should be the x corrdinate list!");
-		mexErrMsgTxt(" ");
+		_error_("second argument should be the x corrdinate list");
 	}
 
@@ -109,6 +106,5 @@
 	}
 	else{
-		printf("%s%s\n",__FUNCT__," error message: third argument should be the y corrdinate list!");
-		mexErrMsgTxt(" ");
+		_error_("third argument should be the y corrdinate list");
 	}	
 
@@ -125,6 +121,5 @@
 	}
 	else{
-		printf("%s%s\n",__FUNCT__," error message: fourth argument should be the segments list!");
-		mexErrMsgTxt(" ");
+		_error_("fourth argument should be the segments list");
 	}
 
@@ -138,29 +133,6 @@
 	}
 	else{
-		printf("%s%s\n",__FUNCT__," error message: fourth argument should be the segmentmarkers list!");
-		mexErrMsgTxt(" ");
-	}
-
-	/*
-	printf("Index: \n");
-	for (i=0;i<nel;i++){
-		for(j=0;j<3;j++){
-			printf("%lf ",*(index_in+3*i+j));
-		}
-		printf("\n");
-	}
-	printf("x,y: \n");
-	for (i=0;i<nods;i++){
-		printf("%16.16lf %16.16lf\n",x_in[i],y_in[i]);
-	}
-	printf("segments:\n");
-	for (i=0;i<num_seg;i++){
-		for(j=0;j<3;j++){
-			printf("%lf ",*(segments_in+3*i+j));
-		}
-		printf("%lf ",segmentmarkers_in[i]);
-		printf("\n");
-	}
-	*/
+		_error_("fourth argument should be the segmentmarkers list");
+	}
 
 	/*First, do some fixing on the existing mesh: we do not want any element belonging entirely to the segment list (ie: 
@@ -325,7 +297,7 @@
 void TriMeshProcessRiftsUsage(void)
 {
-	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");
+	_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.");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/TriaSearch/TriaSearch.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/TriaSearch/TriaSearch.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/TriaSearch/TriaSearch.cpp	(revision 12878)
@@ -9,5 +9,5 @@
 
 	/*input: */
-	double* index=NULL;
+	int*    index=NULL;
 	int     nel;
 	int     dummy;
@@ -37,8 +37,4 @@
 	FetchData(&y0,&numberofnodes,Y0HANDLE);
 
-	/* Echo: {{{1*/
-	//printf("(x0,y0)=(%g,%g)\n",x0,y0);
-	/*}}}*/
-
 	/* Run core computations: */
 	TriaSearchx(&tria,index,nel,x,y,nods,x0,y0,numberofnodes);
@@ -54,13 +50,12 @@
 }
 
-void TriaSearchUsage(void)
-{
-	_printf_(true,"TriaSearch- find triangle holding a point (x0,y0) in a mesh\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"         tria=TriaSearch(index,x,y,x0,y0);\n");
-	_printf_(true,"      index,x,y: mesh triangulatrion\n");
-	_printf_(true,"      x0,y0: coordinates of the point for which we are trying to find a triangle\n");
-	_printf_(true,"      x0,y0 can be an array of points\n");
-	_printf_(true,"\n");
+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_("");
 }
Index: /issm/branches/trunk-jpl-damage/src/modules/Xy2ll/Xy2ll.cpp
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/Xy2ll/Xy2ll.cpp	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/Xy2ll/Xy2ll.cpp	(revision 12878)
@@ -24,8 +24,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		Xy2llUsage(); _error_("Xy2ll usage error");
+		Xy2llUsage(); _error2_("Xy2ll usage error");
 	}
 	if (nrhs < NRHS) {
-		Xy2llUsage(); _error_("Xy2ll usage error");
+		Xy2llUsage(); _error2_("Xy2ll usage error");
 	}
 
@@ -39,15 +39,15 @@
 	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
 		options->Get(&cm,"central_meridian");
-		if (verbose) printf("  cm=%g\n",cm);
+		if (verbose) _printLine_("  cm=" << cm);
 		options->Get(&sp,"standard_parallel");
-		if (verbose) printf("  sp=%g\n",sp);
+		if (verbose) _printLine_("  sp=" << sp);
 	}
 
 	/*some checks*/
-	if   (nx != ny) _error_("Must have same number of x[%d] and y[%d] coordinates.",nx,ny);
+	if   (nx != ny){_error2_("Must have same number of x[" << nx << "] and y[" << ny << "] coordinates.");}
 	else            ncoord=nx;
-	if (sgn != +1 && sgn != -1) _error_("Hemisphere sgn=%d must be +1 (north) or -1 (south).",sgn);
-	if (fabs(cm)      > 180.) _error_("Central meridian cm=%g must be between -180 (west) and +180 (east) degrees.",cm);
-	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=%g must be between 0 and 90 degrees (in specified hemisphere).",sp);
+	if (sgn != +1 && sgn != -1) _error2_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
+	if (fabs(cm)      > 180.) _error2_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error2_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
 
 	lat=(double*)mxMalloc(ncoord*sizeof(double));
@@ -55,5 +55,5 @@
 
 	/* Run core computations: */
-	if (verbose) printf("Calling core:\n");
+	if (verbose) _printLine_("Calling core:");
 	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
 		iret=Xy2llx(lat,lon,x,y,ncoord,sgn,cm,sp);
@@ -73,26 +73,26 @@
 
 void Xy2llUsage(void){
-	_printf_(true,"Xy2ll - x/y to lat/long coordinate transformation module:\n");
-	_printf_(true,"\n");
-	_printf_(true,"   This module transforms x/y to lat/long coordinates.\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Usage:\n");
-	_printf_(true,"      [lat,lon]=Xy2ll(x,y,sgn,'param name',param,...);\n");
-	_printf_(true,"\n");
-	_printf_(true,"      x           x coordinates (double vector)\n");
-	_printf_(true,"      y           y coordinates (double vector)\n");
-	_printf_(true,"      sgn         sign for hemisphere (double, +1 (north) or -1 (south))\n");
-	_printf_(true,"\n");
-	_printf_(true,"      central_meridian     central meridian (double, optional, but must specify with sp)\n");
-	_printf_(true,"      standard_parallel    standard parallel (double, optional, but must specify with cm)\n");
-	_printf_(true,"\n");
-	_printf_(true,"      lat         latitude coordinates (double vector)\n");
-	_printf_(true,"      lon         longitude coordinates (double vector)\n");
-	_printf_(true,"\n");
-	_printf_(true,"   Examples:\n");
-	_printf_(true,"      [lat,lon]=Xy2ll(x,y, 1);\n");
-	_printf_(true,"      [lat,lon]=Xy2ll(x,y, 1,'central_meridian',45,'standard_parallel',70);\n");
-	_printf_(true,"      [lat,lon]=Xy2ll(x,y,-1,'central_meridian', 0,'standard_parallel',71);\n");
-	_printf_(true,"\n");
+	_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_("");
 }
 
Index: /issm/branches/trunk-jpl-damage/src/modules/matlab/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/matlab/Makefile.am	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/matlab/Makefile.am	(revision 12878)
@@ -1,3 +1,3 @@
-INCLUDES = @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
+INCLUDES = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
 EXEEXT=$(MATLABWRAPPEREXT)
 #Bin programs {{{1
@@ -41,5 +41,5 @@
 #}}}
 #Flags and libraries {{{1
-LDADD = ../../c/libISSMCore.a ../../c/libISSMModules.a $(TRIANGLELIB) $(PETSCLIB) $(FLIBS) $(PLAPACKLIB) $(MUMPSLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(SHAPELIBLIB) $(GSLLIB)
+LDADD = ../../c/libISSMCore.a ../../c/libISSMModules.a $(TRIANGLELIB) $(PETSCLIB) $(FLIBS) $(PLAPACKLIB) $(SPOOLESLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(SHAPELIBLIB) $(GSLLIB)
 
 #Triangle library
@@ -50,6 +50,9 @@
 AM_CXXFLAGS +=  -D_HAVE_MATLAB_MODULES_ -D_GNU_SOURCE -fPIC -fno-omit-frame-pointer -pthread 
 LDADD       += $(MEXLIB) ../../c/libISSMMatlab.a 
-
-LDADD       += ../../c/libISSMCore.a ../../c/libISSMModules.a 
+LDADD       += ../../c/libISSMCore.a 
+if CIRCULAR_DEPENDENCIES
+LDADD       += $(TRIANGLELIB) $(PETSCLIB) $(FLIBS) $(PLAPACKLIB) $(SPOOLESLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(SHAPELIBLIB) $(GSLLIB)
+endif
+LDADD       += ../../c/libISSMModules.a
 
 #Optimization flags:
Index: /issm/branches/trunk-jpl-damage/src/modules/python/Makefile.am
===================================================================
--- /issm/branches/trunk-jpl-damage/src/modules/python/Makefile.am	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/src/modules/python/Makefile.am	(revision 12878)
@@ -1,3 +1,3 @@
-INCLUDES = @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
+INCLUDES = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
 EXEEXT=$(PYTHONWRAPPEREXT)
 #Bin programs {{{1
@@ -17,5 +17,5 @@
 #Python part
 AM_LDFLAGS   = $(PYTHONLINK)
-AM_CXXFLAGS +=  -D_HAVE_PYTHON_MODULES_ 
+AM_CXXFLAGS +=  -D_HAVE_PYTHON_MODULES_  -fPIC
 if PYTHON3
 AM_CXXFLAGS +=  -DNPY_NO_DEPRECATED_API 
Index: sm/branches/trunk-jpl-damage/src/py/model/petscversion.2.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/py/model/petscversion.2.py	(revision 12877)
+++ 	(revision )
@@ -1,39 +1,0 @@
-#PETSCVERSION - recover petsc version number, inside config.h file
-#
-#   Usage:
-#       PETSC_VERSION=petscversion();
-
-#Module imports {{{
-import os
-import sys
-from issmtier import *
-#}}}
-
-def petscversion():
-
-	#default
-	PETSC_VERSION=3;
-	
-	configfile=issmtier() + "/bin/config.h" #should find it in the install target
-	
-	if not os.path.isfile(configfile):
-		raise RuntimeError("%s%s%s"%("File ",configfile," not found. ISSM has not been configured yet!"))
-
-	#go through the file, and recover the line we want
-	fid=open(configfile,'r');
-
-	tline=fid.readline()
-	while tline:
-
-		if tline=='': 
-			break
-		
-		if tline[0:21]=="#define _PETSC_MAJOR_":
-			PETSC_VERSION=int(tline[22])
-			break
-		
-		tline=fid.readline()
-	
-	fid.close();
-
-	return PETSC_VERSION
Index: sm/branches/trunk-jpl-damage/src/py/utils/OS/ismumps.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/py/utils/OS/ismumps.py	(revision 12877)
+++ 	(revision )
@@ -1,41 +1,0 @@
-#ISMUMPS - figure out if MUMPS package was compiled with ISSM
-#
-#   Usage:
-#       flag=ismumps();
-
-#Module imports {{{
-import os
-import sys
-from issmtier import *
-#}}}
-
-def ismumps():
-
-	configfile=issmtier() + "/bin/config.h" #should find it in the install target
-	
-	if not os.path.isfile(configfile):
-		raise RuntimeError("%s%s%s"%("File ",configfile," not found. ISSM has not been configured yet!"))
-	
-	#%go through the file, and recover the line we want
-	flag=2;
-	fid=open(configfile,'r');
-
-	tline=fid.readline()
-	while tline:
-		
-		if tline=='': 
-			break
-		if tline[0:25]=="/* #undef _HAVE_MUMPS_ */":
-			flag=0;
-			break
-		if tline[0:20]=="#define _HAVE_MUMPS_":
-			flag=1
-			break
-		tline=fid.readline()
-
-	fid.close();
-
-	if flag==2:
-		raise RuntimeError('could not determine whether MUMPS was or was not compiled')
-
-	return flag
Index: sm/branches/trunk-jpl-damage/src/py/utils/Shell/issmtier.py
===================================================================
--- /issm/branches/trunk-jpl-damage/src/py/utils/Shell/issmtier.py	(revision 12877)
+++ 	(revision )
@@ -1,24 +1,0 @@
-
-#ISSMTIER - Get ISSM_TIER environment variable contents.
-#
-#   Usage:
-#      ISSM_TIER=issmtier()
-
-
-#Module imports
-import os
-
-def issmtier():
-
-	if os.name =="posix":
-		ISSM_TIER =os.getenv('ISSM_TIER')
-	else:
-		ISSM_TIER =os.getenv('ISSM_TIER_WIN')
-
-	if(ISSM_TIER[-1]=="/") or (ISSM_TIER[-1]=="\\"):
-		ISSM_TIER = ISSM_TIER[:-2]; #shave off the last '/'
-
-	if ISSM_TIER == "":
-		raise RuntimeError("issmdir error message: ''ISSM_TIER'' environment variable is empty! You should define ISSM_TIER in your .cshrc or .bashrc!")
-		
-	return ISSM_TIER
Index: /issm/branches/trunk-jpl-damage/startup.py
===================================================================
--- /issm/branches/trunk-jpl-damage/startup.py	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/startup.py	(revision 12878)
@@ -22,4 +22,6 @@
 #ISSM path. Go through src/py and load everything we find  that looks like a python file
 for root,dirs,files in os.walk(ISSM_DIR+ '/src/py'):
+	if '.svn' in dirs:
+		dirs.remove('.svn')
 	for file in files:
 		if file.find(".py") != -1:
@@ -31,4 +33,6 @@
 
 for root,dirs,files in os.walk(ISSM_DIR+ '/src/m'):
+	if '.svn' in dirs:
+		dirs.remove('.svn')
 	for file in files:
 		if file.find(".py") != -1:
@@ -64,5 +68,4 @@
 from settings import *
 from solver import *
-from issmtier  import * 
 from ismumps  import * 
 from pairoptions  import * 
@@ -77,6 +80,4 @@
 from stokesoptions import *
 from generic import *
-from none import *
-from none import *
 from hydrology import *
 from miscellaneous import *
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/IdFromString.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/IdFromString.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/IdFromString.m	(revision 12878)
@@ -22,5 +22,5 @@
 %return if no test found
 if isempty(ids_raw),
-	disp(['No test matches ''' string '' ]);
+	disp(['No test matches ''' string '''' ]);
 	return
 end
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/IdFromString.py
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/IdFromString.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/IdFromString.py	(revision 12878)
@@ -0,0 +1,36 @@
+#! /usr/bin/env python
+from IdToName import IdToName
+
+def IdFromString(string):
+	"""
+	IDFROMSTRING - output ids from a given string
+ 
+	    Usage:
+	       ids=IdFromString(string)
+ 
+	    Examples:
+	       ids=IdFromString('Parallel')
+	       ids=IdFromString('79North')
+	"""
+
+	#Check input
+	if not isinstance(string,str):
+		raise TypeError('IdFromString error message: input argument is not a string.')
+
+	#Get the dictionary and scan for matches
+	idnames=IdToName(0)
+	ids=[item[0] for item in idnames.iteritems() if string in item[1]]
+
+	#Return if no test found
+	if not ids:
+		print "No test matches '%s'." % string
+		return ids
+
+	#Display names
+	ids.sort()
+	print "%d tests match '%s':" % (len(ids),string)
+	for id in ids:
+		print "   %d : %s" % (id,idnames[id])
+
+	return ids
+
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/IdToName.py
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/IdToName.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/IdToName.py	(revision 12878)
@@ -0,0 +1,193 @@
+#! /usr/bin/env python
+
+def IdToName(id):
+	"""
+	IDTONAME- return name of test
+ 
+	    Usage:
+	       name=IdToName(id)
+	"""
+
+	idname={
+		101 : 'SquareShelfConstrainedDiagM2d',
+		102 : 'SquareShelfConstrainedDiagM3d',
+		103 : 'SquareShelfConstrainedDiagP3d',
+		104 : 'SquareShelfConstrainedDiagS3d',
+		105 : 'SquareShelfConstrainedProg2d',
+		106 : 'SquareShelfConstrainedProg2dDG',
+		107 : 'SquareShelfConstrainedProg3d',
+		108 : 'SquareShelfConstrainedTherStea',
+		109 : 'SquareShelfConstrainedTherTran',
+		110 : 'SquareShelfConstrainedTranM2d',
+		111 : 'SquareShelfConstrainedTranP3d',
+		112 : 'SquareShelfConstrainedSurfSlop2d',
+		113 : 'SquareShelfConstrainedSurfSlope3d',
+		114 : 'SquareShelfConstrainedBedSlop2d',
+		115 : 'SquareShelfConstrainedBedSlop3d',
+		116 : 'SquareShelfConstrainedBalThic2d',
+		117 : 'SquareShelfConstrainedBalThic3d',
+		118 : 'SquareShelfConstrainedBalThic2dDG',
+		119 : 'SquareBamgMesh',
+		120 : 'SquareShelfConstrainedEnthalpyStea',
+		121 : 'SquareShelfConstrainedEnthalpyTran',
+		122 : 'SquareShelfConstrainedTransP3dEnth',
+		201 : 'SquareShelfDiagM2d',
+		202 : 'SquareShelfDiagM3d',
+		203 : 'SquareShelfDiagP3d',
+		204 : 'SquareShelfDiagS3d',
+		205 : 'SquareShelfDiagMP3dPenalties',
+		206 : 'SquareShelfTherStea',
+		207 : 'SquareShelfTherTran',
+		208 : 'SquareShelfTranM2d',
+		209 : 'SquareShelfTranM3d',
+		210 : 'SquareShelfTranP3d',
+		211 : 'SquareShelfTranS3d',
+		212 : 'SquareShelfCMBM2d',
+		213 : 'SquareShelfCMBM3d',
+		214 : 'SquareShelfCMBP3d',
+		215 : 'SquareShelfCMBS3d',
+		216 : 'SquareShelfDiagM2dRift',
+		217 : 'SquareShelfConstrained',
+		218 : 'SquareShelfConstrainedDakotaB',
+		219 : 'SquareShelfDiagMP3dTiling',
+		220 : 'SquareShelfDiagPS3dTiling',
+		221 : 'SquareShelfDiagMS3dTiling',
+		222 : 'SquareShelfDiagM2dTransientIncrHydro',
+		223 : 'SquareShelfDiagM2dTransientIncrNonHydro',
+		224 : 'SquareShelfDiagP3dTransientIncrHydro',
+		225 : 'SquareShelfDiagP3dTransientIncrNonHydro',
+		226 : 'SquareShelfTranCflM2d',
+		227 : 'SquareShelfTranCflP3d',
+		228 : 'SquareShelfTranForceNeg2d',
+		229 : 'SquareShelfTranForcePos2d',
+		230 : 'SquareShelfTranForceNeg3d',
+		231 : 'SquareShelfTranForcePos3d',
+		232 : 'SquareShelfTherTranForcTemp',
+		233 : 'SquareShelfTranP3dForcTemp',
+		234 : 'SquareShelfTranForceNeg2dDakotaSamp',
+   	235 : 'SquareShelfTranForceNeg2dDakotaLocal',
+		301 : 'SquareSheetConstrainedDiagM2d',
+		302 : 'SquareSheetConstrainedDiagH2d',
+		303 : 'SquareSheetConstrainedDiagHM2d',
+		304 : 'SquareSheetConstrainedDiagM3d',
+		305 : 'SquareSheetConstrainedDiagH3d',
+		306 : 'SquareSheetConstrainedDiagHM3d',
+		307 : 'SquareSheetConstrainedDiagP3d',
+		308 : 'SquareSheetConstrainedDiagS3d',
+		309 : 'SquareSheetConstrainedProg2d',
+		310 : 'SquareSheetConstrainedProg2dDG',
+		311 : 'SquareSheetConstrainedProg3d',
+		312 : 'SquareSheetConstrainedTherStea',
+		313 : 'SquareSheetConstrainedTherTran',
+		314 : 'SquareSheetConstrainedTranH2d',
+		315 : 'SquareSheetConstrainedTranH3d',
+		316 : 'SquareSheetConstrainedTranM2d',
+		317 : 'SquareSheetConstrainedTranP3d',
+		318 : 'SquareSheetConstrainedSteaH3d',
+		319 : 'SquareSheetConstrainedCMDragM2d',
+		320 : 'SquareSheetConstrainedCMDragM3d',
+		321 : 'SquareSheetConstrainedCMDragP3d',
+		322 : 'SquareSheetConstrainedCMDragS3d',
+		323 : 'SquareSheetConstrainedTranCflM2d',
+		324 : 'SquareSheetConstrainedTranCflH3d',
+		325 : 'SquareSheetConstrainedEnthalpyStea',
+		326 : 'SquareSheetConstrainedEnthalpyTran',
+		327 : 'SquareSheetConstrainedTransP3dEnth',
+		328 : 'SquareSheetConstrainedSmbGradients2d',
+		329 : 'SquareSheetConstrainedSmbGradients3d',
+		401 : 'SquareSheetShelfDiagM2d',
+		402 : 'SquareSheetShelfDiagM3d',
+		403 : 'SquareSheetShelfDiagP3d',
+		404 : 'SquareSheetShelfDiagS3d',
+		405 : 'SquareSheetShelfDiagMP3dPenalties',
+		406 : 'SquareSheetShelfTherStea',
+		407 : 'SquareSheetShelfTherTran',
+		408 : 'SquareSheetShelfTranM2d',
+		409 : 'SquareSheetShelfTranMP3dPenalties',
+		410 : 'SquareSheetShelfSteaM3d',
+		411 : 'SquareSheetShelfSteaP3d',
+		412 : 'SquareSheetShelfDiadM3dDakota',
+		413 : 'SquareSheetShelfDiadM3dDakotaPart',
+		414 : 'SquareSheetShelfDiadM3dDakotaMassFlux',
+		415 : 'SquareSheetShelfCMDragSteaM3d',
+		416 : 'SquareSheetShelfCMDragSteaP3d',
+		417 : 'SquareSheetShelfDiadM3dDakotaSamp',
+		418 : 'SquareSheetShelfDiadM3dDakotaAreaAverage',
+		419 : 'SquareSheetShelfDiagMP3dTiling',
+		420 : 'SquareSheetShelfDakotaScaledResponse',
+		421 : 'SquareSheetShelfDiagPS3dTiling',
+		422 : 'SquareSheetShelfDiagMS3dTiling',
+		423 : 'RoundSheetShelfGLMigrationM2d',
+		424 : 'SquareSheetShelfGroundingLine2dAgressice',
+		425 : 'SquareSheetShelfGroundingLine2dSoft',
+		426 : 'SquareSheetShelfGroundingLine3dAgressice',
+		427 : 'SquareSheetShelfGroundingLine3dSoft',
+		428 : 'SquareSheetShelfDiagM2dNewton',
+		439 : 'SquareSheetShelfDiagP3dNewton',
+		430 : 'SquareSheetShelfDiagS3dNewton',
+		431 : 'SquareSheetShelfSteaEnthalpyM3d',
+		432 : 'SquareSheetShelfSteaEnthalpyP3d',
+		501 : 'PigDiagM2d',
+		502 : 'PigDiagP3d',
+		503 : 'PigDiagS3d',
+		504 : 'PigTranM2d',
+		505 : 'PigTranM3d',
+		506 : 'PigTranP3d',
+		507 : 'PigTranS3d',
+		508 : 'PigSteaM3d',
+		509 : 'PigSteaP3d',
+		510 : 'PigSteaS3d',
+		511 : 'PigCMBS3d',
+		512 : 'PigCMDragP3d',
+		513 : 'PigCMDragSteaM3d',
+		514 : 'PigBamgMesh',
+		515 : 'PigTherTranSUPG',
+		516 : 'PigTherSteaSUPG',
+		601 : '79NorthProg2d',
+		602 : '79NorthProg2dDG',
+		603 : '79NorthProg3d',
+		604 : '79NorthSurfSlop2d',
+		605 : '79NorthSurfSlop3d',
+		606 : '79NorthBedSlop2d',
+		607 : '79NorthBedSlop3d',
+		608 : '79NorthBalThic2d',
+		609 : '79NorthBalThic2dDG',
+		610 : '79NorthBalThic3d',
+		611 : '79NorthCMBalThic2dCG',
+		612 : '79NorthCMBalThic2dDG',
+		613 : '79NorthCMBalThicVxVy',
+		1101 : 'ISMIPAPattyn',
+		1102 : 'ISMIPAStokes',
+		1103 : 'ISMIPBPattyn',
+		1104 : 'ISMIPBStokes',
+		1105 : 'ISMIPCPattyn',
+		1106 : 'ISMIPCStokes',
+		1107 : 'ISMIPDPattyn',
+		1108 : 'ISMIPDStokes',
+		1109 : 'ISMIPE',
+		1110 : 'ISMIPF',
+		1201 : 'EISMINTMassConservation',
+		1202 : 'EISMINTDiag1',
+		1203 : 'EISMINTDiag2',
+		1204 : 'EISMINTTran2',
+		1205 : 'EISMINTRoundIceSheetStaticHutter',
+		1206 : 'EISMINTRoundIceSheetStaticPattyn',
+		1207 : 'EISMINTRoundIceSheetStaticStokes',
+		1208 : 'EISMINTA',
+		1301 : 'ThermalMelting',
+		1302 : 'ThermalAdvection',
+		1303 : 'ThermalConduction',
+		1304 : 'ThermalGeothermalFlux',
+		1401 : 'AdaptiveMeshRefinement1',
+		1402 : 'AdaptiveMeshRefinement2',
+		1501 : 'SquareShelfTranSawTooth2d',
+		1502 : 'SquareShelfTranSawTooth3d',
+		1601 : 'SquareShelfM2dRotation',
+		1602 : 'SquareSheetShelfP3dRotation',
+	}
+
+	if not id == 0:
+		return idname.get(id,'N/A')
+	else:
+		return idname
+
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/dak.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/dak.m	(revision 12877)
+++ 	(revision )
@@ -1,52 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',1);
-
-md.timestepping.time_step=1;
-md.settings.output_frequency=1;
-md.timestepping.final_time=4;
-
-%Set up transient
-smb = ones(md.mesh.numberofvertices,1)*3.6;
-smb=[ smb smb*-1 ];
-
-md.surfaceforcings.mass_balance=smb;
-md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
-md.transient.isthermal=0;
-
-%sigma_on_partition=AreaAverageOntoPartition(md,sigma);
-%sigma_on_grids=sigma_on_partition(md.part+1); %just to check in case
-%md.variables.thickness=normal_uncertain('scaled_Thickness',1,1);
-%md.variables.thickness.stddev=sigma_on_partition;
-
-%Dakota inputs,outputs
-md.qmu.variables.surface_mass_balance=normal_uncertain('scaled_SurfaceforcingsMassBalance',1,0.1);
-md.qmu.responses.IceVolume=response_function('IceVolume',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-
-%%  nond_sampling study
-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');
-
-%%  a variety of parameters
-md.qmu.params.evaluation_concurrency=1;
-md.qmu.params.analysis_driver='';
-md.qmu.params.analysis_components='';
-
-%partitioning
-md.qmu.numberofpartitions=20;
-md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
-md.qmu.partition=md.qmu.partition-1;
-md.qmu.isdakota=1;
-
-md.transient.requested_outputs=IceVolumeEnum();
-
-md.diagnostic.reltol=10^-5; %tighten for qmu analyses
-%md.debug.valgrind=1;
-%md.verbose.solution=true;
-md=solve(md,TransientSolutionEnum,'overwrite','y');
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/runme.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/runme.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/runme.m	(revision 12878)
@@ -49,5 +49,5 @@
 if ~ismember(benchmark,{'all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing'})
 	disp('runme warning: benchmark not supported, defaulting to test ''nightly''')
-	benchmark='nighlty';
+	benchmark='nightly';
 end
 % }}}
@@ -87,5 +87,5 @@
 test_ids=intersect(test_ids,list_ids);
 % }}}
-%GET exculde {{{1
+%GET exclude {{{1
 exclude_ids=getfieldvalue(options,'exclude',[]);
 exclude_ids=[exclude_ids];
@@ -126,5 +126,5 @@
 
 			if ~strcmp(oshostname(),'larsen');
-				error(['Nighlty run archives must be saved on "larsen" (hostname is "' oshostname() '")']);
+				error(['Nightly run archives must be saved on "larsen" (hostname is "' oshostname() '")']);
 			end
 			for k=1:length(field_names),
@@ -135,5 +135,5 @@
 			disp(sprintf(['File ./../Archives/' archive_name ' saved\n']));
 
-			%ELSE: CHECK TEST
+		%ELSE: CHECK TEST
 		else,
 
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/runme.py
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/runme.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/runme.py	(revision 12878)
@@ -0,0 +1,274 @@
+#! /usr/bin/env python
+import os
+import glob
+import socket
+import numpy
+#import h5py
+import netCDF4
+import sys
+
+def runme(id=None,exclude=None,benchmark='nightly',procedure='check',output='none',rank=1,numprocs=1):
+	"""
+	RUNME - test deck for ISSM nightly runs
+ 
+	    In a test deck directory (tests/Vertification/NightlyRun for example)
+	    The following command will launch all the existing tests:
+	    >>> runme()
+	    To run the tests 101 and 102:
+	    >>> runme(id=[101,102])
+	    etc...
+ 
+	    Available options:
+	       'id'            followed by the list of ids requested
+	       'exclude'       ids to be excluded from the test
+	       'benchmark'     '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
+	                       ...
+	       'procedure'     'check' : run the test (default)
+	                       'update': update the archive
+ 
+	    Usage:
+	       md=runme(varargin);
+ 
+	    Examples:
+	       runme()
+	       runme(exclude=101)
+	       md=runme(id=102,procedure='update')
+	"""
+
+	from parallelrange import parallelrange
+	from IdToName import IdToName
+
+	#Get ISSM_DIR variable
+	ISSM_DIR=os.environ['ISSM_DIR']
+	print 'ISSM_DIR =',ISSM_DIR
+
+	#Process options
+	#GET benchmark {{{1
+	if not benchmark.lower() in ['all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing']:
+		print "runme warning: benchmark '%s' not supported, defaulting to test 'nightly'." % benchmark
+		benchmark='nightly'
+	# }}}
+	#GET procedure {{{1
+	if not procedure.lower() in ['check','update']:
+		print "runme warning: procedure '%s' not supported, defaulting to test 'check'." % procedure
+		procedure='check'
+	# }}}
+	#GET output {{{1
+	if not output.lower() in ['nightly','daily','none']:
+		print "runme warning: output '%s' not supported, defaulting to test 'none'." % output
+		output='none'
+	# }}}
+	#GET RANK and NUMPROCS for multithreaded runs {{{1
+	if (numprocs<rank):
+		numprocs=1
+	# }}}
+
+	print 'id =',id
+	print 'exclude =',exclude
+	print 'benchmark =',benchmark
+	print 'procedure =',procedure
+	print 'output =',output
+	print 'rank =',rank
+	print 'numprocs =',numprocs
+
+	#GET ids  {{{1
+	flist=glob.glob('test*.py')    #File name must start with 'test' and must end by '.py' and must be different than 'test.py'
+	list_ids=[int(file[4:-3]) for file in flist if not file == 'test.py']    #Keep test id only (skip 'test' and '.py')
+	print 'list_ids =',list_ids
+
+	i1,i2=parallelrange(rank,numprocs,len(list_ids))    #Get tests for this cpu only
+	list_ids=list_ids[i1:i2+1]
+	print 'list_ids after parallelrange =',list_ids
+
+	if id:
+		if isinstance(id,list):
+			test_ids=id
+		else:
+			test_ids=[id]
+		test_ids=set(test_ids).intersection(set(list_ids))
+	else:
+		test_ids=set(list_ids)
+#	print 'test_ids after list =',test_ids
+	# }}}
+
+	#GET exclude {{{1
+	if exclude:
+		if isinstance(exclude,list):
+			exclude_ids=exclude
+		else:
+			exclude_ids=[exclude]
+		test_ids=test_ids.difference(set(exclude_ids))
+#	print 'test_ids after exclude =',test_ids
+	# }}}
+
+	#Process Ids according to benchmarks {{{1
+	if   benchmark.lower() == 'nightly':
+		test_ids=test_ids.intersection(set(range(1,1000)))
+	elif benchmark.lower() == 'ismip':
+		test_ids=test_ids.intersection(set(range(1101,1200)))
+	elif benchmark.lower() == 'eismint':
+		test_ids=test_ids.intersection(set(range(1201,1300)))
+	elif benchmark.lower() == 'thermal':
+		test_ids=test_ids.intersection(set(range(1301,1400)))
+	elif benchmark.lower() == 'mesh':
+		test_ids=test_ids.intersection(set(range(1401,1500)))
+	elif benchmark.lower() == 'validation':
+		test_ids=test_ids.intersection(set(range(1001,2000)))
+	elif benchmark.lower() == 'tranforcing':
+		test_ids=test_ids.intersection(set(range(1501,1503)))
+#	print 'test_ids after benchmark =',test_ids
+	test_ids=list(test_ids)
+	test_ids.sort()
+	print 'test_ids after sort =',test_ids
+	# }}}
+
+	#Loop over tests and launch sequence
+	root=os.getcwd()
+	for id in test_ids:
+		try:
+
+			#Execute test
+			os.chdir(root)
+			id_string=IdToName(id)
+			execfile('test'+str(id)+'.py',globals())
+
+			#UPDATE ARCHIVE?
+			archive_name='Archive'+str(id)
+			if procedure.lower() == 'update':
+
+				if not socket.gethostname().lower().split('.')[0] == 'larsen':
+#					raise RuntimeError("Nightly run archives must be saved on 'larsen' (hostname is '"+socket.gethostname()+"').")
+					print "Nightly run archives must be saved on 'larsen' (hostname is '"+socket.gethostname()+"')."
+#				f = h5py.File(os.path.join('..','Archives',archive_name+'.hdf5'),'w')
+				f = netCDF4.Dataset(os.path.join('..','Archives',archive_name+'.nc'),'w')
+				for k,fieldname in enumerate(field_names):
+					field=numpy.array(field_values[k],dtype=float)
+#					f.create_dataset(archive_name+'_field'+str(k),data=field)
+					f.createDimension(archive_name+'_field'+str(k)+'_0',numpy.size(field,0))
+					f.createDimension(archive_name+'_field'+str(k)+'_1',numpy.size(field,1))
+					v = f.createVariable(archive_name+'_field'+str(k),'f8',(archive_name+'_field'+str(k)+'_0',archive_name+'_field'+str(k)+'_1'))
+					v[:] = field
+				f.close()
+				print "File '%s' saved.\n" % os.path.join('..','Archives',archive_name+'.nc')
+
+			#ELSE: CHECK TEST
+			else:
+
+				#load archive
+				if os.path.exists(os.path.join('..','Archives',archive_name+'.nc')):
+#					f = h5py.File(os.path.join('..','Archives',archive_name+'.hdf5'),'r')
+					f = netCDF4.Dataset(os.path.join('..','Archives',archive_name+'.nc'),'r')
+				else:
+					raise IOError("Archive file '"+os.path.join('..','Archives',archive_name+'.nc')+"' does not exist.")
+
+				for k,fieldname in enumerate(field_names):
+
+					try:
+						#Get field and tolerance
+						field=numpy.array(field_values[k],dtype=float)
+#						print 'field =',field
+						tolerance=field_tolerances[k]
+#						print 'tolerance =',tolerance
+
+						#compare to archive
+#						if archive_name+'_field'+str(k) in f:
+#							archive=f[archive_name+'_field'+str(k)][...]
+						if archive_name+'_field'+str(k) in f.variables:
+							archive=f.variables[archive_name+'_field'+str(k)][:]
+						else:
+							raise NameError("Field name '"+archive_name+'_field'+str(k)+"' does not exist in archive file.")
+#						print 'archive =',archive
+						error_diff=numpy.amax(numpy.abs(archive-field),axis=1)/ \
+								   (numpy.amax(numpy.abs(archive),axis=1)+sys.float_info.epsilon)
+#						print 'error_diff =',error_diff
+
+						#disp test result
+						if (error_diff>tolerance):
+							print 'ERROR   difference: %-7.2g > %7.2g test id: %i test name: %s field: %s' % \
+								(error_diff,tolerance,id,id_string,fieldname)
+						else:
+							print 'SUCCESS difference: %-7.2g < %7.2g test id: %i test name: %s field: %s' % \
+								(error_diff,tolerance,id,id_string,fieldname)
+
+					except Exception as me2:
+
+						#something went wrong, print failure message:
+						directory=os.getcwd().split('/')    #  not used?
+						message=me2
+						if   output.lower() == 'nightly':
+							fid=open(os.path.join(ISSM_DIR,'nightlylog','matlaberror.log'), 'a')
+							fid.write('%s' % message)
+							fid.write('\n------------------------------------------------------------------\n')
+							fid.close()
+							print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,fieldname)
+						elif output.lower() == 'daily':
+							fid=open(os.path.join(ISSM_DIR,'dailylog','matlaberror.log'), 'a')
+							fid.write('%s' % message)
+							fid.write('\n------------------------------------------------------------------\n')
+							fid.close()
+							print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,fieldname)
+						else:
+							print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,fieldname)
+							raise RuntimeError(me2)
+
+				f.close()
+
+		except Exception as me:
+
+			#something went wrong, print failure message:
+			directory=os.getcwd().split('/')    #  not used?
+			message=me
+			if   output.lower() == 'nightly':
+				fid=open(os.path.join(ISSM_DIR+'nightlylog','matlaberror.log'), 'a')
+				fid.write('%s' % message)
+				fid.write('\n------------------------------------------------------------------\n')
+				fid.close()
+				print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,'N/A')
+			elif output.lower() == 'daily':
+				fid=open(os.path.join(ISSM_DIR+'dailylog','matlaberror.log'), 'a')
+				fid.write('%s' % message)
+				fid.write('\n------------------------------------------------------------------\n')
+				fid.close()
+				print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,'N/A')
+			else:
+				print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,'N/A')
+				raise RuntimeError(me)
+
+#	#output md if requested
+#	if nargout==1
+#		varargout{1}=md;
+#	end
+
+	return
+
+if __name__ == '__main__':
+	if 'PYTHONSTARTUP' in os.environ:
+		PYTHONSTARTUP=os.environ['PYTHONSTARTUP']
+		print 'PYTHONSTARTUP =',PYTHONSTARTUP
+		if os.path.exists(PYTHONSTARTUP):
+			try:
+				execfile(PYTHONSTARTUP)
+			except Exception as e:
+				print "PYTHONSTARTUP error: ",e
+		else:
+			print "PYTHONSTARTUP file '%s' does not exist." % PYTHONSTARTUP
+
+	import argparse
+	parser = argparse.ArgumentParser(description='RUNME - test deck for ISSM nightly runs')
+	parser.add_argument('-i','--id', nargs='*', type=int, help='followed by the list of ids requested', default=[])
+	parser.add_argument('-e','--exclude', nargs='*', type=int, help='ids to be excluded from the test', default=[])
+	parser.add_argument('-b','--benchmark', help='nightly/ismip/eismint/thermal/mesh/...', default='nightly')
+	parser.add_argument('-p','--procedure', help='check/update', default='check')
+	parser.add_argument('-o','--output', help='nightly/daily/none', default='none')
+	parser.add_argument('-r','--rank', type=int, help='rank', default=1)
+	parser.add_argument('-n','--numprocs', type=int, help='numprocs', default=1)
+	args = parser.parse_args()
+
+	md = runme(args.id, args.exclude, args.benchmark, args.procedure, args.output, args.rank, args.numprocs)
+
+	exit(md)
+
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test101.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test101.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test101.m	(revision 12878)
@@ -0,0 +1,22 @@
+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=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/branches/trunk-jpl-damage/test/NightlyRun/test101.py
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test101.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test101.py	(revision 12878)
@@ -0,0 +1,24 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+
+md=model()
+md=triangle(md,'../Exp/Square.exp',50000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+
+#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/branches/trunk-jpl-damage/test/NightlyRun/test102.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test102.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test102.m	(revision 12878)
@@ -1,22 +1,18 @@
-md=triangle(model,'../Exp/Square.exp',50000);
+md=triangle(model,'../Exp/Square.exp',180000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.diagnostic.requested_outputs=StressTensorEnum;
 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_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.DiagnosticSolution.Vx),...
 	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
 	(md.results.DiagnosticSolution.Vel),...
 	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.StressTensorxx),...
-	(md.results.DiagnosticSolution.StressTensoryy),...
-	(md.results.DiagnosticSolution.StressTensorxy),...
 	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test102.py
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test102.py	(revision 12877)
+++ 	(revision )
@@ -1,9 +1,0 @@
-from model import *
-from triangle import *
-from setmask import *
-from parameterize import *
-
-md=model();
-md=triangle(md,'../Exp/Square.exp',50000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.py')
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test103.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test103.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test103.m	(revision 12878)
@@ -0,0 +1,27 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.diagnostic.requested_outputs=StressTensorEnum;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure',...
+	'StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.StressTensorxx),...
+	(md.results.DiagnosticSolution.StressTensoryy),...
+	(md.results.DiagnosticSolution.StressTensorzz),...
+	(md.results.DiagnosticSolution.StressTensorxy),...
+	(md.results.DiagnosticSolution.StressTensorxz),...
+	(md.results.DiagnosticSolution.StressTensoryz),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test104.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test104.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test104.m	(revision 12878)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,2);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'stokes','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,DiagnosticSolutionEnum);
@@ -9,5 +9,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08};
 field_values={...
 	(md.results.DiagnosticSolution.Vx),...
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test105.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test105.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test105.m	(revision 12878)
@@ -0,0 +1,13 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test106.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test106.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test106.m	(revision 12878)
@@ -1,27 +1,16 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',150000);
+md=meshconvert(md);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,2);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.diagnostic.requested_outputs=StressTensorEnum;
-md=solve(md,DiagnosticSolutionEnum);
+md.prognostic.stabilization=3;
+md.prognostic.spcthickness=md.geometry.thickness;
+md=solve(md,PrognosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure',...
-	'StressTensorxx','StressTensoryy','StressTensorzz','StressTensorxy','StressTensorxz','StressTensoryz'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,...
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.StressTensorxx),...
-	(md.results.DiagnosticSolution.StressTensoryy),...
-	(md.results.DiagnosticSolution.StressTensorzz),...
-	(md.results.DiagnosticSolution.StressTensorxy),...
-	(md.results.DiagnosticSolution.StressTensorxz),...
-	(md.results.DiagnosticSolution.StressTensoryz),...
+	(md.results.PrognosticSolution.Thickness),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test107.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test107.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test107.m	(revision 12878)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md=extrude(md,5,3);
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test108.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test108.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test108.m	(revision 12878)
@@ -2,17 +2,15 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,2);
-md=setflowequation(md,'stokes','all');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.timestepping.time_step=0;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,ThermalSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08};
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test109.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test109.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test109.m	(revision 12878)
@@ -0,0 +1,19 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isdiagnostic=0;
+md.transient.isprognostic=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test110.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test110.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test110.m	(revision 12878)
@@ -4,10 +4,37 @@
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum);
+md.transient.requested_outputs=IceVolumeEnum();
+
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Volume1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Volume2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Volume3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).IceVolume),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).IceVolume),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).IceVolume),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test1107.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test1107.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test1107.m	(revision 12878)
@@ -131,5 +131,5 @@
 };
 field_tolerances={...
-	1e-08,1e-08,1e-06,...
+	1e-07,1e-08,1e-06,...
 	1e-08,1e-08,1e-06,...
 	1e-08,1e-08,1e-07,...
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test1108.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test1108.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test1108.m	(revision 12878)
@@ -74,5 +74,5 @@
 	1e-07,1e-07,1e-07,...
 	1e-08,1e-08,1e-08,...
-	1e-08,1e-07,1e-08,...
+	1e-08,1e-07,1e-07,...
 	1e-08,1e-08,1e-08,...
 	1e-08,1e-07,1e-07,...
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test111.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test111.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test111.m	(revision 12878)
@@ -0,0 +1,53 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.requested_outputs=IceVolumeEnum();
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names={...
+	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface2','Thickness1','Temperature1','BasalforcingsMeltingRate1','Volume1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2','Volume2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3','Volume3'};
+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-12,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-11};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).IceVolume),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).IceVolume),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).IceVolume),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test112.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test112.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test112.m	(revision 12878)
@@ -1,16 +1,14 @@
 md=triangle(model,'../Exp/Square.exp',150000);
-md=meshconvert(md);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.prognostic.stabilization=3;
-md.prognostic.spcthickness=md.geometry.thickness;
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,SurfaceSlopeSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test113.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test113.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test113.m	(revision 12878)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SurfaceSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test114.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test114.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test114.m	(revision 12878)
@@ -3,12 +3,12 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=setflowequation(md,'macayeal','all');
-md=extrude(md,5,3);
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,BedSlopeSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test115.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test115.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test115.m	(revision 12878)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BedSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test116.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test116.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test116.m	(revision 12878)
@@ -1,16 +1,16 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
+%Add boundary conditions on thickness on the border
+pos=find(md.mesh.vertexonboundary);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
 md=setflowequation(md,'macayeal','all');
-md.timestepping.time_step=0;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,ThermalSolutionEnum);
+md=solve(md,BalancethicknessSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13};
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
 field_values={...
-	(md.results.ThermalSolution.Temperature),...
-	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	(md.results.BalancethicknessSolution.Thickness),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test117.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test117.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test117.m	(revision 12878)
@@ -0,0 +1,17 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,5,1);
+%Add boundary conditions on thickness on the border
+pos=find(md.mesh.vertexonboundary);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test118.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test118.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test118.m	(revision 12878)
@@ -1,19 +1,16 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',150000);
+md=meshconvert(md);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
+md.balancethickness.stabilization=3;
+md.initialization.vy=md.initialization.vy+400;
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
-md.transient.isthermal=1;
-md.transient.isgroundingline=0;
-md=solve(md,TransientSolutionEnum);
+md=solve(md,BalancethicknessSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13};
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
 field_values={...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.BalancethicknessSolution.Thickness),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test119.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test119.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test119.m	(revision 12878)
@@ -0,0 +1,25 @@
+
+%Simple mesh
+md=bamg(model,'domain','../Exp/Square.exp','hmax',100000);
+x1=md.mesh.x;
+y1=md.mesh.y;
+
+%hVertices
+md=bamg(model,'domain','../Exp/Square.exp','hmax',300000,'hvertices',[10000 100000 400000 100000]');
+x2=md.mesh.x;
+y2=md.mesh.y;
+
+%big mesh
+t0=clock;
+md=bamg(model,'domain','../Exp/Square.exp','hmax',3000);
+nbelements=md.mesh.numberofelements;
+elapsedtime=etime(clock,t0);
+
+%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.5};
+field_values={...
+	x1, y1,...
+	x2, y2,...
+	nbelements,elapsedtime...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test120.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test120.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test120.m	(revision 12878)
@@ -1,36 +1,18 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',180000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1);
 md=setflowequation(md,'macayeal','all');
+md.timestepping.time_step=0;
 md.cluster=generic('name',oshostname(),'np',3);
-
-md=solve(md,TransientSolutionEnum);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md=solve(md,EnthalpySolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-						1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-						1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Enthalpy','Waterfraction','Temperature'};
+field_tolerances={1e-13,1e-10,1e-13};
 field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
+	(md.results.EnthalpySolution.Enthalpy),...
+	(md.results.EnthalpySolution.Waterfraction),...
+	(md.results.EnthalpySolution.Temperature),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test121.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test121.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test121.m	(revision 12878)
@@ -0,0 +1,30 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.transient.isdiagnostic=0;
+md.transient.isprognostic=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md.thermal.isenthalpy=1;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Enthalpy1','Waterfraction1','Temperature1',...
+	'Enthalpy2','Waterfraction2','Temperature2',...
+	'Enthalpy3','Waterfraction3','Temperature3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-10,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Enthalpy),...
+	(md.results.TransientSolution(1).Waterfraction),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(2).Enthalpy),...
+	(md.results.TransientSolution(2).Waterfraction),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(3).Enthalpy),...
+	(md.results.TransientSolution(3).Waterfraction),...
+	(md.results.TransientSolution(3).Temperature),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test122.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test122.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test122.m	(revision 12878)
@@ -4,16 +4,18 @@
 md=extrude(md,3,1);
 md=setflowequation(md,'pattyn','all');
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.thermal.isenthalpy=1;
+md.thermal.stabilization=2;
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names={...
-	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','Enthalpy1','Waterfraction1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','Enthalpy2','Waterfraction2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','Enthalpy3','Waterfraction3'};
 field_tolerances={...
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
@@ -26,5 +28,6 @@
 	(md.results.TransientSolution(1).Thickness),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).Enthalpy),...
+	(md.results.TransientSolution(1).Waterfraction),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
@@ -36,5 +39,6 @@
 	(md.results.TransientSolution(2).Thickness),...
 	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Enthalpy),...
+	(md.results.TransientSolution(2).Waterfraction),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
@@ -46,4 +50,5 @@
 	(md.results.TransientSolution(3).Thickness),...
 	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Enthalpy),...
+	(md.results.TransientSolution(3).Waterfraction),...
 	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test124.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test124.m	(revision 12877)
+++ 	(revision )
@@ -1,14 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,SurfaceSlopeSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
-field_tolerances={1e-13,1e-13};
-field_values={...
-	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
-	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test126.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test126.m	(revision 12877)
+++ 	(revision )
@@ -1,15 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,5,1);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,SurfaceSlopeSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
-field_tolerances={1e-13,1e-13};
-field_values={...
-	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
-	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test128.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test128.m	(revision 12877)
+++ 	(revision )
@@ -1,14 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BedSlopeSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'BedSlopeX','BedSlopeY'};
-field_tolerances={1e-13,1e-13};
-field_values={...
-	(md.results.BedSlopeSolution.BedSlopeX),...
-	(md.results.BedSlopeSolution.BedSlopeY),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test130.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test130.m	(revision 12877)
+++ 	(revision )
@@ -1,15 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,5,1);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BedSlopeSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'BedSlopeX','BedSlopeY'};
-field_tolerances={1e-13,1e-13};
-field_values={...
-	(md.results.BedSlopeSolution.BedSlopeX),...
-	(md.results.BedSlopeSolution.BedSlopeY),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test132.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test132.m	(revision 12877)
+++ 	(revision )
@@ -1,16 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.par');
-%Add boundary conditions on thickness on the border
-pos=find(md.mesh.vertexonboundary);
-md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
-field_values={...
-	(md.results.BalancethicknessSolution.Thickness),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test134.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test134.m	(revision 12877)
+++ 	(revision )
@@ -1,17 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,5,1);
-%Add boundary conditions on thickness on the border
-pos=find(md.mesh.vertexonboundary);
-md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
-field_values={...
-	(md.results.BalancethicknessSolution.Thickness),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test136.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test136.m	(revision 12877)
+++ 	(revision )
@@ -1,16 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=meshconvert(md);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md.balancethickness.stabilization=3;
-md.initialization.vy=md.initialization.vy+400;
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
-field_values={...
-	(md.results.BalancethicknessSolution.Thickness),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test137.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test137.m	(revision 12877)
+++ 	(revision )
@@ -1,25 +1,0 @@
-
-%Simple mesh
-md=bamg(model,'domain','../Exp/Square.exp','hmax',100000);
-x1=md.mesh.x;
-y1=md.mesh.y;
-
-%hVertices
-md=bamg(model,'domain','../Exp/Square.exp','hmax',300000,'hvertices',[10000 100000 400000 100000]');
-x2=md.mesh.x;
-y2=md.mesh.y;
-
-%big mesh
-t0=clock;
-md=bamg(model,'domain','../Exp/Square.exp','hmax',3000);
-nbelements=md.mesh.numberofelements;
-elapsedtime=etime(clock,t0);
-
-%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.5};
-field_values={...
-	x1, y1,...
-	x2, y2,...
-	nbelements,elapsedtime...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test140.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test140.m	(revision 12877)
+++ 	(revision )
@@ -1,18 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-md.timestepping.time_step=0;
-md.cluster=generic('name',oshostname(),'np',3);
-md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md=solve(md,EnthalpySolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Enthalpy','Waterfraction','Temperature'};
-field_tolerances={1e-13,1e-10,1e-13};
-field_values={...
-	(md.results.EnthalpySolution.Enthalpy),...
-	(md.results.EnthalpySolution.Waterfraction),...
-	(md.results.EnthalpySolution.Temperature),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test142.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test142.m	(revision 12877)
+++ 	(revision )
@@ -1,30 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
-md.transient.isthermal=1;
-md.transient.isgroundingline=0;
-md.thermal.isenthalpy=1;
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Enthalpy1','Waterfraction1','Temperature1',...
-	'Enthalpy2','Waterfraction2','Temperature2',...
-	'Enthalpy3','Waterfraction3','Temperature3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-10,1e-13};
-field_values={...
-	(md.results.TransientSolution(1).Enthalpy),...
-	(md.results.TransientSolution(1).Waterfraction),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(2).Enthalpy),...
-	(md.results.TransientSolution(2).Waterfraction),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(3).Enthalpy),...
-	(md.results.TransientSolution(3).Waterfraction),...
-	(md.results.TransientSolution(3).Temperature),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test144.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test144.m	(revision 12877)
+++ 	(revision )
@@ -1,54 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',200000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
-md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md.thermal.isenthalpy=1;
-md.thermal.stabilization=2;
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','Enthalpy1','Waterfraction1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','Enthalpy2','Waterfraction2', ...
-					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','Enthalpy3','Waterfraction3'};
-field_tolerances={...
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).Enthalpy),...
-	(md.results.TransientSolution(1).Waterfraction),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).Enthalpy),...
-	(md.results.TransientSolution(2).Waterfraction),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).Enthalpy),...
-	(md.results.TransientSolution(3).Waterfraction),...
-	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test201.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test201.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test201.m	(revision 12878)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test202.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test202.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test202.m	(revision 12878)
@@ -1,5 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',180000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -7,9 +8,10 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.DiagnosticSolution.Vx),...
 	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
 	(md.results.DiagnosticSolution.Vel),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test203.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test203.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test203.m	(revision 12878)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test204.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test204.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test204.m	(revision 12878)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,2);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'stokes','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,DiagnosticSolutionEnum);
@@ -9,5 +9,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08};
 field_values={...
 	(md.results.DiagnosticSolution.Vx),...
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test205.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test205.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test205.m	(revision 12878)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','../Exp/SquareHalfRight.exp','fill','macayeal','coupling','penalties');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-05,1e-05,1e-05,1e-05,1e-05};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test206.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test206.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test206.m	(revision 12878)
@@ -2,17 +2,15 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,2);
-md=setflowequation(md,'pattyn','all');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.timestepping.time_step=0;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,ThermalSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test207.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test207.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test207.m	(revision 12878)
@@ -0,0 +1,23 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isdiagnostic=0;
+md.transient.isprognostic=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature1','BasalforcingsMeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test208.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test208.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test208.m	(revision 12878)
@@ -1,18 +1,33 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,2);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08};
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test209.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test209.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test209.m	(revision 12878)
@@ -0,0 +1,48 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,...
+	1e-13,1e-13,1e-08,1e-13,1e-13,1e-10,1e-10,1e-10,1e-13,1e-8};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test210.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test210.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test210.m	(revision 12878)
@@ -1,18 +1,48 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',200000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,2);
-md=setflowequation(md,'pattyn','../Exp/SquareHalfRight.exp','fill','macayeal','coupling','penalties');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,TransientSolutionEnum);
 
 %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_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      '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-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
+	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test211.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test211.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test211.m	(revision 12878)
@@ -0,0 +1,50 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'stokes','all');
+md.diagnostic.reltol=NaN;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names={...
+	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={...
+	1e-08,1e-08,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,...
+	1e-08,1e-08,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06,...
+	1e-07,1e-07,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test212.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test212.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test212.m	(revision 12878)
@@ -1,16 +1,33 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',200000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
 md=setflowequation(md,'macayeal','all');
-md.timestepping.time_step=0;
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,ThermalSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13};
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.ThermalSolution.Temperature),...
-	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
-	};
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyBbar),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test213.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test213.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test213.m	(revision 12878)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyB),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test214.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test214.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test214.m	(revision 12878)
@@ -1,23 +1,34 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',200000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'pattyn','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
 md.cluster=generic('name',oshostname(),'np',3);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
-md.transient.isthermal=1;
-md.transient.isgroundingline=0;
-md=solve(md,TransientSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature1','BasalforcingsMeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08};
 field_values={...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
-	};
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyB),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test215.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test215.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test215.m	(revision 12878)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'stokes','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyB),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test216.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test216.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test216.m	(revision 12878)
@@ -1,33 +1,24 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/SquareHole.exp','../Exp/Rifts.exp',50000);
+md=meshprocessrifts(md,'../Exp/Square.exp');
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+
+%rift settings
+md.rifts.riftstruct.fill=MelangeEnum();
+md.rifts.riftstruct.fraction=0;
+md.diagnostic.rift_penalty_lock=2;
+md.diagnostic.rift_penalty_threshold=0;
+md.rifts.riftstruct.fractionincrement=.1;
+md=solve(md,DiagnosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-11,1e-11,1e-11,1e-11};
 field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test217.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test217.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test217.m	(revision 12878)
@@ -0,0 +1,69 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%redo the parameter file for this special shelf. 
+%constant thickness, constrained (vy=0) flow into an icefront, 
+%from 0 m/yr at the grounding line.
+
+%tighten
+md.diagnostic.restol=10^-4;
+
+%needed later
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+
+di=md.materials.rho_ice/md.materials.rho_water;
+
+h=1000;
+md.geometry.thickness=h*ones(md.mesh.numberofvertices,1);
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+%Initial velocity and pressure
+md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+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);
+
+%Boundary conditions:
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+%constrain flanks to 0 normal velocity
+pos=find(md.mesh.x==xmin | md.mesh.x==xmax);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvz(pos)=NaN;
+
+%constrain grounding line to 0 velocity
+pos=find(md.mesh.y==ymin);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+
+%icefront
+nodeonicefront=zeros(md.mesh.numberofvertices,1);
+pos=find(md.mesh.y==ymax); nodeonicefront(pos)=1;
+pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2))); diagnostic.icefront=md.mesh.segments(pos,:);
+diagnostic.icefront=[diagnostic.icefront 1*md.mask.elementonfloatingice(diagnostic.icefront(:,end))];
+md.diagnostic.icefront=diagnostic.icefront;
+
+md=solve(md,DiagnosticSolutionEnum);
+
+%create analytical solution: strain rate is constant = ((rho_ice*g*h)/4B)^3 (Paterson, 4th Edition, page 292.
+%ey_c=(md.materials.rho_ice*md.constants.g*(1-di)*md.geometry.thickness./(4*md.materials.rheology_B)).^3;
+%vy_c=ey_c.*md.mesh.y*md.constants.yts;
+
+%Fields and tolerances to track changes
+field_names     ={'Vy'};
+field_tolerances={1e-13};
+field_values={(md.results.DiagnosticSolution.Vy)};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test218.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test218.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test218.m	(revision 12878)
@@ -1,48 +1,92 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=squaremesh(model,1000000,1000000,5,5);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+
+%redo the parameter file for this special shelf. 
+%constant thickness, constrained (vy=0) flow into an icefront, 
+%from 0 m/yr at the grounding line.
+
+%needed later
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+
+di=md.materials.rho_ice/md.materials.rho_water;
+
+h=1000;
+md.geometry.thickness=h*ones(md.mesh.numberofvertices,1);
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+%Initial velocity and pressure
+md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+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);
+
+%Boundary conditions:
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+
+%constrain flanks to 0 normal velocity
+pos=find(md.mesh.x==xmin | md.mesh.x==xmax);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvz(pos)=NaN;
+
+%constrain grounding line to 0 velocity
+pos=find(md.mesh.y==ymin);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+
+%icefront
+nodeonicefront=zeros(md.mesh.numberofvertices,1);
+pos=find(md.mesh.y==ymax); nodeonicefront(pos)=1;
+pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2))); diagnostic.icefront=md.mesh.segments(pos,:);
+diagnostic.icefront=[diagnostic.icefront 1*md.mask.elementonfloatingice(diagnostic.icefront(:,end))];
+md.diagnostic.icefront=diagnostic.icefront;
+
+%partitioning
+md.qmu.numberofpartitions=md.mesh.numberofvertices;
+md=partitioner(md,'package','linear','npart',md.qmu.numberofpartitions);
+md.qmu.partition=md.qmu.partition-1;
+
+%Dakota options
+%variables
+md.qmu.variables.rheology_B=normal_uncertain('scaled_MaterialsRheologyB',1,.05);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+%imperative! 
+md.diagnostic.reltol=10^-10; %tighten for qmu analysese
+md.qmu.isdakota=1;
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
-field_tolerances={...
-	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,...
-	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,...
-	1e-13,1e-13,1e-08,1e-13,1e-13,1e-10,1e-10,1e-10,1e-13,1e-8};
+md=tres(md,'dakota');
+md.results.dakota.importancefactors=importancefactors(md,'scaled_MaterialsRheologyB','MaxVel')';
+field_names     ={'importancefactors'};
+field_tolerances={1e-10};
 field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+         md.results.dakota.importancefactors,...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test219.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test219.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test219.m	(revision 12878)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','../Exp/SquareHalfRight.exp','fill','macayeal');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test220.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test220.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test220.m	(revision 12878)
@@ -1,48 +1,18 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model,'../Exp/Square.exp',120000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
+md=extrude(md,2,1);
+md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      '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-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
-	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
 field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test221.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test221.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test221.m	(revision 12878)
@@ -0,0 +1,19 @@
+md=triangle(model,'../Exp/Square.exp',120000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,2,1);
+md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','macayeal');
+md.cluster=generic('name',oshostname(),'np',3);
+md.diagnostic.viscosity_overshoot=0;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test222.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test222.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test222.m	(revision 12878)
@@ -1,24 +1,16 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'stokes','all');
-md.diagnostic.reltol=NaN;
+md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
+md.prognostic.hydrostatic_adjustment='Incremental';
 md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names={...
-	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
-field_tolerances={...
-	1e-08,1e-08,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,...
-	1e-08,1e-08,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06,...
-	1e-07,1e-07,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06};
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
 	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
 	(md.results.TransientSolution(1).Vel),...
 	(md.results.TransientSolution(1).Pressure),...
@@ -26,9 +18,6 @@
 	(md.results.TransientSolution(1).Surface),...
 	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
 	(md.results.TransientSolution(2).Vel),...
 	(md.results.TransientSolution(2).Pressure),...
@@ -36,9 +25,6 @@
 	(md.results.TransientSolution(2).Surface),...
 	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
 	(md.results.TransientSolution(3).Vel),...
 	(md.results.TransientSolution(3).Pressure),...
@@ -46,5 +32,3 @@
 	(md.results.TransientSolution(3).Surface),...
 	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test223.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test223.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test223.m	(revision 12878)
@@ -0,0 +1,35 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.geometry.bed=md.geometry.bed+50; md.geometry.surface=md.geometry.surface+50;
+md.cluster=generic('name',oshostname(),'np',3);
+md.prognostic.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test224.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test224.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test224.m	(revision 12878)
@@ -2,32 +2,48 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
-
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'MaterialsRheologyBbar'};
-md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
-md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
-
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md.prognostic.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      '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-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
+	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
-	(md.results.DiagnosticSolution.MaterialsRheologyBbar),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
-};
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test225.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test225.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test225.m	(revision 12878)
@@ -0,0 +1,50 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.geometry.bed=md.geometry.bed+50; md.geometry.surface=md.geometry.surface+50;
+md.cluster=generic('name',oshostname(),'np',3);
+md.prognostic.hydrostatic_adjustment='Incremental';
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      '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-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
+	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
+	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test226.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test226.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test226.m	(revision 12878)
@@ -1,34 +1,35 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
 md=setflowequation(md,'macayeal','all');
-
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'MaterialsRheologyBbar'};
-md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
-md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
-
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md.timestepping.time_adapt=1;
+md.timestepping.final_time=10;
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
-	(md.results.DiagnosticSolution.MaterialsRheologyB),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
-};
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test227.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test227.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test227.m	(revision 12878)
@@ -0,0 +1,50 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_adapt=1;
+md.timestepping.final_time=10;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      '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-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
+	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
+	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test228.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test228.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test228.m	(revision 12878)
@@ -1,34 +1,64 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
 
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'MaterialsRheologyBbar'};
-md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
-md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
 
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
-field_tolerances={1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08};
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
-	(md.results.DiagnosticSolution.MaterialsRheologyB),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
-};
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test229.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test229.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test229.m	(revision 12878)
@@ -0,0 +1,64 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*2 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
+	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
+field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test230.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test230.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test230.m	(revision 12878)
@@ -1,34 +1,69 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model,'../Exp/Square.exp',350000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
 
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'MaterialsRheologyBbar'};
-md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
-md.inversion.gradient_scaling=10^7*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
 
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
-field_tolerances={1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3',...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceMassbalance4'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
-	(md.results.DiagnosticSolution.MaterialsRheologyB),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
-};
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test231.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test231.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test231.m	(revision 12878)
@@ -0,0 +1,69 @@
+md=triangle(model,'../Exp/Square.exp',350000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+%Set up transient
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*2 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3',...
+	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceMassbalance4'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test232.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test232.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test232.m	(revision 12878)
@@ -1,24 +1,28 @@
-md=triangle(model,'../Exp/SquareHole.exp','../Exp/Rifts.exp',50000);
-md=meshprocessrifts(md,'../Exp/Square.exp');
+md=triangle(model,'../Exp/Square.exp',180000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-
-%rift settings
-md.rifts.riftstruct.fill=MelangeEnum();
-md.rifts.riftstruct.fraction=0;
-md.diagnostic.rift_penalty_lock=2;
-md.diagnostic.rift_penalty_threshold=0;
-md.rifts.riftstruct.fractionincrement=.1;
-md=solve(md,DiagnosticSolutionEnum);
+md.thermal.spctemperature=[md.thermal.spctemperature, md.thermal.spctemperature+5, md.thermal.spctemperature+10, md.thermal.spctemperature+15; 1.5 2.5 3.5 4];
+md.timestepping.time_step=1;
+md.timestepping.final_time=4;
+md.transient.isdiagnostic=0;
+md.transient.isprognostic=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={1e-11,1e-11,1e-11,1e-11};
+field_names     ={'Temperature1','BasalforcingsMeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3','Temperature4','BasalforcingsMeltingRate4'};
+field_tolerances={1e-13,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.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(4).Temperature),...
+	(md.results.TransientSolution(4).BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test233.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test233.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test233.m	(revision 12878)
@@ -0,0 +1,62 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.thermal.spctemperature=[md.thermal.spctemperature, md.thermal.spctemperature+5; 1 2];
+md.timestepping.time_step=0.5;
+md.timestepping.final_time=2;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3', ...
+					   'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','Temperature4','BasalforcingsMeltingRate4'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09, ...
+						1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-07, ...
+						1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06, ...
+						1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(4).Vx),...
+	(md.results.TransientSolution(4).Vy),...
+	(md.results.TransientSolution(4).Vz),...
+	(md.results.TransientSolution(4).Vel),...
+	(md.results.TransientSolution(4).Pressure),...
+	(md.results.TransientSolution(4).Bed),...
+	(md.results.TransientSolution(4).Surface),...
+	(md.results.TransientSolution(4).Thickness),...
+	(md.results.TransientSolution(4).Temperature),...
+	(md.results.TransientSolution(4).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test234.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test234.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test234.m	(revision 12878)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',180000);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
@@ -5,65 +5,68 @@
 md.cluster=generic('name',oshostname(),'np',3);
 
-%redo the parameter file for this special shelf. 
-%constant thickness, constrained (vy=0) flow into an icefront, 
-%from 0 m/yr at the grounding line.
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
 
-%tighten
-md.diagnostic.restol=10^-4;
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
 
-%needed later
-ymin=min(md.mesh.y);
-ymax=max(md.mesh.y);
-xmin=min(md.mesh.x);
-xmax=max(md.mesh.x);
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+%Dakota options
 
-di=md.materials.rho_ice/md.materials.rho_water;
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
 
-h=1000;
-md.geometry.thickness=h*ones(md.mesh.numberofvertices,1);
-md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
-md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+%variables
+md.qmu.variables.surface_mass_balance=normal_uncertain('scaled_SurfaceforcingsMassBalance',1,0.1);
 
-%Initial velocity and pressure
-md.initialization.vx=zeros(md.mesh.numberofvertices,1);
-md.initialization.vy=zeros(md.mesh.numberofvertices,1);
-md.initialization.vz=zeros(md.mesh.numberofvertices,1);
-md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.IceVolume=response_function('IceVolume',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.massFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
 
-%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);
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
 
-%Boundary conditions:
-md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+%%  nond_sampling study
+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');
 
-%constrain flanks to 0 normal velocity
-pos=find(md.mesh.x==xmin | md.mesh.x==xmax);
-md.diagnostic.spcvx(pos)=0;
-md.diagnostic.spcvz(pos)=NaN;
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+md.qmu.isdakota=1;
 
-%constrain grounding line to 0 velocity
-pos=find(md.mesh.y==ymin);
-md.diagnostic.spcvx(pos)=0;
-md.diagnostic.spcvy(pos)=0;
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+md.transient.requested_outputs=IceVolumeEnum();
 
-%icefront
-nodeonicefront=zeros(md.mesh.numberofvertices,1);
-pos=find(md.mesh.y==ymax); nodeonicefront(pos)=1;
-pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2))); diagnostic.icefront=md.mesh.segments(pos,:);
-diagnostic.icefront=[diagnostic.icefront 1*md.mask.elementonfloatingice(diagnostic.icefront(:,end))];
-md.diagnostic.icefront=diagnostic.icefront;
-
-md=solve(md,DiagnosticSolutionEnum);
-
-%create analytical solution: strain rate is constant = ((rho_ice*g*h)/4B)^3 (Paterson, 4th Edition, page 292.
-%ey_c=(md.materials.rho_ice*md.constants.g*(1-di)*md.geometry.thickness./(4*md.materials.rheology_B)).^3;
-%vy_c=ey_c.*md.mesh.y*md.constants.yts;
+%solve
+md=solve(md,TransientSolutionEnum,'overwrite','y');
+md=tres(md,'dakota');
 
 %Fields and tolerances to track changes
-field_names     ={'Vy'};
-field_tolerances={1e-13};
-field_values={(md.results.DiagnosticSolution.Vy)};
+md.results.dakota.importancefactors=[];
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'importancefactors'};
+field_tolerances={1e-11};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test235.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test235.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test235.m	(revision 12878)
@@ -0,0 +1,72 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+md.timestepping.time_step=1;
+md.settings.output_frequency=1;
+md.timestepping.final_time=4;
+
+smb = ones(md.mesh.numberofvertices,1)*3.6;
+smb=[ smb smb*-1 ];
+
+md.surfaceforcings.mass_balance= smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
+md.transient.isthermal=0;
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.surface_mass_balance=normal_uncertain('scaled_SurfaceforcingsMassBalance',1,100);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.IceVolume=response_function('IceVolume',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.massFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+md.qmu.params.fd_gradient_step_size='0.1';
+md.qmu.isdakota=1;
+
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+md.transient.requested_outputs=IceVolumeEnum();
+
+%solve
+md=solve(md,TransientSolutionEnum,'overwrite','y');
+md=tres(md,'dakota');
+
+%Fields and tolerances to track changes
+md.results.dakota.importancefactors=[];
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'importancefactors'};
+field_tolerances={1e-11};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test236.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test236.m	(revision 12877)
+++ 	(revision )
@@ -1,92 +1,0 @@
-md=squaremesh(model,1000000,1000000,5,5);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-
-%redo the parameter file for this special shelf. 
-%constant thickness, constrained (vy=0) flow into an icefront, 
-%from 0 m/yr at the grounding line.
-
-%needed later
-ymin=min(md.mesh.y);
-ymax=max(md.mesh.y);
-xmin=min(md.mesh.x);
-xmax=max(md.mesh.x);
-
-di=md.materials.rho_ice/md.materials.rho_water;
-
-h=1000;
-md.geometry.thickness=h*ones(md.mesh.numberofvertices,1);
-md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
-md.geometry.surface=md.geometry.bed+md.geometry.thickness;
-
-%Initial velocity and pressure
-md.initialization.vx=zeros(md.mesh.numberofvertices,1);
-md.initialization.vy=zeros(md.mesh.numberofvertices,1);
-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);
-
-%Boundary conditions:
-md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
-
-%constrain flanks to 0 normal velocity
-pos=find(md.mesh.x==xmin | md.mesh.x==xmax);
-md.diagnostic.spcvx(pos)=0;
-md.diagnostic.spcvz(pos)=NaN;
-
-%constrain grounding line to 0 velocity
-pos=find(md.mesh.y==ymin);
-md.diagnostic.spcvx(pos)=0;
-md.diagnostic.spcvy(pos)=0;
-
-%icefront
-nodeonicefront=zeros(md.mesh.numberofvertices,1);
-pos=find(md.mesh.y==ymax); nodeonicefront(pos)=1;
-pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2))); diagnostic.icefront=md.mesh.segments(pos,:);
-diagnostic.icefront=[diagnostic.icefront 1*md.mask.elementonfloatingice(diagnostic.icefront(:,end))];
-md.diagnostic.icefront=diagnostic.icefront;
-
-%partitioning
-md.qmu.numberofpartitions=md.mesh.numberofvertices;
-md=partitioner(md,'package','linear','npart',md.qmu.numberofpartitions);
-md.qmu.partition=md.qmu.partition-1;
-
-%Dakota options
-%variables
-md.qmu.variables.rheology_B=normal_uncertain('scaled_MaterialsRheologyB',1,.05);
-
-%responses
-md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-
-%method
-md.qmu.method     =dakota_method('nond_l');
-
-%parameters
-md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='diagnostic';
-md.qmu.params.evaluation_concurrency=1;
-md.qmu.params.interval_type='forward';
-
-%imperative! 
-md.diagnostic.reltol=10^-10; %tighten for qmu analysese
-md.qmu.isdakota=1;
-
-%solve
-md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
-
-%Fields and tolerances to track changes
-md=tres(md,'dakota');
-md.results.dakota.importancefactors=importancefactors(md,'scaled_MaterialsRheologyB','MaxVel')';
-field_names     ={'importancefactors'};
-field_tolerances={1e-10};
-field_values={...
-         md.results.dakota.importancefactors,...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test238.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test238.m	(revision 12877)
+++ 	(revision )
@@ -1,18 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,2);
-md=setflowequation(md,'pattyn','../Exp/SquareHalfRight.exp','fill','macayeal');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-13};
-field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test240.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test240.m	(revision 12877)
+++ 	(revision )
@@ -1,18 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',120000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,2,1);
-md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
-field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test242.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test242.m	(revision 12877)
+++ 	(revision )
@@ -1,19 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',120000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,2,1);
-md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','macayeal');
-md.cluster=generic('name',oshostname(),'np',3);
-md.diagnostic.viscosity_overshoot=0;
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
-field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test244.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test244.m	(revision 12877)
+++ 	(revision )
@@ -1,34 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.prognostic.hydrostatic_adjustment='Incremental';
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test246.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test246.m	(revision 12877)
+++ 	(revision )
@@ -1,35 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.geometry.bed=md.geometry.bed+50; md.geometry.surface=md.geometry.surface+50;
-md.cluster=generic('name',oshostname(),'np',3);
-md.prognostic.hydrostatic_adjustment='Incremental';
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test248.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test248.m	(revision 12877)
+++ 	(revision )
@@ -1,49 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',200000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.prognostic.hydrostatic_adjustment='Incremental';
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      '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-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
-	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test250.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test250.m	(revision 12877)
+++ 	(revision )
@@ -1,50 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',200000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
-md.geometry.bed=md.geometry.bed+50; md.geometry.surface=md.geometry.surface+50;
-md.cluster=generic('name',oshostname(),'np',3);
-md.prognostic.hydrostatic_adjustment='Incremental';
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      '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-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
-	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test252.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test252.m	(revision 12877)
+++ 	(revision )
@@ -1,35 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_adapt=1;
-md.timestepping.final_time=10;
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test254.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test254.m	(revision 12877)
+++ 	(revision )
@@ -1,50 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',200000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_adapt=1;
-md.timestepping.final_time=10;
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      '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-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,...
-	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
-	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test256.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test256.m	(revision 12877)
+++ 	(revision )
@@ -1,64 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-
-md.timestepping.time_step=1;
-md.settings.output_frequency=1;
-md.timestepping.final_time=4;
-
-%Set up transient
-smb = ones(md.mesh.numberofvertices,1)*3.6;
-smb=[ smb smb*-1 ];
-
-md.surfaceforcings.mass_balance= smb;
-md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
-md.transient.isthermal=0;
-
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
-	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
-	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
-	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
-field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
-	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
-	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
-	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
-
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
-	(md.results.TransientSolution(4).Vx),...
-	(md.results.TransientSolution(4).Vy),...
-	(md.results.TransientSolution(4).Vel),...
-	(md.results.TransientSolution(4).Pressure),...
-	(md.results.TransientSolution(4).Bed),...
-	(md.results.TransientSolution(4).Surface),...
-	(md.results.TransientSolution(4).Thickness),...
-	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test258.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test258.m	(revision 12877)
+++ 	(revision )
@@ -1,64 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-
-md.timestepping.time_step=1;
-md.settings.output_frequency=1;
-md.timestepping.final_time=4;
-
-%Set up transient
-smb = ones(md.mesh.numberofvertices,1)*3.6;
-smb=[ smb smb*2 ];
-
-md.surfaceforcings.mass_balance= smb;
-md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
-md.transient.isthermal=0;
-
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
-	'Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
-	'Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3', ...
-	'Vx4','Vy4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceforcingsMassBalance4'};
-field_tolerances={1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
-	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
-	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
-	1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
-
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
-	(md.results.TransientSolution(4).Vx),...
-	(md.results.TransientSolution(4).Vy),...
-	(md.results.TransientSolution(4).Vel),...
-	(md.results.TransientSolution(4).Pressure),...
-	(md.results.TransientSolution(4).Bed),...
-	(md.results.TransientSolution(4).Surface),...
-	(md.results.TransientSolution(4).Thickness),...
-	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test260.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test260.m	(revision 12877)
+++ 	(revision )
@@ -1,69 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',350000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-
-md.timestepping.time_step=1;
-md.settings.output_frequency=1;
-md.timestepping.final_time=4;
-
-%Set up transient
-smb = ones(md.mesh.numberofvertices,1)*3.6;
-smb=[ smb smb*-1 ];
-
-md.surfaceforcings.mass_balance= smb;
-md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
-md.transient.isthermal=0;
-
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3',...
-	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceMassbalance4'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
-	(md.results.TransientSolution(4).Vx),...
-	(md.results.TransientSolution(4).Vy),...
-	(md.results.TransientSolution(4).Vz),...
-	(md.results.TransientSolution(4).Vel),...
-	(md.results.TransientSolution(4).Pressure),...
-	(md.results.TransientSolution(4).Bed),...
-	(md.results.TransientSolution(4).Surface),...
-	(md.results.TransientSolution(4).Thickness),...
-	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test262.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test262.m	(revision 12877)
+++ 	(revision )
@@ -1,69 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',350000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-
-md.timestepping.time_step=1;
-md.settings.output_frequency=1;
-md.timestepping.final_time=4;
-
-%Set up transient
-smb = ones(md.mesh.numberofvertices,1)*3.6;
-smb=[ smb smb*2 ];
-
-md.surfaceforcings.mass_balance= smb;
-md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
-md.transient.isthermal=0;
-
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','SurfaceforcingsMassBalance1', ...
-	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','SurfaceforcingsMassBalance2', ...
-	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','SurfaceforcingsMassBalance3',...
-	'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','SurfaceMassbalance4'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
-	(md.results.TransientSolution(4).Vx),...
-	(md.results.TransientSolution(4).Vy),...
-	(md.results.TransientSolution(4).Vz),...
-	(md.results.TransientSolution(4).Vel),...
-	(md.results.TransientSolution(4).Pressure),...
-	(md.results.TransientSolution(4).Bed),...
-	(md.results.TransientSolution(4).Surface),...
-	(md.results.TransientSolution(4).Thickness),...
-	(md.results.TransientSolution(4).SurfaceforcingsMassBalance),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test264.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test264.m	(revision 12877)
+++ 	(revision )
@@ -1,28 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.thermal.spctemperature=[md.thermal.spctemperature, md.thermal.spctemperature+5, md.thermal.spctemperature+10, md.thermal.spctemperature+15; 1.5 2.5 3.5 4];
-md.timestepping.time_step=1;
-md.timestepping.final_time=4;
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
-md.transient.isthermal=1;
-md.transient.isgroundingline=0;
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Temperature1','BasalforcingsMeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3','Temperature4','BasalforcingsMeltingRate4'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-field_values={...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(4).Temperature),...
-	(md.results.TransientSolution(4).BasalforcingsMeltingRate),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test266.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test266.m	(revision 12877)
+++ 	(revision )
@@ -1,62 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',200000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.thermal.spctemperature=[md.thermal.spctemperature, md.thermal.spctemperature+5; 1 2];
-md.timestepping.time_step=0.5;
-md.timestepping.final_time=2;
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3', ...
-					   'Vx4','Vy4','Vz4','Vel4','Pressure4','Bed4','Surface4','Thickness4','Temperature4','BasalforcingsMeltingRate4'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09, ...
-						1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-07, ...
-						1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06, ...
-						1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(4).Vx),...
-	(md.results.TransientSolution(4).Vy),...
-	(md.results.TransientSolution(4).Vz),...
-	(md.results.TransientSolution(4).Vel),...
-	(md.results.TransientSolution(4).Pressure),...
-	(md.results.TransientSolution(4).Bed),...
-	(md.results.TransientSolution(4).Surface),...
-	(md.results.TransientSolution(4).Thickness),...
-	(md.results.TransientSolution(4).Temperature),...
-	(md.results.TransientSolution(4).BasalforcingsMeltingRate),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test268.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test268.m	(revision 12877)
+++ 	(revision )
@@ -1,72 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-
-md.timestepping.time_step=1;
-md.settings.output_frequency=1;
-md.timestepping.final_time=4;
-
-smb = ones(md.mesh.numberofvertices,1)*3.6;
-smb=[ smb smb*-1 ];
-
-md.surfaceforcings.mass_balance= smb;
-md.surfaceforcings.mass_balance(end+1,:)=[1.5 3];
-md.transient.isthermal=0;
-%Dakota options
-
-%partitioning
-md.qmu.numberofpartitions=20;
-md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
-md.qmu.partition=md.qmu.partition-1;
-
-%variables
-md.qmu.variables.surface_mass_balance=normal_uncertain('scaled_SurfaceforcingsMassBalance',1,100);
-
-%responses
-md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.IceVolume=response_function('IceVolume',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.massFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-
-%mass flux profiles
-md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp'};
-md.qmu.mass_flux_profile_directory=pwd;
-
-%method
-md.qmu.method     =dakota_method('nond_l');
-
-%parameters
-md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='';
-md.qmu.params.analysis_components='';
-md.qmu.params.evaluation_concurrency=1;
-md.qmu.params.interval_type='forward';
-md.qmu.params.fd_gradient_step_size='0.1';
-md.qmu.isdakota=1;
-
-md.diagnostic.reltol=10^-5; %tighten for qmu analyses
-md.transient.requested_outputs=IceVolumeEnum();
-
-%solve
-md=solve(md,TransientSolutionEnum,'overwrite','y');
-md=tres(md,'dakota');
-
-%Fields and tolerances to track changes
-md.results.dakota.importancefactors=[];
-for i=1:8,
-	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).mean];
-end
-for i=1:8,
-	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).stddev];
-end
-field_names     ={'importancefactors'};
-field_tolerances={1e-11};
-field_values={...
-         md.results.dakota.importancefactors,...
-	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test301.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test301.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test301.m	(revision 12878)
@@ -0,0 +1,16 @@
+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=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test302.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test302.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test302.m	(revision 12878)
@@ -2,5 +2,5 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'hutter','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,DiagnosticSolutionEnum);
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test303.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test303.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test303.m	(revision 12878)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'hutter','../Exp/SquareHalfRight.exp','fill','macayeal');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test304.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test304.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test304.m	(revision 12878)
@@ -1,15 +1,17 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',180000);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'hutter','all');
+md=extrude(md,3,2);
+md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,DiagnosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.DiagnosticSolution.Vx),...
 	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
 	(md.results.DiagnosticSolution.Vel),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test305.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test305.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test305.m	(revision 12878)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,5,2);
+md=setflowequation(md,'hutter','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test306.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test306.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test306.m	(revision 12878)
@@ -1,5 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',180000);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,4,2);
 md=setflowequation(md,'hutter','../Exp/SquareHalfRight.exp','fill','macayeal');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -7,9 +8,10 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.DiagnosticSolution.Vx),...
 	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
 	(md.results.DiagnosticSolution.Vel),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test307.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test307.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test307.m	(revision 12878)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,2e-10,2e-10,1e-10};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test308.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test308.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test308.m	(revision 12878)
@@ -2,6 +2,6 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,2);
-md=setflowequation(md,'macayeal','all');
+md=extrude(md,3,1);
+md=setflowequation(md,'stokes','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,DiagnosticSolutionEnum);
@@ -9,5 +9,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
 field_values={...
 	(md.results.DiagnosticSolution.Vx),...
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test309.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test309.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test309.m	(revision 12878)
@@ -0,0 +1,13 @@
+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=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test310.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test310.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test310.m	(revision 12878)
@@ -1,18 +1,16 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',150000);
+md=meshconvert(md);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,5,2);
-md=setflowequation(md,'hutter','all');
+md=setflowequation(md,'macayeal','all');
+md.prognostic.stabilization=3;
+md.prognostic.spcthickness=md.geometry.thickness;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,PrognosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.PrognosticSolution.Thickness),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test311.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test311.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test311.m	(revision 12878)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md=extrude(md,5,0.5);
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test312.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test312.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test312.m	(revision 12878)
@@ -2,17 +2,15 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,4,2);
-md=setflowequation(md,'hutter','../Exp/SquareHalfRight.exp','fill','macayeal');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.timestepping.time_step=0;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,ThermalSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test313.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test313.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test313.m	(revision 12878)
@@ -0,0 +1,20 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.verbose=verbose('convergence',true,'solution',true);
+md.transient.isdiagnostic=0;
+md.transient.isprognostic=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test314.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test314.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test314.m	(revision 12878)
@@ -1,18 +1,33 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'hutter','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-10,2e-10,1e-10};
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-10,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.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test315.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test315.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test315.m	(revision 12878)
@@ -0,0 +1,47 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,5,1.2);
+md=setflowequation(md,'hutter','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-13,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...,
+						1e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-10,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test316.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test316.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test316.m	(revision 12878)
@@ -1,18 +1,33 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test317.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test317.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test317.m	(revision 12878)
@@ -0,0 +1,47 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      '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_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test318.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test318.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test318.m	(revision 12878)
@@ -1,13 +1,22 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',180000);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=extrude(md,4,1);
+md=setflowequation(md,'hutter','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum);
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13
+};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test319.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test319.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test319.m	(revision 12878)
@@ -0,0 +1,33 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test320.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test320.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test320.m	(revision 12878)
@@ -1,16 +1,34 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=meshconvert(md);
+md=triangle(model,'../Exp/Square.exp',200000);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
 md=setflowequation(md,'macayeal','all');
-md.prognostic.stabilization=3;
-md.prognostic.spcthickness=md.geometry.thickness;
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
-	};
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test321.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test321.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test321.m	(revision 12878)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[102*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-08,1e-07,1e-10,1e-10,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test322.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test322.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test322.m	(revision 12878)
@@ -1,14 +1,34 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',200000);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
-md=extrude(md,5,0.5);
+md=extrude(md,3,1);
+md=setflowequation(md,'stokes','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[104*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-06,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
-	};
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test323.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test323.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test323.m	(revision 12878)
@@ -0,0 +1,35 @@
+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.timestepping.time_adapt=1;
+md.timestepping.final_time=600;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test324.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test324.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test324.m	(revision 12878)
@@ -1,16 +1,49 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-md.timestepping.time_step=0;
+md=extrude(md,5,1.2);
+md=setflowequation(md,'hutter','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,ThermalSolutionEnum);
+md.timestepping.time_adapt=1;
+md.timestepping.final_time=500;
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+					   %'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={1e-13,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...,
+						5*1e-11,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-10,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.ThermalSolution.Temperature),...
-	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+%	(md.results.TransientSolution(3).Vx),...
+%	(md.results.TransientSolution(3).Vy),...
+%	(md.results.TransientSolution(3).Vz),...
+%	(md.results.TransientSolution(3).Vel),...
+%	(md.results.TransientSolution(3).Pressure),...
+%	(md.results.TransientSolution(3).Bed),...
+%	(md.results.TransientSolution(3).Surface),...
+%	(md.results.TransientSolution(3).Thickness),...
+%	(md.results.TransientSolution(3).Temperature),...
+%	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test325.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test325.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test325.m	(revision 12878)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.timestepping.time_step=0;
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md=solve(md,EnthalpySolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Enthalpy','Waterfraction','Temperature'};
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.EnthalpySolution.Enthalpy),...
+	(md.results.EnthalpySolution.Waterfraction),...
+	(md.results.EnthalpySolution.Temperature),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test326.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test326.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test326.m	(revision 12878)
@@ -5,16 +5,26 @@
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.verbose=verbose('convergence',true,'solution',true);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
 md.transient.isdiagnostic=0;
 md.transient.isprognostic=0;
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
+md.thermal.isenthalpy=1;
 md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13};
+field_names     ={'Enthalpy1','Waterfraction1','Temperature1',...
+	'Enthalpy2','Waterfraction2','Temperature2',...
+	'Enthalpy3','Waterfraction3','Temperature3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
+	(md.results.TransientSolution(1).Enthalpy),...
+	(md.results.TransientSolution(1).Waterfraction),...
 	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Enthalpy),...
+	(md.results.TransientSolution(2).Waterfraction),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(3).Enthalpy),...
+	(md.results.TransientSolution(3).Waterfraction),...
+	(md.results.TransientSolution(3).Temperature),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test327.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test327.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test327.m	(revision 12878)
@@ -0,0 +1,55 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.temperature(:)=272;
+md.thermal.spctemperature(find(md.mesh.vertexonsurface))=272;
+md.thermal.isenthalpy=1;
+md.basalforcings.geothermalflux(:)=5;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','Enthalpy1','Waterfraction1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','Enthalpy2','Waterfraction2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','Enthalpy3','Waterfraction3'};
+field_tolerances={1e-09,1e-09,1e-09,1e-10,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-10,...
+						1e-09,5e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).Enthalpy),...
+	(md.results.TransientSolution(1).Waterfraction),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).Enthalpy),...
+	(md.results.TransientSolution(2).Waterfraction),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).Enthalpy),...
+	(md.results.TransientSolution(3).Waterfraction),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test328.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test328.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test328.m	(revision 12878)
@@ -2,32 +2,44 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'hutter','all');
+md=setflowequation(md,'macayeal','all');
+md.surfaceforcings.issmbgradients=1;
+md.surfaceforcings.smb_pos_max=5000. - 0.00005*md.mesh.x + 0.0001*md.mesh.y;
+md.surfaceforcings.smb_pos_min=1250. + 0.00005*md.mesh.x -0.0001*md.mesh.y;
+md.surfaceforcings.a_pos=15000. - 0.000051*md.mesh.x + 0.00011*md.mesh.y;
+md.surfaceforcings.b_pos=-100. + 0.00005*md.mesh.x - 0.0001*md.mesh.y;
+md.surfaceforcings.a_neg=-20000. - 0.00005*md.mesh.x + 0.0001*md.mesh.y;
+md.surfaceforcings.b_neg=250. + 0.000051*md.mesh.x - 0.00011*md.mesh.y;
+md.surfaceforcings.hc=(md.surfaceforcings.a_pos-md.surfaceforcings.a_neg)./(md.surfaceforcings.b_neg-md.surfaceforcings.b_pos);
+md.transient.requested_outputs=TotalSmbEnum();
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx1','Vy1','Vel1','Bed1','Surface1','Thickness1','SMB1','TotalSmb1','Vx2','Vy2','Vel2','Bed2','Surface2','Thickness2','SMB2','TotalSmb2','Vx3','Vy3','Vel3','Bed3','Surface3','Thickness3','SMB3','TotalSmb3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
 	(md.results.TransientSolution(1).Vy),...
 	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
 	(md.results.TransientSolution(1).Bed),...
 	(md.results.TransientSolution(1).Surface),...
 	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(1).TotalSmb),...
 	(md.results.TransientSolution(2).Vx),...
 	(md.results.TransientSolution(2).Vy),...
 	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
 	(md.results.TransientSolution(2).Bed),...
 	(md.results.TransientSolution(2).Surface),...
 	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).TotalSmb),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
 	(md.results.TransientSolution(3).Vx),...
 	(md.results.TransientSolution(3).Vy),...
 	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
 	(md.results.TransientSolution(3).Bed),...
 	(md.results.TransientSolution(3).Surface),...
 	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).TotalSmb),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test329.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test329.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test329.m	(revision 12878)
@@ -0,0 +1,55 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.surfaceforcings.issmbgradients=1;
+md.surfaceforcings.smb_pos_max=5000. - 0.00005*md.mesh.x + 0.0001*md.mesh.y;
+md.surfaceforcings.smb_pos_min=1250. + 0.00005*md.mesh.x -0.0001*md.mesh.y;
+md.surfaceforcings.a_pos=15000. - 0.000051*md.mesh.x + 0.00011*md.mesh.y;
+md.surfaceforcings.b_pos=-100. + 0.00005*md.mesh.x - 0.0001*md.mesh.y;
+md.surfaceforcings.a_neg=-20000. - 0.00005*md.mesh.x + 0.0001*md.mesh.y;
+md.surfaceforcings.b_neg=250. + 0.000051*md.mesh.x - 0.00011*md.mesh.y;
+md.surfaceforcings.hc=(md.surfaceforcings.a_pos-md.surfaceforcings.a_neg)./(md.surfaceforcings.b_neg-md.surfaceforcings.b_pos);
+md.transient.requested_outputs=TotalSmbEnum();
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Bed1','Surface1','Thickness1','Temperature1','SMB1','TotalSmb1','Vx2','Vy2','Vz2','Vel2','Bed2','Surface2','Thickness2','Temperature2','SMB2','TotalSmb1','Vx3','Vy3','Vz3','Vel3','Bed3','Surface3','Thickness3','Temperature3','SMB3','TotalSmb1'};
+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-10,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,...
+						1e-09,5e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
+
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(1).TotalSmb),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(2).TotalSmb),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	(md.results.TransientSolution(3).TotalSmb),...
+	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test330.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test330.m	(revision 12877)
+++ 	(revision )
@@ -1,47 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,5,1.2);
-md=setflowequation(md,'hutter','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
-field_tolerances={1e-13,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...,
-						1e-10,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-						1e-10,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test332.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test332.m	(revision 12877)
+++ 	(revision )
@@ -1,33 +1,0 @@
-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=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test334.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test334.m	(revision 12877)
+++ 	(revision )
@@ -1,47 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',200000);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      '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_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test336.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test336.m	(revision 12877)
+++ 	(revision )
@@ -1,22 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,4,1);
-md=setflowequation(md,'hutter','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
-md=solve(md,SteadystateSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13
-};
-field_values={...
-	(md.results.SteadystateSolution.Vx),...
-	(md.results.SteadystateSolution.Vy),...
-	(md.results.SteadystateSolution.Vz),...
-	(md.results.SteadystateSolution.Vel),...
-	(md.results.SteadystateSolution.Pressure),...
-	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test338.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test338.m	(revision 12877)
+++ 	(revision )
@@ -1,33 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',200000);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
-
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'FrictionCoefficient'};
-md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
-md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
-
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
-field_tolerances={1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
-	(md.results.DiagnosticSolution.FrictionCoefficient),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
-};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test340.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test340.m	(revision 12877)
+++ 	(revision )
@@ -1,34 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',200000);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'FrictionCoefficient'};
-md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
-md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
-
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
-field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
-field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
-	(md.results.DiagnosticSolution.FrictionCoefficient),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
-};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test342.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test342.m	(revision 12877)
+++ 	(revision )
@@ -1,34 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',200000);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
-
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'FrictionCoefficient'};
-md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=[102*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
-md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
-
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
-field_tolerances={1e-08,1e-07,1e-10,1e-10,1e-09,1e-09,1e-09};
-field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
-	(md.results.DiagnosticSolution.FrictionCoefficient),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
-};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test344.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test344.m	(revision 12877)
+++ 	(revision )
@@ -1,34 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',200000);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'stokes','all');
-
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'FrictionCoefficient'};
-md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=[104*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
-md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
-
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
-field_tolerances={1e-06,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
-field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
-	(md.results.DiagnosticSolution.FrictionCoefficient),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
-};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test346.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test346.m	(revision 12877)
+++ 	(revision )
@@ -1,35 +1,0 @@
-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.timestepping.time_adapt=1;
-md.timestepping.final_time=600;
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test348.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test348.m	(revision 12877)
+++ 	(revision )
@@ -1,49 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,5,1.2);
-md=setflowequation(md,'hutter','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_adapt=1;
-md.timestepping.final_time=500;
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
-					   %'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
-field_tolerances={1e-13,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...,
-						5*1e-11,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-						1e-10,  1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-%	(md.results.TransientSolution(3).Vx),...
-%	(md.results.TransientSolution(3).Vy),...
-%	(md.results.TransientSolution(3).Vz),...
-%	(md.results.TransientSolution(3).Vel),...
-%	(md.results.TransientSolution(3).Pressure),...
-%	(md.results.TransientSolution(3).Bed),...
-%	(md.results.TransientSolution(3).Surface),...
-%	(md.results.TransientSolution(3).Thickness),...
-%	(md.results.TransientSolution(3).Temperature),...
-%	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test350.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test350.m	(revision 12877)
+++ 	(revision )
@@ -1,18 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-md.timestepping.time_step=0;
-md.cluster=generic('name',oshostname(),'np',3);
-md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md=solve(md,EnthalpySolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Enthalpy','Waterfraction','Temperature'};
-field_tolerances={1e-13,1e-13,1e-13};
-field_values={...
-	(md.results.EnthalpySolution.Enthalpy),...
-	(md.results.EnthalpySolution.Waterfraction),...
-	(md.results.EnthalpySolution.Temperature),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test352.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test352.m	(revision 12877)
+++ 	(revision )
@@ -1,30 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
-md.transient.isthermal=1;
-md.transient.isgroundingline=0;
-md.thermal.isenthalpy=1;
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Enthalpy1','Waterfraction1','Temperature1',...
-	'Enthalpy2','Waterfraction2','Temperature2',...
-	'Enthalpy3','Waterfraction3','Temperature3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
-field_values={...
-	(md.results.TransientSolution(1).Enthalpy),...
-	(md.results.TransientSolution(1).Waterfraction),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(2).Enthalpy),...
-	(md.results.TransientSolution(2).Waterfraction),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(3).Enthalpy),...
-	(md.results.TransientSolution(3).Waterfraction),...
-	(md.results.TransientSolution(3).Temperature),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test354.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test354.m	(revision 12877)
+++ 	(revision )
@@ -1,55 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',200000);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md.initialization.temperature(:)=272;
-md.thermal.spctemperature(find(md.mesh.vertexonsurface))=272;
-md.thermal.isenthalpy=1;
-md.basalforcings.geothermalflux(:)=5;
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','Enthalpy1','Waterfraction1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','Enthalpy2','Waterfraction2', ...
-					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','Enthalpy3','Waterfraction3'};
-field_tolerances={1e-09,1e-09,1e-09,1e-10,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-10,...
-						1e-09,5e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10,1e-10};
-field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).Enthalpy),...
-	(md.results.TransientSolution(1).Waterfraction),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).Enthalpy),...
-	(md.results.TransientSolution(2).Waterfraction),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).Enthalpy),...
-	(md.results.TransientSolution(3).Waterfraction),...
-	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test401.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test401.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test401.m	(revision 12878)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test402.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test402.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test402.m	(revision 12878)
@@ -2,4 +2,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,4,1);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -7,9 +8,10 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	(md.results.DiagnosticSolution.Vx),...
 	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
 	(md.results.DiagnosticSolution.Vel),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test403.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test403.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test403.m	(revision 12878)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test404.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test404.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test404.m	(revision 12878)
@@ -1,7 +1,7 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',180000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,4,1);
-md=setflowequation(md,'macayeal','all');
+md=extrude(md,3,1);
+md=setflowequation(md,'stokes','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,DiagnosticSolutionEnum);
@@ -9,5 +9,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
+field_tolerances={1e-07,1e-07,1e-06,1e-07,1e-07};
 field_values={...
 	(md.results.DiagnosticSolution.Vx),...
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test405.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test405.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test405.m	(revision 12878)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','penalties');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-05,1e-05,1e-05,1e-05,1e-05};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test406.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test406.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test406.m	(revision 12878)
@@ -1,18 +1,16 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,5,1);
+md=extrude(md,4,1);
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md.timestepping.time_step=0;
+md=solve(md,ThermalSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test407.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test407.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test407.m	(revision 12878)
@@ -0,0 +1,19 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,4,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isdiagnostic=0;
+md.transient.isprognostic=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test408.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test408.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test408.m	(revision 12878)
@@ -1,18 +1,33 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-07,1e-07,1e-06,1e-07,1e-07};
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test409.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test409.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test409.m	(revision 12878)
@@ -0,0 +1,48 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','penalties');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
+					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
+field_tolerances={...
+	1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,...
+	1e-03,1e-03,1e-02,1e-03,1e-02,1e-04,1e-01,1e-03,1e-01,1e-01,...
+	1e-02,1e-02,1e-01,1e-02,1e-01,1e-04,1e-04,1e-04,1e-04,1e-01};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vz),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test410.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test410.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test410.m	(revision 12878)
@@ -1,18 +1,21 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,5,1);
-md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','penalties');
+md=extrude(md,3,2);
+md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
 
 %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_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-10,1e-10,1e-09,1e-10,1e-13,1e-10,1e-06};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test411.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test411.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test411.m	(revision 12878)
@@ -0,0 +1,22 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-09,1e-09,1e-08,1e-09,1e-09,1e-08,1e-05
+};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test412.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test412.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test412.m	(revision 12878)
@@ -1,16 +1,44 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',300000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,4,1);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
-md=solve(md,ThermalSolutionEnum);
+
+%partitioning
+md.qmu.numberofpartitions=md.mesh.numberofvertices;
+md=partitioner(md,'package','linear','npart',md.qmu.numberofpartitions);
+md.qmu.partition=md.qmu.partition-1;
+md.qmu.isdakota=1;
+
+
+%Dakota options
+%variables
+md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+%imperative! 
+md.diagnostic.reltol=10^-5; %tighten for qmu analysese
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13};
+md=tres(md,'dakota');
+md.results.dakota.importancefactors=importancefactors(md,'scaled_FrictionCoefficient','MaxVel')';
+field_names     ={'importancefactors'};
+field_tolerances={1e-10};
 field_values={...
-	(md.results.ThermalSolution.Temperature),...
-	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+         md.results.dakota.importancefactors,...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test413.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test413.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test413.m	(revision 12878)
@@ -0,0 +1,45 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+
+%imperative!
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+md.qmu.isdakota=1;
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+
+%Fields and tolerances to track changes
+md=tres(md,'dakota');
+md.results.dakota.importancefactors=importancefactors(md,'scaled_FrictionCoefficient','MaxVel')';
+field_names     ={'importancefactors'};
+field_tolerances={1e-10};
+field_values={...
+         md.results.dakota.importancefactors,...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test414.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test414.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test414.m	(revision 12878)
@@ -2,18 +2,69 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,4,1);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
-md.transient.isthermal=1;
-md.transient.isgroundingline=0;
-md=solve(md,TransientSolutionEnum);
+md.materials.rho_ice=10^7; %involved in the mass flux, make it easy
+md.geometry.thickness(:)=1; %make it easy
+
+%constrain all velocities to 1 m/yr, in the y-direction
+md.diagnostic.spcvx=zeros(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=zeros(md.mesh.numberofvertices,1);
+
+%Dakota options
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+
+%variables
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp','../Exp/Square.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+md.qmu.isdakota=1;
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=tres(md,'dakota');
 
 %Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13};
+%ok, mass flux of 3 profiles should be -3 Gt/yr -3 Gt/yr and the sum, which is -6 Gt/yr
+%we recover those mass fluxes through the mean of the response.
+%also, we recover the max velo, which should be 1m/yr. 
+%we put all that data in the importancefactors, which we will use to test for success.
+%also, check that the stddev are 0.
+md.results.dakota.importancefactors=[];
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'importancefactors'};
+field_tolerances={1e-11};
 field_values={...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+         md.results.dakota.importancefactors,...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test415.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test415.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test415.m	(revision 12878)
@@ -0,0 +1,38 @@
+md=triangle(model,'../Exp/Square.exp',170000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.timestepping.time_step=0;
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
+field_tolerances={1e-10,1e-10,1e-11,1e-13,1e-10,1e-09,1e-10,1e-8,1e-09,1e-6};
+field_values={...
+	(md.results.SteadystateSolution.Gradient1),...
+	md.results.SteadystateSolution.J,...
+	(md.results.SteadystateSolution.FrictionCoefficient),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test416.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test416.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test416.m	(revision 12878)
@@ -1,33 +1,38 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',170000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[102*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.timestepping.time_step=0;
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+md=solve(md,SteadystateSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
+field_tolerances={1e-08,1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-07,1e-08,1e-05};
 field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	};
+	(md.results.SteadystateSolution.Gradient1),...
+	md.results.SteadystateSolution.J,...
+	(md.results.SteadystateSolution.FrictionCoefficient),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test417.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test417.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test417.m	(revision 12878)
@@ -0,0 +1,73 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.materials.rho_ice=10^7; %involved in the mass flux, make it easy
+md.geometry.thickness(:)=1; %make it easy
+
+%constrain all velocities to 1 m/yr, in the y-direction
+md.diagnostic.spcvx(:)=0;
+md.diagnostic.spcvy(:)=1;
+md.diagnostic.spcvz(:)=0;
+
+%Dakota options
+md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
+
+md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%mass flux profiles
+md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp','../Exp/Square.exp'};
+md.qmu.mass_flux_profile_directory=pwd;
+
+
+%%  nond_sampling study
+
+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');
+
+%%  a variety of parameters
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.analysis_driver='';
+md.qmu.params.analysis_components='';
+
+%partitioning
+md.qmu.numberofpartitions=20;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
+md.qmu.partition=md.qmu.partition-1;
+md.qmu.isdakota=1;
+
+md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+
+%Fields and tolerances to track changes
+md=tres(md,'dakota');
+
+%ok, mass flux of 3 profiles should be -3 Gt/yr -3 Gt/yr and the sum, which is -6 Gt/yr
+%we recover those mass fluxes through the mean of the response.
+%also, we recover the max velo, which should be 1m/yr. 
+%we put all that data in the montecarlo field, which we will use to test for success.
+%also, check that the stddev are 0.
+md.results.dakota.montecarlo=[];
+for i=1:8,
+	md.results.dakota.montecarlo=[md.results.dakota.montecarlo md.results.dakota.dresp_out(i).mean];
+end
+for i=1:8,
+	md.results.dakota.montecarlo=[md.results.dakota.montecarlo md.results.dakota.dresp_out(i).stddev];
+end
+field_names     ={'montecarlo'};
+field_tolerances={1e-11};
+field_values={...
+         md.results.dakota.montecarlo,...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test418.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test418.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test418.m	(revision 12878)
@@ -1,48 +1,21 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+%test partitioning, and partition averaging
+md=triangle(model,'../Exp/Square.exp',30000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','penalties');
+md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
 
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', ...
-					   'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3'};
-field_tolerances={...
-	1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,1e-05,...
-	1e-03,1e-03,1e-02,1e-03,1e-02,1e-04,1e-01,1e-03,1e-01,1e-01,...
-	1e-02,1e-02,1e-01,1e-02,1e-01,1e-04,1e-04,1e-04,1e-04,1e-01};
+%partitioning
+md.qmu.numberofpartitions=100;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions);
+md.qmu.partition=md.qmu.partition-1;
+
+vector=(1:1:md.mesh.numberofvertices)';
+vector_on_partition=AreaAverageOntoPartition(md,vector);
+vector_on_nodes=vector_on_partition(md.qmu.partition+1);
+
+field_names     ={'vector_on_nodes'};
+field_tolerances={1e-11};
 field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(3).Vx),...
-	(md.results.TransientSolution(3).Vy),...
-	(md.results.TransientSolution(3).Vz),...
-	(md.results.TransientSolution(3).Vel),...
-	(md.results.TransientSolution(3).Pressure),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+         vector_on_nodes,...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test419.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test419.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test419.m	(revision 12878)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test420.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test420.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test420.m	(revision 12878)
@@ -1,21 +1,49 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',200000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,3,2);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
-md=solve(md,SteadystateSolutionEnum);
+
+%partitioning
+md.qmu.numberofpartitions=10;
+md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions);
+md.qmu.partition=md.qmu.partition-1;
+md.qmu.isdakota=1;
+
+%Dakota options
+%variables
+md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
+
+%responses
+md.qmu.responses.MaxVel=response_function('scaled_Thickness',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
+
+%method
+md.qmu.method     =dakota_method('nond_l');
+
+%parameters
+md.qmu.params.direct=true;
+md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.evaluation_concurrency=1;
+md.qmu.params.interval_type='forward';
+
+
+%imperative! 
+md.diagnostic.reltol=10^-5; %tighten for qmu analysese
+
+%solve
+md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=tres(md,'dakota');
+
+%test on thickness
+h=zeros(md.qmu.numberofpartitions,1);
+for i=1:md.qmu.numberofpartitions,
+	h(i)=md.qmu.results.dresp_out(i).mean;
+end
+
+%project onto grid
+thickness=h(md.qmu.partition+1);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-10,1e-10,1e-09,1e-10,1e-13,1e-10,1e-06};
-field_values={...
-	(md.results.SteadystateSolution.Vx),...
-	(md.results.SteadystateSolution.Vy),...
-	(md.results.SteadystateSolution.Vz),...
-	(md.results.SteadystateSolution.Vel),...
-	(md.results.SteadystateSolution.Pressure),...
-	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
-	};
+field_names     ={'Thickness'};
+field_tolerances={1e-10};
+field_values={thickness};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test421.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test421.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test421.m	(revision 12878)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-09,2e-05,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test422.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test422.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test422.m	(revision 12878)
@@ -1,22 +1,19 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',180000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,3,2);
-md=setflowequation(md,'pattyn','all');
+md=extrude(md,5,1);
+md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','macayeal');
 md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
-md=solve(md,SteadystateSolutionEnum);
+md.diagnostic.reltol=0.4;
+md=solve(md,DiagnosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-09,1e-09,1e-08,1e-09,1e-09,1e-08,1e-05
-};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
 field_values={...
-	(md.results.SteadystateSolution.Vx),...
-	(md.results.SteadystateSolution.Vy),...
-	(md.results.SteadystateSolution.Vz),...
-	(md.results.SteadystateSolution.Vel),...
-	(md.results.SteadystateSolution.Pressure),...
-	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test423.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test423.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test423.m	(revision 12878)
@@ -0,0 +1,37 @@
+radius=1e6;
+shelfextent=2e5;
+
+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.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);
+
+%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};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test424.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test424.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test424.m	(revision 12878)
@@ -1,44 +1,40 @@
-md=triangle(model,'../Exp/Square.exp',300000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=setflowequation(md,'macayeal','all');
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.thickness(:)=1000;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md.surfaceforcings.mass_balance(:)=100;
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='AgressiveMigration';
+
 md.cluster=generic('name',oshostname(),'np',3);
-
-%partitioning
-md.qmu.numberofpartitions=md.mesh.numberofvertices;
-md=partitioner(md,'package','linear','npart',md.qmu.numberofpartitions);
-md.qmu.partition=md.qmu.partition-1;
-md.qmu.isdakota=1;
-
-
-%Dakota options
-%variables
-md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
-md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
-
-%responses
-md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-
-%method
-md.qmu.method     =dakota_method('nond_l');
-
-%parameters
-md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='diagnostic';
-md.qmu.params.evaluation_concurrency=1;
-md.qmu.params.interval_type='forward';
-
-%imperative! 
-md.diagnostic.reltol=10^-5; %tighten for qmu analysese
-
-%solve
-md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-md=tres(md,'dakota');
-md.results.dakota.importancefactors=importancefactors(md,'scaled_FrictionCoefficient','MaxVel')';
-field_names     ={'importancefactors'};
-field_tolerances={1e-10};
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+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.dakota.importancefactors,...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskElementonfloatingice),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test425.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test425.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test425.m	(revision 12878)
@@ -0,0 +1,40 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'macayeal','all');
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.thickness(:)=1300;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md.surfaceforcings.mass_balance(:)=-150;
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='SoftMigration';
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+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.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test426.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test426.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test426.m	(revision 12878)
@@ -1,45 +1,42 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model,'../Exp/Square.exp',350000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.thickness(:)=1000;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md.surfaceforcings.mass_balance(:)=100;
+md=extrude(md,3,1);
 md=setflowequation(md,'macayeal','all');
+
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='AgressiveMigration';
 md.cluster=generic('name',oshostname(),'np',3);
 
-%Dakota options
-
-%partitioning
-md.qmu.numberofpartitions=20;
-md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
-md.qmu.partition=md.qmu.partition-1;
-
-%variables
-md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
-md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
-
-%responses
-md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-
-%method
-md.qmu.method     =dakota_method('nond_l');
-
-%parameters
-md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='diagnostic';
-md.qmu.params.evaluation_concurrency=1;
-md.qmu.params.interval_type='forward';
-
-
-%imperative!
-md.diagnostic.reltol=10^-5; %tighten for qmu analyses
-md.qmu.isdakota=1;
-
-%solve
-md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-md=tres(md,'dakota');
-md.results.dakota.importancefactors=importancefactors(md,'scaled_FrictionCoefficient','MaxVel')';
-field_names     ={'importancefactors'};
-field_tolerances={1e-10};
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-11,1e-11,1e-11,1e-13,...
+	1e-10,1e-10,1e-10,1e-13};
 field_values={...
-         md.results.dakota.importancefactors,...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskElementonfloatingice),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test427.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test427.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test427.m	(revision 12878)
@@ -0,0 +1,41 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md.initialization.vel(:)=0;
+md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
+md.geometry.thickness(:)=1300;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md=setflowequation(md,'macayeal','all');
+md=extrude(md,3,1);
+
+md.surfaceforcings.mass_balance(:)=-150;
+md.transient.isdiagnostic=0;
+md.transient.isgroundingline=1;
+md.groundingline.migration='SoftMigration';
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
+	'Bed2','Surface2','Thickness2','Floatingice2',...
+	'Bed3','Surface3','Thickness3','Floatingice3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13,1e-13,...
+	1e-10,1e-11,1e-10,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).Bed),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test428.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test428.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test428.m	(revision 12878)
@@ -3,68 +3,16 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=setflowequation(md,'macayeal','all');
+md.diagnostic.isnewton=1;
+md.diagnostic.restol=0.0001;
 md.cluster=generic('name',oshostname(),'np',3);
-md.materials.rho_ice=10^7; %involved in the mass flux, make it easy
-md.geometry.thickness(:)=1; %make it easy
-
-%constrain all velocities to 1 m/yr, in the y-direction
-md.diagnostic.spcvx=zeros(md.mesh.numberofvertices,1);
-md.diagnostic.spcvy=ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvz=zeros(md.mesh.numberofvertices,1);
-
-%Dakota options
-
-%partitioning
-md.qmu.numberofpartitions=20;
-md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
-md.qmu.partition=md.qmu.partition-1;
-
-%variables
-md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
-
-%responses
-md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-
-%mass flux profiles
-md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp','../Exp/Square.exp'};
-md.qmu.mass_flux_profile_directory=pwd;
-
-%method
-md.qmu.method     =dakota_method('nond_l');
-
-%parameters
-md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='diagnostic';
-md.qmu.params.evaluation_concurrency=1;
-md.qmu.params.interval_type='forward';
-md.qmu.isdakota=1;
-md.diagnostic.reltol=10^-5; %tighten for qmu analyses
-
-%solve
-md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
-md=tres(md,'dakota');
+md=solve(md,DiagnosticSolutionEnum);
 
 %Fields and tolerances to track changes
-%ok, mass flux of 3 profiles should be -3 Gt/yr -3 Gt/yr and the sum, which is -6 Gt/yr
-%we recover those mass fluxes through the mean of the response.
-%also, we recover the max velo, which should be 1m/yr. 
-%we put all that data in the importancefactors, which we will use to test for success.
-%also, check that the stddev are 0.
-md.results.dakota.importancefactors=[];
-for i=1:8,
-	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).mean];
-end
-for i=1:8,
-	md.results.dakota.importancefactors=[md.results.dakota.importancefactors md.results.dakota.dresp_out(i).stddev];
-end
-field_names     ={'importancefactors'};
-field_tolerances={1e-11};
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
 field_values={...
-         md.results.dakota.importancefactors,...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test429.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test429.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test429.m	(revision 12878)
@@ -0,0 +1,20 @@
+md=triangle(model,'../Exp/Square.exp',180000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1);
+md=setflowequation(md,'pattyn','all');
+md.diagnostic.isnewton=1;
+md.diagnostic.restol=0.0001;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test430.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test430.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test430.m	(revision 12878)
@@ -1,38 +1,20 @@
-md=triangle(model,'../Exp/Square.exp',170000);
+md=triangle(model,'../Exp/Square.exp',180000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'FrictionCoefficient'};
-md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
-md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
-md.timestepping.time_step=0;
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
-
+md=setflowequation(md,'stokes','all');
+md.diagnostic.isnewton=1;
+md.diagnostic.restol=0.0001;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,SteadystateSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
-field_tolerances={1e-10,1e-10,1e-11,1e-13,1e-10,1e-09,1e-10,1e-8,1e-09,1e-6};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-07,1e-07,1e-06,1e-07,1e-07};
 field_values={...
-	(md.results.SteadystateSolution.Gradient1),...
-	md.results.SteadystateSolution.J,...
-	(md.results.SteadystateSolution.FrictionCoefficient),...
-	(md.results.SteadystateSolution.Pressure),...
-	(md.results.SteadystateSolution.Vel),...
-	(md.results.SteadystateSolution.Vx),...
-	(md.results.SteadystateSolution.Vy),...
-	(md.results.SteadystateSolution.Vz),...
-	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
-};
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test431.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test431.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test431.m	(revision 12878)
@@ -0,0 +1,24 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,2);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0;
+md.thermal.isenthalpy=1;
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','Water fraction','Enthalpy'};
+field_tolerances={1e-10,1e-10,1e-09,1e-10,1e-13,1e-10,1e-10,1e-10};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.Waterfraction),...
+	(md.results.SteadystateSolution.Enthalpy),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test432.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test432.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test432.m	(revision 12878)
@@ -1,38 +1,24 @@
-md=triangle(model,'../Exp/Square.exp',170000);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,3,1);
+md=extrude(md,3,2);
 md=setflowequation(md,'pattyn','all');
-
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'FrictionCoefficient'};
-md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=[102*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
-md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.3*ones(md.inversion.nsteps,1);
+md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_step=0;
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
-
-md.cluster=generic('name',oshostname(),'np',3);
+md.thermal.isenthalpy=1;
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
 md=solve(md,SteadystateSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
-field_tolerances={1e-08,1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-07,1e-08,1e-05};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','Water fraction','Enthalpy'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-13,1e-10,1e-10,1e-10};
 field_values={...
-	(md.results.SteadystateSolution.Gradient1),...
-	md.results.SteadystateSolution.J,...
-	(md.results.SteadystateSolution.FrictionCoefficient),...
-	(md.results.SteadystateSolution.Pressure),...
-	(md.results.SteadystateSolution.Vel),...
 	(md.results.SteadystateSolution.Vx),...
 	(md.results.SteadystateSolution.Vy),...
 	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
 	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
-};
+	(md.results.SteadystateSolution.Waterfraction),...
+	(md.results.SteadystateSolution.Enthalpy),...
+	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test434.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test434.m	(revision 12877)
+++ 	(revision )
@@ -1,73 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.materials.rho_ice=10^7; %involved in the mass flux, make it easy
-md.geometry.thickness(:)=1; %make it easy
-
-%constrain all velocities to 1 m/yr, in the y-direction
-md.diagnostic.spcvx(:)=0;
-md.diagnostic.spcvy(:)=1;
-md.diagnostic.spcvz(:)=0;
-
-%Dakota options
-md.qmu.variables.drag_coefficient=normal_uncertain('scaled_FrictionCoefficient',1,0.01);
-
-md.qmu.responses.MaxVel=response_function('MaxVel',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux1=response_function('indexed_MassFlux_1',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux2=response_function('indexed_MassFlux_2',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux3=response_function('indexed_MassFlux_3',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux4=response_function('indexed_MassFlux_4',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux5=response_function('indexed_MassFlux_5',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux6=response_function('indexed_MassFlux_6',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-md.qmu.responses.MassFlux7=response_function('indexed_MassFlux_7',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-
-%mass flux profiles
-md.qmu.mass_flux_profiles={'../Exp/MassFlux1.exp','../Exp/MassFlux2.exp','../Exp/MassFlux3.exp','../Exp/MassFlux4.exp','../Exp/MassFlux5.exp','../Exp/MassFlux6.exp','../Exp/Square.exp'};
-md.qmu.mass_flux_profile_directory=pwd;
-
-
-%%  nond_sampling study
-
-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');
-
-%%  a variety of parameters
-md.qmu.params.evaluation_concurrency=1;
-md.qmu.params.analysis_driver='';
-md.qmu.params.analysis_components='';
-
-%partitioning
-md.qmu.numberofpartitions=20;
-md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions,'weighting','on');
-md.qmu.partition=md.qmu.partition-1;
-md.qmu.isdakota=1;
-
-md.diagnostic.reltol=10^-5; %tighten for qmu analyses
-
-md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
-
-%Fields and tolerances to track changes
-md=tres(md,'dakota');
-
-%ok, mass flux of 3 profiles should be -3 Gt/yr -3 Gt/yr and the sum, which is -6 Gt/yr
-%we recover those mass fluxes through the mean of the response.
-%also, we recover the max velo, which should be 1m/yr. 
-%we put all that data in the montecarlo field, which we will use to test for success.
-%also, check that the stddev are 0.
-md.results.dakota.montecarlo=[];
-for i=1:8,
-	md.results.dakota.montecarlo=[md.results.dakota.montecarlo md.results.dakota.dresp_out(i).mean];
-end
-for i=1:8,
-	md.results.dakota.montecarlo=[md.results.dakota.montecarlo md.results.dakota.dresp_out(i).stddev];
-end
-field_names     ={'montecarlo'};
-field_tolerances={1e-11};
-field_values={...
-         md.results.dakota.montecarlo,...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test438.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test438.m	(revision 12877)
+++ 	(revision )
@@ -1,18 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,5,1);
-md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
-field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test440.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test440.m	(revision 12877)
+++ 	(revision )
@@ -1,49 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',200000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-
-%partitioning
-md.qmu.numberofpartitions=10;
-md=partitioner(md,'package','chaco','npart',md.qmu.numberofpartitions);
-md.qmu.partition=md.qmu.partition-1;
-md.qmu.isdakota=1;
-
-%Dakota options
-%variables
-md.qmu.variables.rho_ice=normal_uncertain('MaterialsRhoIce',md.materials.rho_ice,0.01);
-
-%responses
-md.qmu.responses.MaxVel=response_function('scaled_Thickness',[],[0.0001 0.001 0.01 0.25 0.5 0.75 0.99 0.999 0.9999]);
-
-%method
-md.qmu.method     =dakota_method('nond_l');
-
-%parameters
-md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='diagnostic';
-md.qmu.params.evaluation_concurrency=1;
-md.qmu.params.interval_type='forward';
-
-
-%imperative! 
-md.diagnostic.reltol=10^-5; %tighten for qmu analysese
-
-%solve
-md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
-md=tres(md,'dakota');
-
-%test on thickness
-h=zeros(md.qmu.numberofpartitions,1);
-for i=1:md.qmu.numberofpartitions,
-	h(i)=md.qmu.results.dresp_out(i).mean;
-end
-
-%project onto grid
-thickness=h(md.qmu.partition+1);
-
-%Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-10};
-field_values={thickness};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test442.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test442.m	(revision 12877)
+++ 	(revision )
@@ -1,18 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,5,1);
-md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-08,1e-09,1e-05,1e-09,1e-09};
-field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test444.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test444.m	(revision 12877)
+++ 	(revision )
@@ -1,19 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,5,1);
-md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','macayeal');
-md.cluster=generic('name',oshostname(),'np',3);
-md.diagnostic.reltol=0.4;
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
-field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test446.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test446.m	(revision 12877)
+++ 	(revision )
@@ -1,37 +1,0 @@
-radius=1e6;
-shelfextent=2e5;
-
-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.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);
-
-%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};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test448.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test448.m	(revision 12877)
+++ 	(revision )
@@ -1,40 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.initialization.vx(:)=0;
-md.initialization.vy(:)=0;
-md.initialization.vel(:)=0;
-md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
-md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
-md.geometry.thickness(:)=1000;
-md.geometry.surface=md.geometry.bed+md.geometry.thickness;
-md.surfaceforcings.mass_balance(:)=100;
-md.transient.isdiagnostic=0;
-md.transient.isgroundingline=1;
-md.groundingline.migration='AgressiveMigration';
-
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
-	'Bed2','Surface2','Thickness2','Floatingice2',...
-	'Bed3','Surface3','Thickness3','Floatingice3'};
-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.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).MaskElementonfloatingice),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).MaskElementonfloatingice),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).MaskElementonfloatingice),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test450.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test450.m	(revision 12877)
+++ 	(revision )
@@ -1,40 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.initialization.vx(:)=0;
-md.initialization.vy(:)=0;
-md.initialization.vel(:)=0;
-md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
-md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
-md.geometry.thickness(:)=1300;
-md.geometry.surface=md.geometry.bed+md.geometry.thickness;
-md.surfaceforcings.mass_balance(:)=-150;
-md.transient.isdiagnostic=0;
-md.transient.isgroundingline=1;
-md.groundingline.migration='SoftMigration';
-
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
-	'Bed2','Surface2','Thickness2','Floatingice2',...
-	'Bed3','Surface3','Thickness3','Floatingice3'};
-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.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).MaskElementonfloatingice),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).MaskElementonfloatingice),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).MaskElementonfloatingice),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test452.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test452.m	(revision 12877)
+++ 	(revision )
@@ -1,42 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',350000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md.initialization.vx(:)=0;
-md.initialization.vy(:)=0;
-md.initialization.vel(:)=0;
-md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
-md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
-md.geometry.thickness(:)=1000;
-md.geometry.surface=md.geometry.bed+md.geometry.thickness;
-md.surfaceforcings.mass_balance(:)=100;
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-
-md.transient.isdiagnostic=0;
-md.transient.isgroundingline=1;
-md.groundingline.migration='AgressiveMigration';
-md.cluster=generic('name',oshostname(),'np',3);
-
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
-	'Bed2','Surface2','Thickness2','Floatingice2',...
-	'Bed3','Surface3','Thickness3','Floatingice3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,...
-	1e-11,1e-11,1e-11,1e-13,...
-	1e-10,1e-10,1e-10,1e-13};
-field_values={...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).MaskElementonfloatingice),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).MaskElementonfloatingice),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).MaskElementonfloatingice),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test454.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test454.m	(revision 12877)
+++ 	(revision )
@@ -1,41 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md.initialization.vx(:)=0;
-md.initialization.vy(:)=0;
-md.initialization.vel(:)=0;
-md.geometry.bed=-700-abs(md.mesh.y-500000)/1000;
-md.geometry.bathymetry=-700-abs(md.mesh.y-500000)/1000;
-md.geometry.thickness(:)=1300;
-md.geometry.surface=md.geometry.bed+md.geometry.thickness;
-md=setflowequation(md,'macayeal','all');
-md=extrude(md,3,1);
-
-md.surfaceforcings.mass_balance(:)=-150;
-md.transient.isdiagnostic=0;
-md.transient.isgroundingline=1;
-md.groundingline.migration='SoftMigration';
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Bed1','Surface1','Thickness1','Floatingice1',...
-	'Bed2','Surface2','Thickness2','Floatingice2',...
-	'Bed3','Surface3','Thickness3','Floatingice3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,...
-	1e-13,1e-13,1e-13,1e-13,...
-	1e-10,1e-11,1e-10,1e-13};
-field_values={...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).MaskElementonfloatingice),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).MaskElementonfloatingice),...
-	(md.results.TransientSolution(3).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).MaskElementonfloatingice),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test456.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test456.m	(revision 12877)
+++ 	(revision )
@@ -1,18 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.diagnostic.isnewton=1;
-md.diagnostic.restol=0.0001;
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13};
-field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test458.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test458.m	(revision 12877)
+++ 	(revision )
@@ -1,20 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,5,1);
-md=setflowequation(md,'pattyn','all');
-md.diagnostic.isnewton=1;
-md.diagnostic.restol=0.0001;
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
-field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test460.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test460.m	(revision 12877)
+++ 	(revision )
@@ -1,20 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'stokes','all');
-md.diagnostic.isnewton=1;
-md.diagnostic.restol=0.0001;
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-07,1e-07,1e-06,1e-07,1e-07};
-field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test462.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test462.m	(revision 12877)
+++ 	(revision )
@@ -1,24 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,3,2);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
-md.thermal.isenthalpy=1;
-md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md=solve(md,SteadystateSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','Water fraction','Enthalpy'};
-field_tolerances={1e-10,1e-10,1e-09,1e-10,1e-13,1e-10,1e-10,1e-10};
-field_values={...
-	(md.results.SteadystateSolution.Vx),...
-	(md.results.SteadystateSolution.Vy),...
-	(md.results.SteadystateSolution.Vz),...
-	(md.results.SteadystateSolution.Vel),...
-	(md.results.SteadystateSolution.Pressure),...
-	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.Waterfraction),...
-	(md.results.SteadystateSolution.Enthalpy),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test464.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test464.m	(revision 12877)
+++ 	(revision )
@@ -1,24 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,3,2);
-md=setflowequation(md,'pattyn','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
-md.thermal.isenthalpy=1;
-md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md=solve(md,SteadystateSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','Water fraction','Enthalpy'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-13,1e-10,1e-10,1e-10};
-field_values={...
-	(md.results.SteadystateSolution.Vx),...
-	(md.results.SteadystateSolution.Vy),...
-	(md.results.SteadystateSolution.Vz),...
-	(md.results.SteadystateSolution.Vel),...
-	(md.results.SteadystateSolution.Pressure),...
-	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.Waterfraction),...
-	(md.results.SteadystateSolution.Enthalpy),...
-	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test501.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test501.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test501.m	(revision 12878)
@@ -0,0 +1,16 @@
+md=triangle(model,'../Exp/Pig.exp',20000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test502.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test502.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test502.m	(revision 12878)
@@ -2,14 +2,16 @@
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
-md=setflowequation(md,'macayeal','all');
+md=extrude(md,3,0.9);
+md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,DiagnosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08};
 field_values={...
 	(md.results.DiagnosticSolution.Vx),...
 	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
 	(md.results.DiagnosticSolution.Vel),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test503.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test503.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test503.m	(revision 12878)
@@ -0,0 +1,18 @@
+md=triangle(model,'../Exp/Pig.exp',20000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,0.9);
+md=setflowequation(md,'stokes','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test504.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test504.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test504.m	(revision 12878)
@@ -2,17 +2,25 @@
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,3,0.9);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08};
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test505.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test505.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test505.m	(revision 12878)
@@ -0,0 +1,34 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test506.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test506.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test506.m	(revision 12878)
@@ -1,18 +1,35 @@
-md=triangle(model,'../Exp/Pig.exp',20000);
+md=triangle(model,'../Exp/Pig.exp',30000);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,3,0.9);
-md=setflowequation(md,'stokes','all');
+md=extrude(md,2,1);
+md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,1e-12,1e-11,1e-12,1e-12,...
+						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,1e-08};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test507.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test507.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test507.m	(revision 12878)
@@ -0,0 +1,35 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,2,1);
+md=setflowequation(md,'stokes','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+%The thickness wants to be lower than 1 so we contrain it to 1
+field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
+				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
+field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vz),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Bed),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vz),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Bed),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test508.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test508.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test508.m	(revision 12878)
@@ -1,26 +1,22 @@
-md=triangle(model,'../Exp/Pig.exp',20000);
+md=triangle(model,'../Exp/Pig.exp',30000);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,4,1.1);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-08
+};
 field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test509.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test509.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test509.m	(revision 12878)
@@ -0,0 +1,22 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06
+};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test510.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test510.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test510.m	(revision 12878)
@@ -1,34 +1,22 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
+md=triangle(model,'../Exp/Pig.exp',20000);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
+md=extrude(md,2,1);
+md=setflowequation(md,'stokes','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+md.timestepping.time_step=0;
+md=solve(md,SteadystateSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
-field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-12,1e-12,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06
+};
 field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test511.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test511.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test511.m	(revision 12878)
@@ -0,0 +1,39 @@
+md=triangle(model,'../Exp/Pig.exp',10000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+
+%impose hydrostatic equilibrium (required by Stokes)
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md=extrude(md,3,1);
+md=setflowequation(md,'stokes','all');
+md=modelextract(md,md.mask.elementonfloatingice);
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10^8*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyB' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-11,1e-12,1e-12,1e-09,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.MaterialsRheologyB),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test512.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test512.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test512.m	(revision 12878)
@@ -1,35 +1,34 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
+md=triangle(model,'../Exp/Pig.exp',20000);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,2,1);
+md=extrude(md,3,1);
 md=setflowequation(md,'pattyn','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
-field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,1e-12,1e-11,1e-12,1e-12,...
-						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,1e-08};
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+field_tolerances={1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11};
 field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	};
+	(md.results.DiagnosticSolution.Gradient1),...
+	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.FrictionCoefficient),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test513.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test513.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test513.m	(revision 12878)
@@ -0,0 +1,39 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
+md.inversion.nsteps=2;
+md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
+md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+md.timestepping.time_step=0;
+
+md.thermal.penalty_lock=5;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SteadystateSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
+field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-6,1e-6,1e-6,1e-6,1e-6,1e-06};
+field_values={...
+	(md.results.SteadystateSolution.Gradient1),...
+	md.results.SteadystateSolution.J,...
+	(md.results.SteadystateSolution.FrictionCoefficient),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test514.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test514.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test514.m	(revision 12878)
@@ -1,35 +1,56 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
+%Simple mesh 1
+hVertices=10000*ones(27,1);
+hVertices(1:5)=1000;
+md=bamg(model,'domain','../Exp/Pig.exp','hmax',20000,'hVertices',hVertices,'gradation',3,'geometricalmetric',1);
+x1=md.mesh.x;
+y1=md.mesh.y;
+
+%Simple mesh 2
+md=bamg(model,'domain','../Exp/Pig.exp','hmax',10000);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,2,1);
-md=setflowequation(md,'stokes','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+x2=md.mesh.x;
+y2=md.mesh.y;
+
+%refine existing mesh 1
+hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,md.inversion.vy_obs,'node');
+metric=ComputeMetric(hessian,2/9,1,1000,25*10^3,[]);
+md.miscellaneous.dummy=metric;
+md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1);
+x3=md2.mesh.x;
+y3=md2.mesh.y;
+
+%refine existing mesh 2
+md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1,'anisomax',1);
+x4=md2.mesh.x;
+y4=md2.mesh.y;
+
+%refine existing mesh 3
+hVertices=NaN*ones(md.mesh.numberofvertices,1);
+hVertices(find(md.mesh.vertexonboundary))=500;
+md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1,'anisomax',1,'hVertices',hVertices);
+x5=md2.mesh.x;
+y5=md2.mesh.y;
+
+%refine existing mesh 4
+md2=bamg(md,'field',md.inversion.vy_obs,'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1,'Hessiantype',0,'err',1);
+x6=md2.mesh.x;
+y6=md2.mesh.y;
+
+%refine existing mesh 5
+md2=bamg(md,'field',[md.inversion.vy_obs md.geometry.thickness],'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1,'Hessiantype',1,'err',[10 100]); 
+x7=md2.mesh.x;
+y7=md2.mesh.y;
 
 %Fields and tolerances to track changes
-%The thickness wants to be lower than 1 so we contrain it to 1
-field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
-				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
-field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06,1e-06};
+field_names     ={'x1' 'y1' 'x2' 'y2' 'x3' 'y3' 'x4' 'y4' 'x5' 'y5' 'x6' 'y6'  'x7' 'y7' };
+field_tolerances={1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13};
 field_values={...
-	(md.results.TransientSolution(1).Vx),...
-	(md.results.TransientSolution(1).Vy),...
-	(md.results.TransientSolution(1).Vz),...
-	(md.results.TransientSolution(1).Vel),...
-	(md.results.TransientSolution(1).Pressure),...
-	(md.results.TransientSolution(1).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Vx),...
-	(md.results.TransientSolution(2).Vy),...
-	(md.results.TransientSolution(2).Vz),...
-	(md.results.TransientSolution(2).Vel),...
-	(md.results.TransientSolution(2).Pressure),...
-	(md.results.TransientSolution(2).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	x1, y1,...
+	y2, y2,...
+	y3, y3,...
+	y4, y4,...
+	y5, y5,...
+	y6, y6,...
+	y7, y7,...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test515.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test515.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test515.m	(revision 12878)
@@ -0,0 +1,23 @@
+md=triangle(model,'../Exp/Pig.exp',30000);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.thermal.stabilization=2;
+md.cluster=generic('name',oshostname(),'np',3);
+md.transient.isdiagnostic=0;
+md.transient.isprognostic=0;
+md.transient.isthermal=1;
+md.transient.isgroundingline=0;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature1','BasalforcingsMeltingRate1', ...
+				      'Temperature2','BasalforcingsMeltingRate2'};
+field_tolerances={1e-13,1e-8,1e-13,1e-8};
+field_values={...
+	(md.results.TransientSolution(1).Temperature),...
+	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test516.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test516.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test516.m	(revision 12878)
@@ -2,21 +2,17 @@
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,4,1.1);
-md=setflowequation(md,'macayeal','all');
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.thermal.stabilization=2;
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_step=0;
-md=solve(md,SteadystateSolutionEnum);
+md.thermal.penalty_threshold=40;
+md=solve(md,ThermalSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-08
-};
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-11,1e-11};
 field_values={...
-	(md.results.SteadystateSolution.Vx),...
-	(md.results.SteadystateSolution.Vy),...
-	(md.results.SteadystateSolution.Vz),...
-	(md.results.SteadystateSolution.Vel),...
-	(md.results.SteadystateSolution.Pressure),...
-	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
 	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test518.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test518.m	(revision 12877)
+++ 	(revision )
@@ -1,22 +1,0 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
-md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
-md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
-md=solve(md,SteadystateSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06
-};
-field_values={...
-	(md.results.SteadystateSolution.Vx),...
-	(md.results.SteadystateSolution.Vy),...
-	(md.results.SteadystateSolution.Vz),...
-	(md.results.SteadystateSolution.Vel),...
-	(md.results.SteadystateSolution.Pressure),...
-	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test520.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test520.m	(revision 12877)
+++ 	(revision )
@@ -1,22 +1,0 @@
-md=triangle(model,'../Exp/Pig.exp',20000);
-md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
-md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,2,1);
-md=setflowequation(md,'stokes','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
-md=solve(md,SteadystateSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06
-};
-field_values={...
-	(md.results.SteadystateSolution.Vx),...
-	(md.results.SteadystateSolution.Vy),...
-	(md.results.SteadystateSolution.Vz),...
-	(md.results.SteadystateSolution.Vel),...
-	(md.results.SteadystateSolution.Pressure),...
-	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test522.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test522.m	(revision 12877)
+++ 	(revision )
@@ -1,39 +1,0 @@
-md=triangle(model,'../Exp/Pig.exp',10000);
-md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
-md=parameterize(md,'../Par/Pig.par');
-
-%impose hydrostatic equilibrium (required by Stokes)
-md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
-md.geometry.surface=md.geometry.bed+md.geometry.thickness;
-md=extrude(md,3,1);
-md=setflowequation(md,'stokes','all');
-md=modelextract(md,md.mask.elementonfloatingice);
-
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'MaterialsRheologyBbar'};
-md.inversion.min_parameters=10^6*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=2*10^9*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=101*ones(md.inversion.nsteps,1);
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
-md.inversion.gradient_scaling=10^8*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
-
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyB' 'Pressure' 'Vel' 'Vx' 'Vy'};
-field_tolerances={1e-11,1e-12,1e-12,1e-09,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
-field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
-	(md.results.DiagnosticSolution.MaterialsRheologyB),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
-};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test524.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test524.m	(revision 12877)
+++ 	(revision )
@@ -1,34 +1,0 @@
-md=triangle(model,'../Exp/Pig.exp',20000);
-md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
-md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
-
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'FrictionCoefficient'};
-md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
-md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
-
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
-field_tolerances={1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11};
-field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
-	(md.results.DiagnosticSolution.FrictionCoefficient),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
-};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test526.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test526.m	(revision 12877)
+++ 	(revision )
@@ -1,39 +1,0 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
-md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
-md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-
-%control parameters
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'FrictionCoefficient'};
-md.inversion.min_parameters=1*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=200*ones(md.mesh.numberofvertices,1);
-md.inversion.nsteps=2;
-md.inversion.cost_functions=[103*ones(md.inversion.nsteps,1)  501*ones(md.inversion.nsteps,1)];
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2*10^-7;
-md.inversion.gradient_scaling=3*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=2*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
-md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
-md.timestepping.time_step=0;
-
-md.thermal.penalty_lock=5;
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,SteadystateSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
-field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-6,1e-6,1e-6,1e-6,1e-6,1e-06};
-field_values={...
-	(md.results.SteadystateSolution.Gradient1),...
-	md.results.SteadystateSolution.J,...
-	(md.results.SteadystateSolution.FrictionCoefficient),...
-	(md.results.SteadystateSolution.Pressure),...
-	(md.results.SteadystateSolution.Vel),...
-	(md.results.SteadystateSolution.Vx),...
-	(md.results.SteadystateSolution.Vy),...
-	(md.results.SteadystateSolution.Vz),...
-	(md.results.SteadystateSolution.Temperature),...
-	(md.results.SteadystateSolution.BasalforcingsMeltingRate)
-};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test527.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test527.m	(revision 12877)
+++ 	(revision )
@@ -1,56 +1,0 @@
-%Simple mesh 1
-hVertices=10000*ones(27,1);
-hVertices(1:5)=1000;
-md=bamg(model,'domain','../Exp/Pig.exp','hmax',20000,'hVertices',hVertices,'gradation',3,'geometricalmetric',1);
-x1=md.mesh.x;
-y1=md.mesh.y;
-
-%Simple mesh 2
-md=bamg(model,'domain','../Exp/Pig.exp','hmax',10000);
-md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
-md=parameterize(md,'../Par/Pig.par');
-x2=md.mesh.x;
-y2=md.mesh.y;
-
-%refine existing mesh 1
-hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,md.inversion.vy_obs,'node');
-metric=ComputeMetric(hessian,2/9,1,1000,25*10^3,[]);
-md.miscellaneous.dummy=metric;
-md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1);
-x3=md2.mesh.x;
-y3=md2.mesh.y;
-
-%refine existing mesh 2
-md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1,'anisomax',1);
-x4=md2.mesh.x;
-y4=md2.mesh.y;
-
-%refine existing mesh 3
-hVertices=NaN*ones(md.mesh.numberofvertices,1);
-hVertices(find(md.mesh.vertexonboundary))=500;
-md2=bamg(md,'metric',md.miscellaneous.dummy,'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1,'anisomax',1,'hVertices',hVertices);
-x5=md2.mesh.x;
-y5=md2.mesh.y;
-
-%refine existing mesh 4
-md2=bamg(md,'field',md.inversion.vy_obs,'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1,'Hessiantype',0,'err',1);
-x6=md2.mesh.x;
-y6=md2.mesh.y;
-
-%refine existing mesh 5
-md2=bamg(md,'field',[md.inversion.vy_obs md.geometry.thickness],'hmin',1000,'hmax',20000,'gradation',3,'geometricalmetric',1,'Hessiantype',1,'err',[10 100]); 
-x7=md2.mesh.x;
-y7=md2.mesh.y;
-
-%Fields and tolerances to track changes
-field_names     ={'x1' 'y1' 'x2' 'y2' 'x3' 'y3' 'x4' 'y4' 'x5' 'y5' 'x6' 'y6'  'x7' 'y7' };
-field_tolerances={1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13 1e-13};
-field_values={...
-	x1, y1,...
-	y2, y2,...
-	y3, y3,...
-	y4, y4,...
-	y5, y5,...
-	y6, y6,...
-	y7, y7,...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test530.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test530.m	(revision 12877)
+++ 	(revision )
@@ -1,23 +1,0 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
-md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
-md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
-md.thermal.stabilization=2;
-md.cluster=generic('name',oshostname(),'np',3);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
-md.transient.isthermal=1;
-md.transient.isgroundingline=0;
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Temperature1','BasalforcingsMeltingRate1', ...
-				      'Temperature2','BasalforcingsMeltingRate2'};
-field_tolerances={1e-13,1e-8,1e-13,1e-8};
-field_values={...
-	(md.results.TransientSolution(1).Temperature),...
-	(md.results.TransientSolution(1).BasalforcingsMeltingRate),...
-	(md.results.TransientSolution(2).Temperature),...
-	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test532.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test532.m	(revision 12877)
+++ 	(revision )
@@ -1,18 +1,0 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
-md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
-md=parameterize(md,'../Par/Pig.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'pattyn','all');
-md.thermal.stabilization=2;
-md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
-md.thermal.penalty_threshold=40;
-md=solve(md,ThermalSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-11,1e-11};
-field_values={...
-	(md.results.ThermalSolution.Temperature),...
-	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
-	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test601.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test601.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test601.m	(revision 12878)
@@ -0,0 +1,13 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test602.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test602.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test602.m	(revision 12878)
@@ -1,6 +1,9 @@
 md=triangle(model,'../Exp/79North.exp',10000);
+md=meshconvert(md);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
 md=setflowequation(md,'macayeal','all');
+md.prognostic.stabilization=3;
+md.prognostic.spcthickness=md.geometry.thickness;
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,PrognosticSolutionEnum);
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test603.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test603.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test603.m	(revision 12878)
@@ -0,0 +1,14 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,6,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,PrognosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.PrognosticSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test604.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test604.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test604.m	(revision 12878)
@@ -1,16 +1,14 @@
 md=triangle(model,'../Exp/79North.exp',10000);
-md=meshconvert(md);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
 md=setflowequation(md,'macayeal','all');
-md.prognostic.stabilization=3;
-md.prognostic.spcthickness=md.geometry.thickness;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,SurfaceSlopeSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test605.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test605.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test605.m	(revision 12878)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,5,1.5);
+md=setflowequation(md,'pattyn','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,SurfaceSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
+	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test606.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test606.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test606.m	(revision 12878)
@@ -2,13 +2,13 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
-md=extrude(md,6,1);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,BedSlopeSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test607.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test607.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test607.m	(revision 12878)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=extrude(md,2,1);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BedSlopeSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'BedSlopeX','BedSlopeY'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.BedSlopeSolution.BedSlopeX),...
+	(md.results.BedSlopeSolution.BedSlopeY),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test608.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test608.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test608.m	(revision 12878)
@@ -4,11 +4,10 @@
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,SurfaceSlopeSolutionEnum);
+md=solve(md,BalancethicknessSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
-field_tolerances={1e-13,1e-13};
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
 field_values={...
-	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
-	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	(md.results.BalancethicknessSolution.Thickness),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test609.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test609.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test609.m	(revision 12878)
@@ -0,0 +1,15 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=meshconvert(md);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+md.balancethickness.stabilization=3;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
+field_values={...
+	(md.results.BalancethicknessSolution.Thickness),...
+	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test610.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test610.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test610.m	(revision 12878)
@@ -2,14 +2,13 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
-md=extrude(md,5,1.5);
-md=setflowequation(md,'pattyn','all');
+md=extrude(md,3,1);
+md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,SurfaceSlopeSolutionEnum);
+md=solve(md,BalancethicknessSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'SurfaceSlopeX','SurfaceSlopeY'};
-field_tolerances={1e-13,1e-13};
+field_names     ={'Thickness'};
+field_tolerances={1e-13};
 field_values={...
-	(md.results.SurfaceSlopeSolution.SurfaceSlopeX),...
-	(md.results.SurfaceSlopeSolution.SurfaceSlopeY),...
+	(md.results.BalancethicknessSolution.Thickness),...
 	};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test611.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test611.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test611.m	(revision 12878)
@@ -0,0 +1,31 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.nsteps=2;
+md.prognostic.stabilization=1;
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'BalancethicknessThickeningRate'};
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.min_parameters=-50*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=50*ones(md.mesh.numberofvertices,1);
+md.inversion.cost_functions=201*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10/md.constants.yts*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient' 'Misfits' 'BalancethicknessThickeningRate' 'Thickness'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.BalancethicknessSolution.Gradient1),...
+	md.results.BalancethicknessSolution.J,...
+	(md.results.BalancethicknessSolution.BalancethicknessThickeningRate),...
+	(md.results.BalancethicknessSolution.Thickness)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test612.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test612.m	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test612.m	(revision 12878)
@@ -1,14 +1,32 @@
 md=triangle(model,'../Exp/79North.exp',10000);
+md=meshconvert(md);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
 md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.nsteps=2;
+md.balancethickness.stabilization=3;
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'BalancethicknessThickeningRate'};
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.min_parameters=-50*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=50*ones(md.mesh.numberofvertices,1);
+md.inversion.cost_functions=201*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.gradient_scaling=10/md.constants.yts*ones(md.inversion.nsteps,1);
+md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BedSlopeSolutionEnum);
+md=solve(md,BalancethicknessSolutionEnum);
 
 %Fields and tolerances to track changes
-field_names     ={'BedSlopeX','BedSlopeY'};
-field_tolerances={1e-13,1e-13};
+field_names     ={'Gradient' 'Misfits' 'BalancethicknessThickeningRate' 'Thickness'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
 field_values={...
-	(md.results.BedSlopeSolution.BedSlopeX),...
-	(md.results.BedSlopeSolution.BedSlopeY),...
-	};
+	(md.results.BalancethicknessSolution.Gradient1),...
+	md.results.BalancethicknessSolution.J,...
+	(md.results.BalancethicknessSolution.BalancethicknessThickeningRate),...
+	(md.results.BalancethicknessSolution.Thickness)
+};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test613.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test613.m	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test613.m	(revision 12878)
@@ -0,0 +1,41 @@
+md=triangle(model,'../Exp/79North.exp',10000);
+md=meshconvert(md);
+md=setmask(md,'../Exp/79NorthShelf.exp','');
+md=parameterize(md,'../Par/79North.par');
+md=setflowequation(md,'macayeal','all');
+
+%Ice sheet only
+md=modelextract(md,md.mask.elementongroundedice);
+pos=find(md.mesh.vertexonboundary);
+md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
+
+%control parameters
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.iscontrol=1;
+md.inversion.thickness_obs=md.geometry.thickness;
+md.inversion.nsteps=2;
+md.inversion.control_parameters={'Vx' 'Vy'};
+md.balancethickness.stabilization=1;
+md.inversion.gradient_scaling=[10/md.constants.yts*ones(md.inversion.nsteps,1) 10/md.constants.yts*ones(md.inversion.nsteps,1)];
+md.inversion.min_parameters=[-2000*ones(md.mesh.numberofvertices,1) -2000*ones(md.mesh.numberofvertices,1)];
+md.inversion.max_parameters=[+2000*ones(md.mesh.numberofvertices,1) +2000*ones(md.mesh.numberofvertices,1)];
+md.inversion.cost_functions=201*ones(md.inversion.nsteps,1);
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
+md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
+
+md.verbose.control=1;
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancethicknessSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient1' 'Gradient2' 'Misfits' 'Vx' 'Vy' 'Thickness'};
+field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
+field_values={...
+	(md.results.BalancethicknessSolution.Gradient1),...
+	(md.results.BalancethicknessSolution.Gradient2),...
+	md.results.BalancethicknessSolution.J,...
+	(md.results.BalancethicknessSolution.Vx),...
+	(md.results.BalancethicknessSolution.Vy),...
+	(md.results.BalancethicknessSolution.Thickness)
+};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test614.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test614.m	(revision 12877)
+++ 	(revision )
@@ -1,15 +1,0 @@
-md=triangle(model,'../Exp/79North.exp',10000);
-md=setmask(md,'../Exp/79NorthShelf.exp','');
-md=parameterize(md,'../Par/79North.par');
-md=extrude(md,2,1);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BedSlopeSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'BedSlopeX','BedSlopeY'};
-field_tolerances={1e-13,1e-13};
-field_values={...
-	(md.results.BedSlopeSolution.BedSlopeX),...
-	(md.results.BedSlopeSolution.BedSlopeY),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test616.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test616.m	(revision 12877)
+++ 	(revision )
@@ -1,13 +1,0 @@
-md=triangle(model,'../Exp/79North.exp',10000);
-md=setmask(md,'../Exp/79NorthShelf.exp','');
-md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
-field_values={...
-	(md.results.BalancethicknessSolution.Thickness),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test618.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test618.m	(revision 12877)
+++ 	(revision )
@@ -1,15 +1,0 @@
-md=triangle(model,'../Exp/79North.exp',10000);
-md=meshconvert(md);
-md=setmask(md,'../Exp/79NorthShelf.exp','');
-md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
-md.balancethickness.stabilization=3;
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
-field_values={...
-	(md.results.BalancethicknessSolution.Thickness),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test620.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test620.m	(revision 12877)
+++ 	(revision )
@@ -1,14 +1,0 @@
-md=triangle(model,'../Exp/79North.exp',10000);
-md=setmask(md,'../Exp/79NorthShelf.exp','');
-md=parameterize(md,'../Par/79North.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
-field_values={...
-	(md.results.BalancethicknessSolution.Thickness),...
-	};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test622.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test622.m	(revision 12877)
+++ 	(revision )
@@ -1,31 +1,0 @@
-md=triangle(model,'../Exp/79North.exp',10000);
-md=setmask(md,'../Exp/79NorthShelf.exp','');
-md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
-
-%control parameters
-md.inversion.nsteps=2;
-md.prognostic.stabilization=1;
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'BalancethicknessThickeningRate'};
-md.inversion.thickness_obs=md.geometry.thickness;
-md.inversion.min_parameters=-50*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=50*ones(md.mesh.numberofvertices,1);
-md.inversion.cost_functions=201*ones(md.inversion.nsteps,1);
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
-md.inversion.gradient_scaling=10/md.constants.yts*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
-
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'BalancethicknessThickeningRate' 'Thickness'};
-field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
-field_values={...
-	(md.results.BalancethicknessSolution.Gradient1),...
-	md.results.BalancethicknessSolution.J,...
-	(md.results.BalancethicknessSolution.BalancethicknessThickeningRate),...
-	(md.results.BalancethicknessSolution.Thickness)
-};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test624.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test624.m	(revision 12877)
+++ 	(revision )
@@ -1,32 +1,0 @@
-md=triangle(model,'../Exp/79North.exp',10000);
-md=meshconvert(md);
-md=setmask(md,'../Exp/79NorthShelf.exp','');
-md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
-
-%control parameters
-md.inversion.nsteps=2;
-md.balancethickness.stabilization=3;
-md.inversion.iscontrol=1;
-md.inversion.control_parameters={'BalancethicknessThickeningRate'};
-md.inversion.thickness_obs=md.geometry.thickness;
-md.inversion.min_parameters=-50*ones(md.mesh.numberofvertices,1);
-md.inversion.max_parameters=50*ones(md.mesh.numberofvertices,1);
-md.inversion.cost_functions=201*ones(md.inversion.nsteps,1);
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
-md.inversion.gradient_scaling=10/md.constants.yts*ones(md.inversion.nsteps,1);
-md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
-
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'BalancethicknessThickeningRate' 'Thickness'};
-field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
-field_values={...
-	(md.results.BalancethicknessSolution.Gradient1),...
-	md.results.BalancethicknessSolution.J,...
-	(md.results.BalancethicknessSolution.BalancethicknessThickeningRate),...
-	(md.results.BalancethicknessSolution.Thickness)
-};
Index: sm/branches/trunk-jpl-damage/test/NightlyRun/test626.m
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test626.m	(revision 12877)
+++ 	(revision )
@@ -1,41 +1,0 @@
-md=triangle(model,'../Exp/79North.exp',10000);
-md=meshconvert(md);
-md=setmask(md,'../Exp/79NorthShelf.exp','');
-md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
-
-%Ice sheet only
-md=modelextract(md,md.mask.elementongroundedice);
-pos=find(md.mesh.vertexonboundary);
-md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
-
-%control parameters
-md.inversion.thickness_obs=md.geometry.thickness;
-md.inversion.iscontrol=1;
-md.inversion.thickness_obs=md.geometry.thickness;
-md.inversion.nsteps=2;
-md.inversion.control_parameters={'Vx' 'Vy'};
-md.balancethickness.stabilization=1;
-md.inversion.gradient_scaling=[10/md.constants.yts*ones(md.inversion.nsteps,1) 10/md.constants.yts*ones(md.inversion.nsteps,1)];
-md.inversion.min_parameters=[-2000*ones(md.mesh.numberofvertices,1) -2000*ones(md.mesh.numberofvertices,1)];
-md.inversion.max_parameters=[+2000*ones(md.mesh.numberofvertices,1) +2000*ones(md.mesh.numberofvertices,1)];
-md.inversion.cost_functions=201*ones(md.inversion.nsteps,1);
-md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
-md.inversion.maxiter_per_step=4*ones(md.inversion.nsteps,1);
-md.inversion.step_threshold=0.99*ones(md.inversion.nsteps,1);
-
-md.verbose.control=1;
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Gradient1' 'Gradient2' 'Misfits' 'Vx' 'Vy' 'Thickness'};
-field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
-field_values={...
-	(md.results.BalancethicknessSolution.Gradient1),...
-	(md.results.BalancethicknessSolution.Gradient2),...
-	md.results.BalancethicknessSolution.J,...
-	(md.results.BalancethicknessSolution.Vx),...
-	(md.results.BalancethicknessSolution.Vy),...
-	(md.results.BalancethicknessSolution.Thickness)
-};
Index: /issm/branches/trunk-jpl-damage/test/NightlyRun/test999.py
===================================================================
--- /issm/branches/trunk-jpl-damage/test/NightlyRun/test999.py	(revision 12878)
+++ /issm/branches/trunk-jpl-damage/test/NightlyRun/test999.py	(revision 12878)
@@ -0,0 +1,27 @@
+#md=model()
+#md=triangle(md,'../Exp/Square.exp',50000)
+#md=setmask(md,'all','')
+#md=parameterize(md,'../Par/SquareShelfConstrained.py')
+
+md1=[11,12,13]
+md2=[21,22,23]
+md3=[34,32,33]
+md4=[41,44,43]
+md5=[51,52,53]
+md6=[61,62,63]
+md7=[71,72,73]
+
+#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=[\
+	[md1],\
+	[md2],\
+	[md3],\
+	[md4],\
+	[md5],\
+	[md6],\
+	[md7],\
+	]
Index: /issm/branches/trunk-jpl-damage/test/Par/SquareShelfConstrained.par
===================================================================
--- /issm/branches/trunk-jpl-damage/test/Par/SquareShelfConstrained.par	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/Par/SquareShelfConstrained.par	(revision 12878)
@@ -51,5 +51,5 @@
 md=SetIceShelfBC(md);
 
-%Change name so that no test have the same name
+%Change name so that no tests have the same name
 A=dbstack;
 if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/branches/trunk-jpl-damage/test/Par/SquareShelfConstrained.py
===================================================================
--- /issm/branches/trunk-jpl-damage/test/Par/SquareShelfConstrained.py	(revision 12877)
+++ /issm/branches/trunk-jpl-damage/test/Par/SquareShelfConstrained.py	(revision 12878)
@@ -4,4 +4,6 @@
 import InterpFromMeshToMesh2d as im
 from   paterson import  *
+from SetIceShelfBC import *
+import inspect
 
 #Start defining model parameters here
@@ -18,10 +20,15 @@
 #Initial velocity 
 mat=matio.loadmat('../Data/SquareShelfConstrained.data')
+#Reshape as Rank-1 arrays
+x=reshape(mat['x'],(-1))
+y=reshape(mat['y'],(-1))
+vx=mat['vx']
+vy=mat['vy']
 #deal with 'F' oriented matlab matrices!
 index=mat['index'].astype(float)
 index=reshape(index.T,(len(index),3),order='F')
 
-md.initialization.vx = im.InterpFromMeshToMesh2d(index, mat['x'], mat['y'], mat['vx'], md.mesh.x, md.mesh.y)
-md.initialization.vy = im.InterpFromMeshToMesh2d(index, mat['x'], mat['y'], mat['vy'], md.mesh.x, md.mesh.y)
+md.initialization.vx = im.InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y)
+md.initialization.vy = im.InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y)
 md.initialization.vz = zeros(md.mesh.numberofvertices)
 md.initialization.pressure = zeros(md.mesh.numberofvertices)
@@ -53,7 +60,6 @@
 #Deal with boundary conditions:
 md = SetIceShelfBC(md)
-#Change name so that no test have the same name
-A = dbstack
-if length(A) > 2.:
-    md.miscellaneous.name = A[2].file[0:0-2.]
+#Change name so that no tests have the same name
+if len(inspect.stack()) > 2:
+    md.miscellaneous.name = inspect.stack()[2][1].split('.')[0]
 
