Index: /issm/trunk/Makefile.am
===================================================================
--- /issm/trunk/Makefile.am	(revision 13394)
+++ /issm/trunk/Makefile.am	(revision 13395)
@@ -1,3 +1,6 @@
-EXTRA_DIST = reconf  scripts test m4 examples cron etc doc packages contributors.txt 
-SUBDIRS = src bin
+EXTRA_DIST = reconf scripts test m4 examples cron etc doc packages contributors.txt 
+SUBDIRS = src
 bin_SCRIPTS=config.h startup.m README.rtf
+
+ACLOCAL_AMFLAGS = -I m4
+
Index: /issm/trunk/configs/config-arm-linux.sh
===================================================================
--- /issm/trunk/configs/config-arm-linux.sh	(revision 13394)
+++ /issm/trunk/configs/config-arm-linux.sh	(revision 13395)
@@ -5,6 +5,8 @@
     --build="i386-apple-darwin10.8.0" \
     --host="arm-linux-androideabi" \
+    --enable-shared \
     --without-fortran \
 	--without-modules \
 	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install 
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+    --disable-static
Index: /issm/trunk/configs/config-discover.sh
===================================================================
--- /issm/trunk/configs/config-discover.sh	(revision 13394)
+++ /issm/trunk/configs/config-discover.sh	(revision 13395)
@@ -18,8 +18,7 @@
  --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-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
  --with-graphics-lib=/usr/lib64/libX11.so \
  --with-cxxoptflags="-O3 -xS" \
Index: /issm/trunk/configs/config-greenplanet.sh
===================================================================
--- /issm/trunk/configs/config-greenplanet.sh	(revision 13394)
+++ /issm/trunk/configs/config-greenplanet.sh	(revision 13395)
@@ -1,3 +1,3 @@
-#!/bin/csh
+#!/bin/sh
 
 #PETSc 3.2
Index: /issm/trunk/configs/config-linux64-ad.sh
===================================================================
--- /issm/trunk/configs/config-linux64-ad.sh	(revision 13394)
+++ /issm/trunk/configs/config-linux64-ad.sh	(revision 13395)
@@ -18,3 +18,3 @@
 	--without-groundingline \
 	--without-kriging  \
-	--with-adolc-dir=$ADOLC_DIR 
+	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install
Index: /issm/trunk/configs/config-linux64-astrid-ad.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid-ad.sh	(revision 13394)
+++ /issm/trunk/configs/config-linux64-astrid-ad.sh	(revision 13395)
@@ -2,35 +2,10 @@
 
 ./configure \
- --prefix=$ISSM_DIR \
- --with-serial=no\
- --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
- --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
- --with-mpi-include=$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-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-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-march=opteron -O2" \
- --with-fortran-lib="-L/usr/lib/gcc/x86_64-redhat-linux/4.1.1/ -lgfortran" \
- --with-rose-dir=$ISSM_DIR/externalpackages/rose/install/ \
- --with-adic2-dir=$ISSM_DIR/externalpackages/adic/install/ \
- --with-numthreads=24 \
- --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-prognostic \
+	--prefix=$ISSM_DIR \
+	--without-kriging  \
+	--without-kml  \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
+	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install \
+	--with-adolc-version=3 \
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
Index: /issm/trunk/configs/config-linux64-astrid-petsc3.3.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid-petsc3.3.sh	(revision 13395)
+++ /issm/trunk/configs/config-linux64-astrid-petsc3.3.sh	(revision 13395)
@@ -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/trunk/configs/config-linux64-astrid-petscdev.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid-petscdev.sh	(revision 13394)
+++ /issm/trunk/configs/config-linux64-astrid-petscdev.sh	(revision 13395)
@@ -1,6 +1,4 @@
 #!/bin/sh
 
-#External packages versions:
-#petsc Dev: FH trying out
 #mpich 1.4
 
@@ -17,6 +15,4 @@
  --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/ \
@@ -24,14 +20,10 @@
  --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-cxxoptflags="-march=opteron -O3" \
  --with-numthreads=32 \
  --enable-debugging
Index: /issm/trunk/configs/config-linux64-astrid-python.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid-python.sh	(revision 13394)
+++ /issm/trunk/configs/config-linux64-astrid-python.sh	(revision 13395)
@@ -13,19 +13,10 @@
  --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
  --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
- --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
  --with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
  --with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/install/lib/ -lmpich " \
  --with-petsc-arch=$ISSM_ARCH \
- --with-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 \
Index: /issm/trunk/configs/config-linux64-astrid.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid.sh	(revision 13394)
+++ /issm/trunk/configs/config-linux64-astrid.sh	(revision 13395)
@@ -7,14 +7,17 @@
 ./configure \
  --prefix=$ISSM_DIR \
- --with-matlab-dir=$MATLAB_DIR \
+ --with-matlab-dir=$ISSM_DIR/externalpackages/matlab/install \
  --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
  --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
  --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-python-dir=$ISSM_DIR/externalpackages/python/install\
+ --with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/lib/python2.7/site-packages/numpy/core/include/numpy\
+ --with-python-version=2.7\
  --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
+ --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
  --with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
  --with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/install/lib/ -lmpich -lmpl " \
  --with-petsc-arch=$ISSM_ARCH \
  --with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
- --with-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" \
@@ -29,5 +32,4 @@
  --with-graphics-lib=/usr/lib64/libX11.so \
  --with-cxxoptflags="-march=opteron -O2" \
- --with-numthreads=32 \
+ --with-numthreads=16 \
  --enable-debugging
- #--with-serial=no \
Index: /issm/trunk/configs/config-macosx64-chris-bothapis.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-chris-bothapis.sh	(revision 13395)
+++ /issm/trunk/configs/config-macosx64-chris-bothapis.sh	(revision 13395)
@@ -0,0 +1,33 @@
+#!/bin/sh
+
+#petsc 3.2
+#mpich 1.4
+
+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/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy\
+	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
+	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
+	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
+	--with-chaco-dir=$ISSM_DIR/externalpackages/chaco/install \
+	--with-fortran-lib="/usr/local/gfortran/lib/gcc/x86_64-apple-darwin10/4.6.2/libgfortran.a" \
+	--with-math-lib="/usr/lib/libm.dylib" \
+	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
+	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
+	--with-numthreads=8 \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-numthreads=8
+	#--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
+	#--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+	#--with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
Index: /issm/trunk/configs/config-macosx64-chris-python.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-chris-python.sh	(revision 13395)
+++ /issm/trunk/configs/config-macosx64-chris-python.sh	(revision 13395)
@@ -0,0 +1,34 @@
+#!/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/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-chaco-dir=$ISSM_DIR/externalpackages/chaco/install \
+	--with-fortran-lib="/usr/local/gfortran/lib/gcc/x86_64-apple-darwin10/4.6.2/libgfortran.a" \
+	--with-math-lib="/usr/lib/libm.dylib" \
+	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
+	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
+	--with-numthreads=8 \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-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-numthreads=8
+	#--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
+	#--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+	#--with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
Index: sm/trunk/configs/config-macosx64-helene.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-helene.sh	(revision 13394)
+++ 	(revision )
@@ -1,26 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-
-./configure \
-	--prefix=$ISSM_DIR \
-	--with-matlab-dir=$MATLAB_DIR \
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
-	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
-	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
-	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a" \
-	--with-petsc-arch=$ISSM_ARCH \
-	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
-	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
-	--with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/include/ " \
-	--with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
-	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
-	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
-	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
-	--with-math-lib="/usr/lib/libm.dylib" \
-	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
-	--with-numthreads=8
Index: /issm/trunk/configs/config-macosx64-larour-ad.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-larour-ad.sh	(revision 13394)
+++ /issm/trunk/configs/config-macosx64-larour-ad.sh	(revision 13395)
@@ -3,18 +3,9 @@
 ./configure \
 	--prefix=$ISSM_DIR \
-	--without-modules\
-	--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-gsl-dir=$ISSM_DIR/externalpackages/gsl/install
-	#--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install\
+	--without-kml  \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
+	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install \
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+
Index: /issm/trunk/configs/config-macosx64-larour-python.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-larour-python.sh	(revision 13394)
+++ /issm/trunk/configs/config-macosx64-larour-python.sh	(revision 13395)
@@ -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/trunk/configs/config-macosx64-larour.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-larour.sh	(revision 13394)
+++ /issm/trunk/configs/config-macosx64-larour.sh	(revision 13395)
@@ -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/trunk/configs/config-macosx64-lion-helene.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-lion-helene.sh	(revision 13395)
+++ /issm/trunk/configs/config-macosx64-lion-helene.sh	(revision 13395)
@@ -0,0 +1,34 @@
+#!/bin/sh
+
+#petsc 3.2
+#mpich 1.4
+
+pythonversion=2.7
+
+./configure \
+	--prefix=$ISSM_DIR \
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
+	--with-python-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  \
+	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
+	--with-chaco-dir=$ISSM_DIR/externalpackages/chaco/install \
+	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
+	--with-math-lib="/usr/lib/libm.dylib" \
+	--with-graphics-lib="-L/usr/X11R6/lib -lX11" \
+	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
+	--with-numthreads=8 \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/include/ " \
+	--with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-numthreads=8
+	#--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+	#--with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
+	#--with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
Index: /issm/trunk/configs/config-macosx64-nicole.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-nicole.sh	(revision 13394)
+++ /issm/trunk/configs/config-macosx64-nicole.sh	(revision 13395)
@@ -15,10 +15,7 @@
 	--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" \
Index: /issm/trunk/configure.ac
===================================================================
--- /issm/trunk/configure.ac	(revision 13394)
+++ /issm/trunk/configure.ac	(revision 13395)
@@ -2,8 +2,10 @@
 
 #AUTOCONF
-AC_INIT([ISSM],[4.2.1],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_INIT([ISSM],[4.2.2],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
 AC_CONFIG_AUX_DIR([./aux-config])         #Put config files in aux-config
 AC_CONFIG_MACRO_DIR([m4])                 #m4 macros are located in m4
+m4_include([m4/issm_options.m4])
 AC_CANONICAL_TARGET                       #Determine the system type
+
 #Compilers
 AC_PROG_CC([cccl cl icl gcc])
@@ -11,6 +13,6 @@
 AC_PROG_CXX([cccl cl icl g++])
 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
@@ -22,14 +24,11 @@
 AM_SILENT_RULES([yes])           #Do not show compilation command by default
 AM_PROG_CC_C_O
+AM_PROG_AR
 
-##LIBTOOL?
-#AC_PROG_LIBTOOL
-#LT_INIT
+#Libtool
+LT_INIT
 
 #Run issm_options.m4
 ISSM_OPTIONS
-
-#AM_PROG_AR must be placed after ISSM_OPTIONS
-AM_PROG_AR
 
 #List all Makefiles
@@ -37,11 +36,8 @@
 			src/Makefile
 			src/c/Makefile 
-			src/py/Makefile
-			src/py/model/Makefile
 			src/modules/Makefile
 			src/modules/python/Makefile
 			src/modules/matlab/Makefile
-			src/m/Makefile
-			bin/Makefile])
+			src/m/Makefile])
 
 #End of configure.ac
Index: /issm/trunk/etc/environment.csh
===================================================================
--- /issm/trunk/etc/environment.csh	(revision 13394)
+++ /issm/trunk/etc/environment.csh	(revision 13395)
@@ -1,140 +1,97 @@
 #ISSM_DIR and ISSM_ARCH should have been defined already in your shell settings file (.bashrc, .cshrc, etc ...)
-source $ISSM_DIR/etc/environment_variables.csh
 
-#Do we have any command line arguments? (such as MATLAB_DIR=otherdirthandefault), source them before exporting the variables 
-#to environment.
-
-#foreach i ($@)
-#eval $i
-#end
-
-#CRON utilities
-setenv PATH {$PATH}:{$ISSM_DIR}/cron
-
-#SCRIPTS utilities
+#Load ISSM scripts
 setenv PATH {$PATH}:{$ISSM_DIR}/scripts
 
 #MATLAB
-setenv MATLAB_DIR {$MATLAB_DIR}
-setenv PATH {$MATLAB_DIR}/bin:{$PATH}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$MATLAB_DIR/lib
+set MATLAB_DIR="$ISSM_DIR/externalpackages/matlab/install"
+if (-d MATLAB_DIR) then
+	setenv MATLAB_DIR {$MATLAB_DIR}
+	setenv PATH {$MATLAB_DIR}/bin:{$PATH}
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$MATLAB_DIR}/bin/glnxa64
+endif
 
 #MPI
-setenv MPI_DIR {$MPI_DIR}
-setenv PATH {$MPI_DIR}/bin:{$PATH}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$MPI_DIR/lib
-setenv MANPATH {$MANPATH}:$MPI_DIR/man
-setenv MPIRUN_NPROCS 8
+set MPI_DIR="$ISSM_DIR/externalpackages/mpich2/install"
+if (-d $MPI_DIR) then
+	setenv MPI_DIR {$MPI_DIR}
+	setenv PATH {$MPI_DIR}/bin:{$PATH}
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$MPI_DIR/lib
+	setenv MANPATH {$MANPATH}:$MPI_DIR/man
+endif
 
 #PETSC
-setenv PETSC_DIR {$PETSC_DIR}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$PETSC_DIR/lib/{$ISSM_ARCH}
+set PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install"
+if (-d $PETSC_DIR) then
+	setenv PETSC_DIR {$PETSC_DIR}
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$PETSC_DIR/lib/{$ISSM_ARCH}
+endif
 
 #SLEPC
-setenv SLEPC_DIR {$SLEPC_DIR}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$SLEPC_DIR/lib/{$ISSM_ARCH}
+set SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
+if (-d $SLEPC_DIR) then
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$SLEPC_DIR/lib/{$ISSM_ARCH}
+endif
 
+#PETSC
+set TAO_DIR="$ISSM_DIR/externalpackages/tao/install"
+if (-d $TAO_DIR) then
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:$TAO_DIR/lib/{$ISSM_ARCH}
+endif
 
 #Dakota
-setenv DAKOTA_DIR {$DAKOTA_DIR}
-setenv PATH {$PATH}:{$DAKOTA_DIR}/bin
-setenv MANPATH {$MANPATH}:{$MPI_DIR}/man:{$DAKOTA_DIR}/docs/man:{$DAKOTA_DIR}/docs/man-ref
-
-#Qhull
-setenv QHULL_DIR {$QHULL_DIR}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$QHULL_DIR}/lib
-
+set DAKOTA_DIR="$ISSM_DIR/externalpackages/dakota/install"
+if (-d $DAKOTA_DIR) then
+	setenv PATH {$PATH}:{$DAKOTA_DIR}/bin
+	setenv MANPATH {$MANPATH}:{$MPI_DIR}/man:{$DAKOTA_DIR}/docs/man:{$DAKOTA_DIR}/docs/man-ref
+endif
 
 #Doxygen
-setenv DOXYGEN_DIR {$DOXYGEN_DIR}
-setenv MANPATH {$MANPATH}:{$DOXYGEN_DIR}/man
-setenv PATH {$PATH}:{$DOXYGEN_DIR}/bin
+set DOXYGEN_DIR="$ISSM_DIR/externalpackages/doxygen/install"
+if (-d $DOXYGEN_DIR) then
+	setenv MANPATH {$MANPATH}:{$DOXYGEN_DIR}/man
+	setenv PATH {$PATH}:{$DOXYGEN_DIR}/bin
+endif
 
-#MTOC
-setenv MTOC_DIR {$MTOC_DIR}
-setenv PATH {$PATH}:{$MTOC_DIR}
+#AUTOTOOLS
+set AUTOTOOLS_DIR="$ISSM_DIR/externalpackages/autotools/install"
+if (-d $AUTOTOOLS_DIR) then
+	setenv PATH {$AUTOTOOLS_DIR}/bin:{$PATH}
+endif
 
-#MATLAB
-setenv MATLAB_DIR {$MATLAB_DIR}
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$MATLAB_DIR}/bin/glnxa64
-setenv PATH {$PATH}:{$MATLAB_DIR}/bin
+#SSH
+set SSH_DIR="$ISSM_DIR/externalpackages/ssh"
+if (-d $SSH_DIR) then
+	setenv PATH {$PATH}:{$SSH_DIR}
+endif
 
-#TRIANGLE
-setenv TRIANGLE_DIR {$TRIANGLE_DIR}
+#VALGRIND
+set VALGRIND_DIR="$ISSM_DIR/externalpackages/valgrind/install/bin"
+if (-d $VALGRIND_DIR) then
+	setenv PATH {$PATH}:{$VALGRIND_DIR}
+endif
 
-#METIS
-setenv METIS_DIR {$METIS_DIR}
-	
-#BLAS
-setenv BLAS_DIR {$BLAS_DIR}
+#MERCURIAL
+set MERCURIAL_DIR="$ISSM_DIR/externalpackages/mercurial/install"
+if (-d $MERCURIAL_DIR) then
+	setenv PYTHONPATH {$MERCURIAL_DIR}/mercurial/pure/
+	setenv PATH {$PATH}:{$MERCURIAL_DIR}
+endif
 
-#LAPACK
-setenv LAPACK_DIR {$LAPACK_DIR}
+#GSL
+set GSL_DIR="$ISSM_DIR/externalpackages/gsl/install"
+if (-d $GSL_DIR) then
+	setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$GSL_DIR}/lib
+endif
 
-#SCALAPACK
-setenv SCALAPACK_DIR {$SCALAPACK_DIR}
-
-#PLAPACK
-setenv PLAPACK_DIR {$PLAPACK_DIR}
-
-#BLACS
-setenv BLACS_DIR {$BLACS_DIR}
+#CMAKE
+set CMAKE_DIR="$ISSM_DIR/externalpackages/cmake/install"
+if (-d $CMAKE_DIR) then
+	setenv PATH {$PATH}:{$CMAKE_DIR}/bin
+endif
 
 #YAMS
-setenv YAMS_DIR {$YAMS_DIR}
-setenv PATH {$PATH}:{$YAMS_DIR}
-
-#TEX2IM
-setenv TEX2IM_DIR {$TEX2IM_DIR}
-setenv PATH {$PATH}:{$TEX2IM_DIR}
-
-#SOWING
-setenv SOWING_DIR {$SOWING_DIR}
-setenv PATH {$PATH}:{$SOWING_DIR}/bin
-setenv LD_LIBRARY_PATH {$LD_LIBRARY_PATH}:{$SOWING_DIR}/lib
-setenv MANPATH {$MANPATH}:{$SOWING_DIR}/man
-
-#Chaco
-setenv CHACO_DIR {$CHACO_DIR}
-setenv PATH {$PATH}:{$CHACO_DIR}
-
-#MeshPart
-setenv MESHPART_DIR {$MESHPART_DIR}
-setenv PATH {$PATH}:{$MESHPART_DIR}
-
-#SCOTCH
-setenv SCOTCH_DIR {$SCOTCH_DIR}
-setenv PATH {$PATH}:{$SCOTCH_DIR}
-setenv MANPATH {$MANPATH}:{$SCOTCH_DIR}/man
-
-#AUTOCONF
-setenv AUTOCONF_DIR {$AUTOCONF_DIR}
-setenv PATH {$AUTOCONF_DIR}/bin:{$PATH}
-
-#AUTOMAKE
-setenv AUTOMAKE_DIR {$AUTOMAKE_DIR}
-setenv PATH {$AUTOMAKE_DIR}/bin:{$PATH}
-
-#BORLAND
-setenv BORLAND_DIR {$BORLAND_DIR}
-setenv PATH {$PATH}:{$BORLAND_DIR}/Bin
-
-#SSH
-setenv SSH_DIR {$SSH_DIR}
-setenv PATH {$PATH}:{$SSH_DIR}
-
-#VALGRIND
-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
+set YAMS_DIR="$ISSM_DIR/externalpackages/yams/install"
+if (-d $YAMS_DIR) then
+	setenv PATH {$PATH}:{$YAMS_DIR}/bin
+endif
Index: /issm/trunk/etc/environment.sh
===================================================================
--- /issm/trunk/etc/environment.sh	(revision 13394)
+++ /issm/trunk/etc/environment.sh	(revision 13395)
@@ -1,3 +1,51 @@
 #ISSM_DIR and ISSM_ARCH should have been defined already in your shell settings file (.bashrc, .cshrc, etc ...)
+
+pathprepend(){ #{{{
+	if [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]]; then
+		PATH="$1:$PATH"
+	fi
+} #}}}
+pathappend(){ #{{{
+	if [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]]; then
+		export PATH="$PATH:$1"
+	fi
+} #}}}
+libpathprepend(){ #{{{
+	if [ -d "$1" ] && [[ ":$LD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export LD_LIBRARY_PATH="$1:$LD_LIBRARY_PATH"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$1:$LD_RUN_PATH"
+	fi
+} #}}}
+libpathappend(){ #{{{
+	if [ -d "$1" ] && [[ ":$LD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$1"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$LD_RUN_PATH:$1"
+	fi
+} #}}}
+dylibpathprepend(){ #{{{
+	if [ -d "$1" ] && [[ ":$DYLD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export DYLD_LIBRARY_PATH="$1:$DYLD_LIBRARY_PATH"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$1:$LD_RUN_PATH"
+	fi
+} #}}}
+dylibpathappend(){ #{{{
+	if [ -d "$1" ] && [[ ":$DYLD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$1"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$LD_RUN_PATH:$1"
+	fi
+} #}}}
+
+#FIXME: during installation packages are installed one by one but environment.sh was sourced
+#before so new packages are NOT in the path.
+#may resource environment.sh with:
+#if [ -z $(echo "$PATH" | grep "$MATLAB_DIR") ]; then export $PATH...; fi
 
 #Windows compilers: 
@@ -6,290 +54,214 @@
 fi
 
-source $ISSM_DIR/etc/environment_variables.sh
-
-#Do we have any command line arguments? (such as MATLAB_DIR=otherdirthandefault), source them after exporting the variables
-#to environment.
-for i in $@
-do
-	eval $i
-done
-
-#CRON utilities
-PATH="$PATH:$ISSM_DIR/cron"
-
-#scripts
-PATH="$PATH:$ISSM_DIR/scripts"
-
-##MATLAB
+#Some basic path, in case it is not included by default
+libpathappend "/usr/local/lib"
+
+#Load ISSM scripts
+pathappend "$ISSM_DIR/scripts"
+
+MATLAB_DIR="$ISSM_DIR/externalpackages/matlab/install"
 export MATLAB_DIR
-PATH="$MATLAB_DIR/bin:$PATH" #take precedence over /usr/local/bin/matlab
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$MATLAB_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$MATLAB_DIR/lib"
-#export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$MATLAB_DIR/bin/glnxa64"
-#export LD_RUN_PATH="$LD_RUN_PATH:$MATLAB_DIR/bin/glnxa64"
-
-#MPI
+pathprepend   "$MATLAB_DIR/bin" #take precedence over /usr/local/bin/matlab
+libpathappend "$MATLAB_DIR/lib"
+
+MPI_DIR="$ISSM_DIR/externalpackages/mpich2/install"
 export MPI_DIR
-PATH="$MPI_DIR/bin:$PATH"
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$MPI_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$MPI_DIR/lib"
-export MANPATH="$MANPATH:$MPI_DIR/man"
-export MPIRUN_NPROCS=24
-
-#PETSC
+pathprepend   "$MPI_DIR/bin"
+libpathappend "$MPI_DIR/lib"
+
+PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install"
 export PETSC_DIR
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$PETSC_DIR/lib/$ISSM_ARCH"
-export LD_RUN_PATH="$LD_RUN_PATH:$PETSC_DIR/lib/$ISSM_ARCH"
-
-#SLEPC
-export SLEPC_DIR
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$SLEPC_DIR/lib/$ISSM_ARCH"
-export LD_RUN_PATH="$LD_RUN_PATH:$SLEPC_DIR/lib/$ISSM_ARCH"
-
-#Dakota
-export DAKOTA_DIR
-PATH="$PATH:$DAKOTA_DIR/bin"
-export MANPATH="$MANPATH:$MPI_DIR/man:$DAKOTA_DIR/docs/man:$DAKOTA_DIR/docs/man-ref"
-
-#Qhull
-export QHULL_DIR
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$QHULL_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$QHULL_DIR/lib"
-
-#Doxygen
-export DOXYGEN_DIR
-MANPATH="$MANPATH:$DOXYGEN_DIR/man"
-PATH="$PATH:$DOXYGEN_DIR/bin"
-
-#MTOC
-export MTOC_DIR
-PATH="$PATH:$MTOC_DIR"
-
-#TRIANGLE
-export TRIANGLE_DIR
-
-#METIS
-export METIS_DIR
-	
-#BLAS
-export BLAS_DIR
-
-#LAPACK
-export LAPACK_DIR
-
-#SCALAPACK
-export SCALAPACK_DIR
-
-#PLAPACK
-export PLAPACK_DIR
-
-#BLACS
-export BLACS_DIR
-
-#YAMS
-export YAMS_DIR
-PATH="$PATH:$YAMS_DIR"
-
-#BAMG
-export BAMG_DIR
-PATH="$PATH:$BAMG_DIR"
-
-#TEX2IM
-export TEX2IM_DIR
-PATH="$PATH:$TEX2IM_DIR"
-
-#SOWING
-export SOWING_DIR
-PATH="$PATH:$SOWING_DIR/bin"
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$SOWING_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$SOWING_DIR/lib"
-export MANPATH="$MANPATH:$SOWING_DIR/man"
-
-#Chaco
-export CHACO_DIR
-PATH="$PATH:$CHACO_DIR"
-
-#MeshPart
-export MESHPART_DIR
-PATH="$PATH:$MESHPART_DIR"
-
-#SCOTCH
-export SCOTCH_DIR
-PATH="$PATH:$SCOTCH_DIR"
-export MANPATH="$MANPATH:$SCOTCH_DIR/man"
-
-#AUTOCONF
-export AUTOCONF_DIR
-PATH="$AUTOCONF_DIR/bin:$PATH"
-
-#AUTOMAKE
-export AUTOMAKE_DIR
-PATH="$AUTOMAKE_DIR/bin:$PATH"
-
-export LIBTOOL_DIR
-PATH="$LIBTOOL_DIR/bin:$PATH"
-
-#BORLAND
-export BORLAND_DIR
-PATH="$PATH:$BORLAND_DIR/Bin"
-
-#INTEL
-#export INTEL_DIR
-#PATH="$PATH:$INTEL_DIR"
-#source $ISSM_DIR/externalpackages/intel/intel.sh
-
-#SDK
-export SDK_DIR
-PATH="$PATH:$SDK_DIR"
-
-#SSH
-export SSH_DIR
-PATH="$PATH:$SSH_DIR"
-
-#VALGRIND
-export VALGRIND_DIR
-PATH="$PATH:$VALGRIND_DIR"
-
-#GRAPHVIZ
-export GRAPHVIZ_DIR
-PATH="$PATH:$GRAPHVIZ_DIR"
-
-#CPPCHECK
-export CPPCHECK_DIR
-PATH="$PATH:$CPPCHECK_DIR"
-
-#GDAL
-export GDAL_DIR
-PATH="$GDAL_DIR/bin:$PATH"
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$GDAL_DIR/lib"
-
-#MERCURIAL
-export PYTHONPATH="$PYTHONPATH:$MERCURIAL_DIR/mercurial/pure/"
-export PATH="$PATH:$MERCURIAL_DIR/"
-
-#BOOST
-export BOOSTROOT
-export BOOST_DIR
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$BOOST_DIR/lib"
-export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$BOOST_DIR/lib"
-export PATH="$PATH:$BOOST_DIR/bin"
-
-#XERCES
-export XERCESROOT 
-export XERCESCROOT
-
-#xaifBooster
-export XAIFBOOSTERROOT
-export XAIFBOOSTER_HOME
-export XAIF_DIR
-export PLATFORM
-
-#angel
-export ANGELROOT
-
-#openanalysis
-export OPENANALYSISROOT
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$OPENANALYSISROOT/lib"
-
-#JAVA
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$JVM_DIR"
-
-#BBFTP
-export PATH="$PATH:$BBFTP_DIR/bin"
-
-#ADIC
-export PATH="$PATH:$ADIC_DIR/bin"
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$ADIC_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$ADIC_DIR/lib"
-
-#COLPACK
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$COLPACK_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$COLPACK_DIR/lib"
-
-#ECLIPSE
-export PATH="$PATH:$ECLIPSE_DIR"
-
-#FLAIM
-export FLAIM_DIR
-
-#APPSCAN
-export PATH="$PATH:$APPSCAN_DIR/install/bin"
-export PATH="$PATH:$APPSCAN_DIR/bin"
-
-#CPPCHECK
-export PATH="$PATH:$CPPCHECK_DIR/bin"
-
-#RATS
-export PATH="$PATH:$RATS_DIR/bin"
-
-#DYSON
-export PATH="$PATH:$DYSON_DIR"
-
-#CMAKE
-export PATH="$PATH:$CMAKE_DIR/bin"
-
-#SHAPELIB
-export PATH="$PATH:$SHAPELIB_DIR/exec"
-
-#CCCL
-export PATH="$PATH:$CCCL_DIR/bin"
-
-#PACKAGEMAKER
-export PATH="$PATH:$PACKAGEMAKER_DIR"
-
-#ANDROID_NDK:
-export ANDROID_NDK_DIR
-export PATH="$PATH:$ANDROID_NDK_DIR/"
-
-#ANDROID_DIR
-export ANDROID_DIR
-
-#ANDROID_SDK
-export PATH="$PATH:$ANDROID_SDK_DIR/"
-
-#ANDROID_ANT
-export PATH="$PATH:$ANDROID_ANT_DIR/"
-
-#GSL
-export PATH="$PATH:$GSL_DIR/bin"
-export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$GSL_DIR/lib"
-export LD_RUN_PATH="$LD_RUN_PATH:$GSL_DIR/lib"
-
-#GMAKE
-export PATH="$GMAKE_DIR/bin:$PATH"
-
-#PYTHON
-export PATH="$PYTHON_DIR/bin:$PATH"
-export PYTHONPATH="$PYTHONPATH:$ISSM_DIR/src/modules/python"
-export LD_LIBRARY_PATH=$ISSM_DIR/src/modules/python:$ISSM_DIR/externalpackages/python/install/lib:$LD_LIBRARY_PATH
-export PYTHONSTARTUP
-
-#MODELE
-export PATH="$MODELE_DIR/src/exec:$PATH"
-
-#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"
-
+libpathappend "$PETSC_DIR/lib"
+
+SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
+libpathappend "$SLEPC_DIR/lib/$ISSM_ARCH"
+
+TAO_DIR="$ISSM_DIR/externalpackages/tao/install"
+libpathappend "$TAO_DIR/lib"
+
+DAKOTA_DIR="$ISSM_DIR/externalpackages/dakota/install"
+pathappend "$DAKOTA_DIR/bin"
+
+DOXYGEN_DIR="$ISSM_DIR/externalpackages/doxygen/install"
+pathappend "$DOXYGEN_DIR/bin"
+
+AUTOTOOLS_DIR="$ISSM_DIR/externalpackages/autotools/install"
+pathprepend "$AUTOTOOLS_DIR/bin"
+
+SDK_DIR="C:/MicrosoftVisualStudio 9.0/Microsoft Visual C++ 2008 Express Edition with SP1 - ENU"
+pathappend "$SDK_DIR"
+
+SSH_DIR="$ISSM_DIR/externalpackages/ssh"
+pathappend "$SSH_DIR"
+
+VALGRIND_DIR="$ISSM_DIR/externalpackages/valgrind/install"
+pathprepend "$VALGRIND_DIR/bin"
+
+CPPCHECK_DIR="$ISSM_DIR/externalpackages/cppcheck/install"
+pathappend "$CPPCHECK_DIR/bin"
+
+GDAL_DIR="$ISSM_DIR/externalpackages/gdal/install"
+pathprepend "$GDAL_DIR/bin:$PATH"
+libpathappend "$GDAL_DIR/lib"
+
+MERCURIAL_DIR="$ISSM_DIR/externalpackages/mercurial/install"
+if [ -d "$MERCURIAL_DIR" ]; then
+	export PYTHONPATH="$PYTHONPATH:$MERCURIAL_DIR/mercurial/pure/"
+	pathappend "$MERCURIAL_DIR"
+fi
+
+BOOST_DIR="$ISSM_DIR/externalpackages/boost/install"
+BOOSTROOT="$ISSM_DIR/externalpackages/boost/install"
+if [ -d "$BOOST_DIR" ]; then
+	export BOOSTROOT
+	export BOOST_DIR
+	libpathappend   "$BOOST_DIR/lib"
+	dylibpathappend "$BOOST_DIR/lib"
+	pathappend      "$BOOST_DIR/bin"
+fi
+
+XERCESROOT="$ISSM_DIR/externalpackages/xerces/install"
+XERCESCROOT="$ISSM_DIR/externalpackages/xerces/src"
+if [ -d "$XERCESROOT" ]; then
+	export XERCESROOT 
+	export XERCESCROOT
+fi
+
+XAIF_DIR="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
+XAIFBOOSTERROOT="$ISSM_DIR/externalpackages/xaifbooster/"
+XAIFBOOSTER_HOME="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
+PLATFORM="x86-Linux"
+if [ -d "$XAIF_DIR" ]; then
+	export XAIFBOOSTERROOT
+	export XAIFBOOSTER_HOME
+	export XAIF_DIR
+	export PLATFORM
+fi
+
+ANGELROOT="$ISSM_DIR/externalpackages/angel/angel"
+if [ -d "$ANGELROOT" ]; then
+	export ANGELROOT
+fi
+
+OPENANALYSISROOT="$ISSM_DIR/externalpackages/openanalysis/install"
+if [ -d "$OPENANALYSISROOT" ]; then
+	export OPENANALYSISROOT
+	libpathappend "$OPENANALYSISROOT/lib"
+fi
+
+JVM_DIR="/usr/local/gcc/4.3.2/lib64/gcj-4.3.2-9/"
+libpathappend "$JVM_DIR"
+
+BBFTP_DIR="$ISSM_DIR/externalpackages/bbftp/install"
+pathappend "$BBFTP_DIR/bin"
+
+ADIC_DIR="$ISSM_DIR/externalpackages/adic/install"
+pathappend "$ADIC_DIR/bin"
+libpathappend "$ADIC_DIR/lib"
+
+COLPACK_DIR="$ISSM_DIR/externalpackages/colpack/install"
+libpathappend "$COLPACK_DIR/lib"
+
+ECLIPSE_DIR="$ISSM_DIR/externalpackages/eclipse/install"
+pathappend "$ECLIPSE_DIR"
+
+APPSCAN_DIR="$ISSM_DIR/externalpackages/appscan/install"
+pathappend "$APPSCAN_DIR/bin"
+
+RATS_DIR="$ISSM_DIR/externalpackages/rats/install"
+pathappend "$RATS_DIR/bin"
+
+DYSON_DIR="$ISSM_DIR/externalpackages/dyson/"
+pathappend "$DYSON_DIR"
+
+CMAKE_DIR="$ISSM_DIR/externalpackages/cmake/install"
+pathappend "$CMAKE_DIR/bin"
+
+SHAPELIB_DIR="$ISSM_DIR/externalpackages/shapelib/install"
+pathappend "$SHAPELIB_DIR/exec"
+
+CCCL_DIR="$ISSM_DIR/externalpackages/cccl/install"
+pathappend "$CCCL_DIR/bin"
+
+PACKAGEMAKER_DIR="$ISSM_DIR/externalpackages/packagemaker/install"
+pathappend "$PACKAGEMAKER_DIR"
+
+ANDROID_NDK_DIR="$ISSM_DIR/externalpackages/android-ndk/install"
+pathappend "$ANDROID_NDK_DIR/"
+
+ANDROID_SDK_DIR="$ANDROID_DIR/android-sdk/install-sdk"
+pathappend "$ANDROID_SDK_DIR/"
+
+GSL_DIR="$ISSM_DIR/externalpackages/gsl/install"
+libpathappend "$GSL_DIR/lib"
+
+GMAKE_DIR="$ISSM_DIR/externalpackages/gmake/install"
+pathprepend "$GMAKE_DIR/bin"
+
+PYTHON_DIR="$ISSM_DIR/externalpackages/python/install"
+if [ -d "$PYTHON_DIR" ]; then
+	export PYTHONPATH="$PYTHONPATH:$ISSM_DIR/lib"
+	export PYTHONSTARTUP="$ISSM_DIR/startup.py"
+	pathprepend    "$PYTHON_DIR/bin"
+	libpathprepend "$ISSM_DIR/lib"
+	libpathprepend "$PYTHON_DIR/lib"
+fi
+
+MODELE_DIR="$ISSM_DIR/externalpackages/modelE/install"
+pathappend "$MODELE_DIR/src/exec"
+
+GIT_DIR="$ISSM_DIR/externalpackages/git/install"
+pathappend "$GIT_DIR/bin"
+
+NCVIEW_DIR="$ISSM_DIR/externalpackages/ncview/install"
+pathappend "$NCVIEW_DIR"
+
+TCLX_DIR="$ISSM_DIR/externalpackages/tclx/install/lib/tclx8.4"
+libpathappend "$TCLX_DIR"
+
+ASPELL_DIR="$ISSM_DIR/externalpackages/aspell/install"
+pathappend "$ASPELL_DIR/bin"
+
+HDF5_DIR="$ISSM_DIR/externalpackages/hdf5/install"
+if [ -d "$HDF5_DIR" ]; then
+	dylibpathappend "$HDF5_DIR/lib"
+	libpathappend "$HDF5_DIR/lib"
+	export LIBRARY_PATH="$LIBRARY_PATH:$HDF5_DIR/lib"
+	export C_INCLUDE_PATH="$C_INCLUDE_PATH:$HDF5_DIR/include"
+fi
+
+#NETCDF
+NETCDF_DIR="$ISSM_DIR/externalpackages/netcdf/install"
+if [ -d "$NETCDF_DIR" ]; then
+	export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$NETCDF_DIR/lib"
+	export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$NETCDF_DIR/lib"
+	export LIBRARY_PATH="$LIBRARY_PATH:$NETCDF_DIR/lib"
+	export C_INCLUDE_PATH="$C_INCLUDE_PATH:$NETCDF_DIR/include"
+fi
+
+#SVN
+SVN_DIR="$ISSM_DIR/externalpackages/svn/install"
+if [ -d "$SVN_DIR" ]; then
+	pathprepend   "$SVN_DIR/bin"
+	libpathappend "$SVN_DIR/lib"
+fi
+
+APR_DIR="$ISSM_DIR/externalpackages/apr/install"
+if [ -d "$APR_DIR" ]; then
+	pathappend    "$APR_DIR/bin"
+	libpathappend "$APR_DIR/lib"
+fi
+
+APR_UTIL_DIR="$ISSM_DIR/externalpackages/apr-util/install"
+pathappend   "$APR_UTIL_DIR/bin:$PATH"
+libpathappend "$APR_UTIL_DIR/lib"
+
+SQLITE_DIR="$ISSM_DIR/externalpackages/sqlite/install"
+pathappend   "$SQLITE_DIR/bin"
+libpathappend "$SQLITE_DIR/lib"
+
+YAMS_DIR="$ISSM_DIR/externalpackages/yams/install"
+pathappend   "$YAMS_DIR"
+
+SWIG_DIR="$ISSM_DIR/externalpackages/swig/install"
+pathappend   "$SWIG_DIR"
Index: sm/trunk/etc/environment_variables.csh
===================================================================
--- /issm/trunk/etc/environment_variables.csh	(revision 13394)
+++ 	(revision )
@@ -1,93 +1,0 @@
-#
-#
-#This routine can only be run if the ISSM_DIR variable has been correctly set!
-#
-#
-
-#MATLAB
-set MATLAB_DIR={$ISSM_DIR}/externalpackages/matlab/install
-
-#MPI
-set MPI_DIR={$ISSM_DIR}/externalpackages/mpich2/install
-
-#PETSC
-set PETSC_DIR={$ISSM_DIR}/externalpackages/petsc/install
-
-#SLEPC
-set SLEPC_DIR={$ISSM_DIR}/externalpackages/slepc/install
-
-#Dakota
-set DAKOTA_DIR={$ISSM_DIR}/externalpackages/dakota/install
-
-#Qhull
-set QHULL_DIR={$ISSM_DIR}/externalpackages/qhull/install
-
-#Doxygen
-set DOXYGEN_DIR={$ISSM_DIR}/externalpackages/doxygen/install
-
-#MTOC
-set MTOC_DIR={$ISSM_DIR}/externalpackages/mtoc/install
-
-#Triangle
-set TRIANGLE_DIR={$ISSM_DIR}/externalpackages/triangle/install
-
-#METIS
-set METIS_DIR={$ISSM_DIR}/externalpackages/metis/install
-
-#BLAS
-set BLAS_DIR={$ISSM_DIR}/externalpackages/petsc/install/externalexternalpackages/fblaslapack
-
-#LAPACK
-set LAPACK_DIR={$ISSM_DIR}/externalpackages/petsc/install/externalexternalpackages/fblaslapack/$ISSM_ARCH
-
-#SCALAPACK
-set SCALAPACK_DIR={$ISSM_DIR}/externalpackages/petsc/install/externalexternalpackages/SCALAPACK/$ISSM_ARCH
-
-#PLAPACK
-set PLAPACK_DIR={$ISSM_DIR}/externalpackages/petsc/install/externalexternalpackages/PLAPACKR32
-
-#BLACS
-set BLACS_DIR={$ISSM_DIR}/externalpackages/petsc/install/externalexternalpackages/blacs-dev/$ISSM_ARCH
-
-#sowing
-set SOWING_DIR={$ISSM_DIR}/externalpackages/sowing/install
-
-#YAMS
-set YAMS_DIR={$ISSM_DIR}/externalpackages/yams/install
-
-#TEX2IM
-set TEX2IM_DIR={$ISSM_DIR}/externalpackages/tex2im/install
-
-#Chaco
-set CHACO_DIR={$ISSM_DIR}/externalpackages/chaco/install
-
-#MeshPart
-set MESHPART_DIR={$ISSM_DIR}/externalpackages/meshpart/install
-
-#SCOTCH
-set SCOTCH_DIR={$ISSM_DIR}/externalpackages/scotch/install
-
-#Development packages
-#automake
-set AUTOMAKE_DIR={$ISSM_DIR}/externalpackages/automake/install
-
-#autoconf
-set AUTOCONF_DIR={$ISSM_DIR}/externalpackages/autoconf/install
-
-#borland
-set BORLAND_DIR=/cygdrive/c/Borland
-
-#ssh
-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: sm/trunk/etc/environment_variables.sh
===================================================================
--- /issm/trunk/etc/environment_variables.sh	(revision 13394)
+++ 	(revision )
@@ -1,214 +1,0 @@
-#
-#
-#This routine can only be run if the ISSM_DIR variable has been correctly set!
-#
-#
-
-#MATLAB
-MATLAB_DIR="$ISSM_DIR/externalpackages/matlab/install"
-
-#MPI
-MPI_DIR="$ISSM_DIR/externalpackages/mpich2/install"
-
-#PETSC
-PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install"
-
-#SLEPC
-SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
-
-#Dakota
-DAKOTA_DIR="$ISSM_DIR/externalpackages/dakota/install"
-
-#Qhull
-QHULL_DIR="$ISSM_DIR/externalpackages/qhull/install"
-
-#Doxygen
-DOXYGEN_DIR="$ISSM_DIR/externalpackages/doxygen/install"
-
-#MTOC
-MTOC_DIR="$ISSM_DIR/externalpackages/mtoc/install"
-
-#Triangle
-TRIANGLE_DIR="$ISSM_DIR/externalpackages/triangle/install"
-
-#METIS
-METIS_DIR="$ISSM_DIR/externalpackages/metis/install"
-
-#BLAS
-BLAS_DIR="$ISSM_DIR/externalpackages/petsc/install/externalpackages/fblaslapack"
-
-#LAPACK
-LAPACK_DIR="$ISSM_DIR/externalpackages/petsc/install/externalpackages/fblaslapack/$ISSM_ARCH"
-
-#SCALAPACK
-SCALAPACK_DIR="$ISSM_DIR/externalpackages/petsc/install/externalpackages/SCALAPACK/$ISSM_ARCH"
-
-#PLAPACK
-PLAPACK_DIR="$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32"
-
-#BLACS
-BLACS_DIR="$ISSM_DIR/externalpackages/petsc/install/externalpackages/blacs-dev/$ISSM_ARCH"
-
-#sowing
-SOWING_DIR="$ISSM_DIR/externalpackages/sowing/install"
-
-#BLACS
-BLACS_DIR="$ISSM_DIR/externalpackages/petsc/install/externalpackages/blacs-dev/$ISSM_ARCH"
-
-#YAMS
-YAMS_DIR="$ISSM_DIR/externalpackages/yams/install"
-
-#BAMG
-BAMG_DIR="$ISSM_DIR/externalpackages/bamg/install"
-
-#Chaco
-CHACO_DIR="$ISSM_DIR/externalpackages/chaco/install"
-
-#MeshPart
-MESHPART_DIR="$ISSM_DIR/externalpackages/meshpart/install"
-
-#SCOTCH
-SCOTCH_DIR="$ISSM_DIR/externalpackages/scotch/install"
-
-#Development packages
-#automake
-AUTOMAKE_DIR="$ISSM_DIR/externalpackages/automake/install"
-
-#libtool
-LIBTOOL_DIR="$ISSM_DIR/externalpackages/libtool/install"
-
-#autoconf
-AUTOCONF_DIR="$ISSM_DIR/externalpackages/autoconf/install"
-
-#borland
-#BORLAND_DIR="/cygdrive/c/Borland/"
-
-#intel
-#INTEL_DIR="C:/IntelInstall/Compiler/11.1/038/bin/ia32/"
-
-#TEX2IM			 
-TEX2IM_DIR="$ISSM_DIR/externalpackages/tex2im/install" 
-
-#sdk
-#SDK_DIR="C:/MicrosoftVisualStudio 9.0/Microsoft Visual C++ 2008 Express Edition with SP1 - ENU"
-
-#ssh 
-SSH_DIR="$ISSM_DIR/externalpackages/ssh"
-
-#valgrind
-VALGRIND_DIR="$ISSM_DIR/externalpackages/valgrind/install/bin"
-
-#graphviz
-GRAPHVIZ_DIR="$ISSM_DIR/externalpackages/graphviz/install/bin"
-
-#cppcheck
-CPPCHECK_DIR="$ISSM_DIR/externalpackages/cppcheck/install"
-
-#gdal
-GDAL_DIR="$ISSM_DIR/externalpackages/gdal/install"
-
-#mercurial
-MERCURIAL_DIR="$ISSM_DIR/externalpackages/mercurial/install"
-
-#boost
-BOOST_DIR="$ISSM_DIR/externalpackages/boost/install"
-BOOSTROOT="$ISSM_DIR/externalpackages/boost/install"
-
-#OpenAnalysis
-OPENANALYSISROOT="$ISSM_DIR/externalpackages/openanalysis/install"
-
-#xerces
-XERCESROOT="$ISSM_DIR/externalpackages/xerces/install"
-XERCESCROOT="$ISSM_DIR/externalpackages/xerces/src"
-
-#xaifBooster
-XAIFBOOSTERROOT="$ISSM_DIR/externalpackages/xaifbooster/"
-XAIF_DIR="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
-XAIFBOOSTER_HOME="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
-PLATFORM=x86-Linux
-
-#angel
-ANGELROOT="$ISSM_DIR/externalpackages/angel/angel"
-
-#java
-JVM_DIR=/usr/local/gcc/4.3.2/lib64/gcj-4.3.2-9/
-
-#bbftp
-BBFTP_DIR="$ISSM_DIR/externalpackages/bbftp/install"
-
-#adic2
-ADIC_DIR="$ISSM_DIR/externalpackages/adic/install"
-
-#colpack
-COLPACK_DIR="$ISSM_DIR/externalpackages/colpack/install"
-
-#eclipse
-ECLIPSE_DIR="$ISSM_DIR/externalpackages/eclipse/install"
-
-#flaim
-FLAIM_DIR="$ISSM_DIR/externalpackages/flaim/install"
-
-#appscan
-APPSCAN_DIR="$ISSM_DIR/externalpackages/appscan"
-
-#cppcheck
-CPPCHECK_DIR="$ISSM_DIR/externalpackages/cppcheck/install"
-
-#rats
-RATS_DIR="$ISSM_DIR/externalpackages/rats/install"
-
-#dyson
-DYSON_DIR="$ISSM_DIR/externalpackages/dyson/"
-
-#cmake
-CMAKE_DIR="$ISSM_DIR/externalpackages/cmake/install"
-
-#shapelib
-SHAPELIB_DIR="$ISSM_DIR/externalpackages/shapelib/install"
-
-#cccl
-CCCL_DIR="$ISSM_DIR/externalpackages/cccl/install"
-
-#packagemaker
-PACKAGEMAKER_DIR="$ISSM_DIR/externalpackages/packagemaker/install"
-
-#android-dev-dir
-ANDROID_DIR="$ISSM_DIR/externalpackages/android"
-
-#android-ndk
-ANDROID_NDK_DIR="$ANDROID_DIR/android-ndk/install"
-
-#android-sdk
-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"
-
-#gnu make
-GMAKE_DIR="$ISSM_DIR/externalpackages/gmake/install"
-
-#PYTHON
-PYTHON_DIR="$ISSM_DIR/externalpackages/python/install"
-PYTHONSTARTUP="$ISSM_DIR/startup.py"
-
-#MODELE
-MODELE_DIR="$ISSM_DIR/externalpackages/modelE"
-
-
-#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/trunk/externalpackages/adic/install.sh
===================================================================
--- /issm/trunk/externalpackages/adic/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/adic/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Erase install
@@ -26,5 +27,5 @@
 	--with-colpack=$ISSM_DIR/externalpackages/colpack/install\
 	--prefix=$ISSM_DIR/externalpackages/adic/install 
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/adolc/install-dev.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-dev.sh	(revision 13395)
+++ /issm/trunk/externalpackages/adolc/install-dev.sh	(revision 13395)
@@ -0,0 +1,20 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install adolc_v220_issm
+
+git clone -b 2.3.x_ISSM  git://gitorious.org/~utke/adol-c/adolc_v220_issm.git 
+
+#Compile ADOL-C
+cd adolc_v220_issm
+
+autoreconf -f -i 
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install 
+
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: sm/trunk/externalpackages/adolc/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-macosx64.sh	(revision 13394)
+++ 	(revision )
@@ -1,61 +1,0 @@
-#!/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/trunk/externalpackages/adolc/install.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/adolc/install.sh	(revision 13395)
@@ -1,14 +1,15 @@
 #!/bin/bash
+set -eu
 
 #some issues on macosx64 with ISSM's autoconf. you might want to run native to mac on this.
 
 #Some cleanup
-rm -rf install ADOL-C-2.2.0 src
+rm -rf install ADOL-C-2.2.0 src trunk
+
+#Create install directories
+mkdir install src
 
 #Download from ISSM server
 $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ADOL-C-2.2.0.tar.gz' 'ADOL-C-2.2.0.tar.gz'
-
-#Create install directories
-mkdir install src
 
 #Untar 
@@ -22,8 +23,8 @@
 cd src 
 
-export CC=gcc
-export CXX=g++
-export CFLAGS="-arch x86_64"
-export CXXFLAGS="-arch x86_64"
+#export CC=gcc
+#export CXX=g++
+#export CFLAGS="-arch x86_64"
+#export CXXFLAGS="-arch x86_64"
 
 ./configure \
@@ -34,5 +35,5 @@
 	--disable-shave
 
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
@@ -40,2 +41,20 @@
 fi
 make install
+
+
+#Ok, bug with libtool: replace all LIBTOOL= by LIBTOOL=libtool 
+#in all Makefiles
+for i in `find ./ -name Makefile `
+do
+	echo $i
+	cat $i | sed 's/LIBTOOL =/LIBTOOL = libtool/g' > $i.bak 
+	mv $i.bak $i
+done
+
+#remake: 
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/android/android-ndk/install.sh
===================================================================
--- /issm/trunk/externalpackages/android/android-ndk/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/android/android-ndk/install.sh	(revision 13395)
@@ -1,27 +1,32 @@
-#This installs the Android NDK (Native Development Kit)
-#which is needed for the compilation of C/C++ code into the 
-#native architecture of the Android device.
+#!/bin/bash
+set -eu
 
-#The android-ndk-r8-darwin-x86.tar.bz2 ndk.tar.bz2 file was downloaded 
-#from the android developer website: 
-source $ANDROID_DIR/android_variables.sh
+# This installs the Android NDK (Native Development Kit)
+# which is needed for the compilation of C/C++ code into the 
+# native architecture of the Android device.
 
-#Cleanup the install
-rm -rf install
-rm -rf $ANDROID_DIR/arm-linux-android-${default_droid}
+# The android-ndk-r8-darwin-x86.tar.bz2 ndk.tar.bz2 file was downloaded 
+# from the android developer website: 
+source $ANDROID_DIR/android_aux.sh
 
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/android-ndk-r'${ndk_rev}'-darwin-x86.tar.bz2' 'ndk.tar.bz2'
+if [[ $step == "1" || $step == "0" ]]; then
+    # Cleanup the install
+    rm -rf install
+    rm -rf $ANDROID_DIR/arm-linux-android-${default_droid}
 
-# Install Android SDK and NDK.
-bunzip2 ndk.tar.bz2
-tar -xvf ndk.tar
-rm -rf ndk.tar ndk.tar.bz2
+    # Download from ISSM server
+    $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/android-ndk-r'${ndk_rev}'-darwin-x86.tar.bz2' 'ndk.tar.bz2'
 
-#Move to install
-mv android-ndk-r${ndk_rev} install
+    # Untar
+    tar -zxvf ndk.tar.bz2
+    rm -rf ndk.tar ndk.tar.bz2
 
-#Create Standalone Development Directory
-#Note: API-14 corresponds to Android 4.0 although we are
-#calling our toolchain 4.1 to agree with our device.
-$ANDROID_NDK_DIR/build/tools/make-standalone-toolchain.sh --platform=android-14 --install-dir=$ANDROID_DIR/arm-linux-android-4.0
+    # Move to install
+    mv android-ndk-r${ndk_rev} install
+fi
+
+# Create Standalone Development Directory
+# Note: API-14 corresponds to Android 4.0.
+if [[ $step == "2" || $step == "0" ]]; then
+    $ANDROID_NDK_DIR/build/tools/make-standalone-toolchain.sh --platform=android-14 --install-dir=$ANDROID_DIR/arm-linux-android-4.0
+fi
Index: /issm/trunk/externalpackages/android/android-sdk/install.sh
===================================================================
--- /issm/trunk/externalpackages/android/android-sdk/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/android/android-sdk/install.sh	(revision 13395)
@@ -1,31 +1,26 @@
-#This installs the Android SDK (Software Development Kit)
-#which is needed for the compilation of the Java project. 
-source $ANDROID_DIR/android_variables.sh
+#!/bin/bash
+set -eu 
 
-step=1;
+# This installs the Android SDK (Software Development Kit)
+# which is needed for the compilation of the Java project. 
 
-#Different steps here. 
-#1: install sdk, ant and sdk tools
-#2: install an emulator.
-#3: test the emulator
-#4: cleanup
+source $ANDROID_DIR/android_aux.sh
+
+# Different steps here. 
+#   0: do all
+#   1: install sdk, ant and sdk tools
+#   2: install an emulator.
+#   3: test the emulator
+#   4: cleanup
 
 present_dir=`pwd`;
 sd_card="issm-sdcard"
 
-((tmp=$1 )) 
+if [[ $step == "1" || $step == "0" ]]; then
 
-if [[ $tmp -ge "1" && $tmp -le "4" ]]; then
-    step=$1
-else
-    echo "Using default step: " $step
-fi
-
-if [[ $step == "1" ]]; then
-
-	#Cleanup the install
+	# Cleanup the install
 	rm -rf install-sdk
 
-	#Download from ISSM server
+	# Download from ISSM server
 	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/android-sdk_r'$sdk_rev'-macosx.zip' 'android-sdk_r'${sdk_rev}'-macosx.zip'
 
@@ -33,15 +28,15 @@
 	unzip -o android-sdk_r${sdk_rev}-macosx.zip
 
-	#Move to install
+	# Move to install
 	mv -f android-sdk-macosx install-sdk
 
-	#Post_install configuration: 
-	#We need specific settings for specific platforms, for the SDK to 
-	#function properly
+	# Post_install configuration: 
+	# We need specific settings for specific platforms, for the SDK to 
+	# function properly
 
-	#For now, we need to install:  
-	#android sdk platform tools  
-	#and a specific android api: API 16, API 15 and API 14
-	#Note: API 16, API 15 and 14 correspond to Android 4.1, 4.0.3 and 4.0 respectively. 
+	# For now, we need to install:  
+	# android sdk platform tools  
+	# and a specific android api: API 16, API 15 and API 14
+	# Note: API 16, API 15 and 14 correspond to Android 4.1, 4.0.3 and 4.0 respectively. 
 
 	cd install-sdk/tools/ && source ./android update sdk -t platform-tool,${api_levels},system-image --no-ui
@@ -49,11 +44,11 @@
 fi
 
-if [[ $step == "2" ]]; then
+if [[ $step == "2" || $step == "0" ]]; then
 
-	#Once this is done, we need to install an emulator. Location will default to ~/.android/avd, 
-	#which we will move to $ISSM_DIR/externalpackages/android-emulators.  
-	#For now, it's called: Android-4.0.3
+	# Once this is done, we need to install an emulator. Location will default to ~/.android/avd, 
+	# which we will move to $ISSM_DIR/externalpackages/android-emulators.  
+	# For now, it's called: Android-4.0.3
 
-	#Here we delete the Android-4.0.3 device if it already exists.
+	# Here we delete the Android-4.0.3 device if it already exists.
 	cd $present_dir/install-sdk/tools
 
@@ -64,6 +59,6 @@
     fi
 
-	#Android will prompt the user to specify hardware emulation options. For now, default
-	#default settings will suffice. Press 'enter' to take default settings or enter 'no'.
+	# Android will prompt the user to specify hardware emulation options. For now, default
+	# default settings will suffice. Press 'enter' to take default settings or enter 'no'.
 
 	./android create avd -f -n $default_droid -t 1 -p $ANDROID_DIR/android-emulators/$default_droid --abi armeabi-v7a
@@ -72,8 +67,8 @@
 fi
 
-if [[ $step == "3" ]]; then
-    #Here we will start up our default emulator to test that it is working properly.
-    #Once the device has booted we will use the Android Debug Bridge tool to gain
-    #a terminal in our device.
+if [[ $step == "3" || $step == "0" ]]; then
+    # Here we will start up our default emulator to test that it is working properly.
+    # Once the device has booted we will use the Android Debug Bridge tool to gain
+    # a terminal in our device.
 
 	cd $present_dir/install-sdk/tools
@@ -82,12 +77,7 @@
     cd ../platform-tools
     ./adb wait-for-device shell
-    #./adb wait-for-device shell mount -o rw,remount -t yaffs2 /dev/block/mtdblock1 /system
-    #./adb wait-for-device shell
-    #./adb push $ISSM_TIER/src/c/issm.exe /data/issm.exe
-    #./adb shell chmod 777 /data/issm.exe
-    #./adb shell /data/issm.exe
 fi
 
-if [[ $step == "4" ]]; then
+if [[ $step == "4" || $step == "0" ]]; then
 	rm -rf install-sdk
 fi
Index: /issm/trunk/externalpackages/android/android_aux.sh
===================================================================
--- /issm/trunk/externalpackages/android/android_aux.sh	(revision 13395)
+++ /issm/trunk/externalpackages/android/android_aux.sh	(revision 13395)
@@ -0,0 +1,30 @@
+#!/bin/bash
+#
+# android_aux.sh serves as an auxiliary script for all installation
+# scripts with the Android suffix.
+#
+# TODO: include M4 macros for generic options.
+#
+
+sdk_rev=20
+ndk_rev=8
+api_levels="android-14,android-15,android-16"
+host_triplet="arm-linux-androideabi"
+default_droid="android-4.1"
+
+step=0;
+j=1;
+
+echo Number of arguments is: $#
+for arg in $* 
+do 
+    if [[ "$arg" =~ --step=([0-9])* ]]; then
+        step=${BASH_REMATCH[1]}; 
+        echo "Setting step to: " $step
+    elif [[ "$arg" =~ -j=([1-9]+[0-9]*) || "$arg" =~ ([1-9]+[0-9]*) ]]; then
+        j=${BASH_REMATCH[1]}; 
+        echo "Number of jobs set to: " $j
+    else
+        echo "Option not recognized"
+    fi
+done
Index: sm/trunk/externalpackages/android/android_variables.sh
===================================================================
--- /issm/trunk/externalpackages/android/android_variables.sh	(revision 13394)
+++ 	(revision )
@@ -1,5 +1,0 @@
-sdk_rev=20
-ndk_rev=8
-api_levels="android-14,android-15,android-16"
-host_triplet="arm-linux-androideabi"
-default_droid="android-4.1"
Index: /issm/trunk/externalpackages/angel/install.sh
===================================================================
--- /issm/trunk/externalpackages/angel/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/angel/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/appscan/install.sh
===================================================================
--- /issm/trunk/externalpackages/appscan/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/appscan/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #AppScan install directory. Just symlink to your existing AppScan software
Index: /issm/trunk/externalpackages/apr-util/install.sh
===================================================================
--- /issm/trunk/externalpackages/apr-util/install.sh	(revision 13395)
+++ /issm/trunk/externalpackages/apr-util/install.sh	(revision 13395)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf apr-util-1.4.1
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/apr-util-1.4.1.tar.gz' 'apr-util-1.4.1.tar.gz'
+
+#Untar 
+tar -zxvf  apr-util-1.4.1.tar.gz
+
+#Move apr-util into src directory
+mv apr-util-1.4.1/* src
+rm -rf apr-util-1.4.1
+
+#Configure apr-util
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/apr-util/install" --with-apr="$ISSM_DIR/externalpackages/apr/install"
+
+#Compile and install apr-util
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/apr/install.sh
===================================================================
--- /issm/trunk/externalpackages/apr/install.sh	(revision 13395)
+++ /issm/trunk/externalpackages/apr/install.sh	(revision 13395)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf apr-1.4.6
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/apr-1.4.6.tar.gz' 'apr-1.4.6.tar.gz'
+
+#Untar 
+tar -zxvf  apr-1.4.6.tar.gz
+
+#Move apr into src directory
+mv apr-1.4.6/* src
+rm -rf apr-1.4.6
+
+#Configure apr
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/apr/install" 
+
+#Compile and install apr
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/aspell/install.sh
===================================================================
--- /issm/trunk/externalpackages/aspell/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/aspell/install.sh	(revision 13395)
@@ -1,8 +1,9 @@
 #!/bin/bash
+set -eu
 
 #0: cleanup
 #1:  install aspell
 #2:  install en dictionary
-step=0
+step=2
 
 
Index: /issm/trunk/externalpackages/autotools/install.sh
===================================================================
--- /issm/trunk/externalpackages/autotools/install.sh	(revision 13395)
+++ /issm/trunk/externalpackages/autotools/install.sh	(revision 13395)
@@ -0,0 +1,44 @@
+#!/bin/bash
+set -eu
+
+rm -rf install
+mkdir install
+
+export PATH="$ISSM_DIR/externalpackages/autotools/install/bin:$PATH"
+
+#install autoconf
+echo " === INSTALLING AUTOCONF =="
+rm -rf src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/autoconf-2.68.tar.gz' 'autoconf-2.68.tar.gz'
+tar -zxvf autoconf-2.68.tar.gz
+mv autoconf-2.68 src
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
+make  
+make install
+cd ..
+
+#install automake
+echo " === INSTALLING AUTOMAKE =="
+rm -rf src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/automake-1.11.3.tar.gz' 'automake-1.11.3.tar.gz'
+tar -zxvf  automake-1.11.3.tar.gz
+mv automake-1.11.3 src
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
+make  
+make install
+cd ..
+
+#install libtool
+echo " === INSTALLING LIBTOOL =="
+rm -rf src
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libtool-2.4.2.tar.gz' 'libtool-2.4.2.tar.gz'
+tar -zxvf  libtool-2.4.2.tar.gz
+rm libtool-2.4.2.tar.gz
+mv libtool-2.4.2 src
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/autotools/install" 
+make  
+make install
+cd ..
Index: /issm/trunk/externalpackages/bbftp/install.sh
===================================================================
--- /issm/trunk/externalpackages/bbftp/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/bbftp/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/blas/configs/macosx64/make.inc
===================================================================
--- /issm/trunk/externalpackages/blas/configs/macosx64/make.inc	(revision 13395)
+++ /issm/trunk/externalpackages/blas/configs/macosx64/make.inc	(revision 13395)
@@ -0,0 +1,34 @@
+####################################################################
+#  BLAS make include file.                                         #
+#  March 2007                                                      #
+####################################################################
+#
+SHELL = /bin/sh
+#
+#  The machine (platform) identifier to append to the library names
+#
+PLAT = _LINUX
+#  
+#  Modify the FORTRAN and OPTS definitions to refer to the
+#  compiler and desired compiler options for your machine.  NOOPT
+#  refers to the compiler options desired when NO OPTIMIZATION is
+#  selected.  Define LOADER and LOADOPTS to refer to the loader and 
+#  desired load options for your machine.
+#
+FORTRAN  = gfortran
+OPTS     = -fPIC -O3
+DRVOPTS  = $(OPTS)
+NOOPT    =
+LOADER   = gfortran
+LOADOPTS =
+#
+#  The archiver and the flag(s) to use when building archive (library)
+#  If you system has no ranlib, set RANLIB = echo.
+#
+ARCH     = ar
+ARCHFLAGS= cr
+RANLIB   = ranlib
+#
+#  The location and name of the Reference BLAS library.
+#
+BLASLIB      = blas$(PLAT).a
Index: /issm/trunk/externalpackages/blas/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/blas/install-linux64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/blas/install-linux64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu 
 
 #Some cleanup
Index: /issm/trunk/externalpackages/blas/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/blas/install-macosx64.sh	(revision 13395)
+++ /issm/trunk/externalpackages/blas/install-macosx64.sh	(revision 13395)
@@ -0,0 +1,29 @@
+#!/bin/bash
+set -eu 
+
+#Some cleanup
+rm -rf src install BLAS blas.tgz
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/blas.tgz' 'blas.tgz'
+
+#Untar 
+tar -zxvf  blas.tgz
+
+#Move blas into install directory
+mv BLAS/* src
+rm -rf BLAS
+
+#install
+cd src 
+cp ../configs/macosx64/make.inc ./
+make 
+
+#Compile 
+cd ../install
+mkdir lib
+cd lib
+cp ../../src/*.a .
+ln -s blas_LINUX.a blas.a
+ln -s blas_LINUX.a libblas.a
Index: /issm/trunk/externalpackages/boost/install-macosx-snowleopard.sh
===================================================================
--- /issm/trunk/externalpackages/boost/install-macosx-snowleopard.sh	(revision 13395)
+++ /issm/trunk/externalpackages/boost/install-macosx-snowleopard.sh	(revision 13395)
@@ -0,0 +1,35 @@
+#!/bin/bash
+
+#Note of caution:  stop after boostrap phase, and run 
+#bjam --debug-configuration, to figure out which paths boost is using to include 
+#python. make sure everyone of these paths is covered by python. If not, just make 
+#symlinks in externalpackages/python to what boost is expecting. Ther is NO WAY 
+#to get the boost library to include python support without doing that. 
+
+#Some cleanup
+rm -rf install boost_1_49_0 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/boost_1_49_0.tar.gz' 'boost_1_49_0.tar.gz'
+
+#Untar 
+tar -zxvf  boost_1_49_0.tar.gz
+
+#Move boost into install directory
+mv boost_1_49_0/* src
+rm -rf boost_1_49_0
+#Configure and compile
+cd src 
+./bootstrap.sh \
+	--prefix="$ISSM_DIR/externalpackages/boost/install" \
+	--with-python=python2.7 \
+	--with-python-root="$ISSM_DIR/externalpackages/python/install" 
+
+#Compile boost
+#./b2 address-model=32 architecture=x86 cxxflags="-arch i386" variant=release threading=multi install
+./b2 toolset=darwin address-model=32 architecture=x86 variant=release threading=multi install
+
+#put bjam into install also: 
+mkdir ../install/bin
+cp bjam ../install/bin
Index: /issm/trunk/externalpackages/boost/install.sh
===================================================================
--- /issm/trunk/externalpackages/boost/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/boost/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Note of caution:  stop after boostrap phase, and run 
Index: /issm/trunk/externalpackages/bsdtar/install-win7.sh
===================================================================
--- /issm/trunk/externalpackages/bsdtar/install-win7.sh	(revision 13394)
+++ /issm/trunk/externalpackages/bsdtar/install-win7.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/cccl/install-win7.orig.sh
===================================================================
--- /issm/trunk/externalpackages/cccl/install-win7.orig.sh	(revision 13394)
+++ /issm/trunk/externalpackages/cccl/install-win7.orig.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/cccl/install-win7.sh
===================================================================
--- /issm/trunk/externalpackages/cccl/install-win7.sh	(revision 13394)
+++ /issm/trunk/externalpackages/cccl/install-win7.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/chaco/install.sh
===================================================================
--- /issm/trunk/externalpackages/chaco/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/chaco/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 # Some cleanup
@@ -23,5 +24,5 @@
 # Build chaco
 cd src/code
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/cmake/install.sh
===================================================================
--- /issm/trunk/externalpackages/cmake/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/cmake/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu 
 
 #Some cleanup
@@ -18,5 +19,5 @@
 cd install 
 ./bootstrap --prefix=$ISSM_DIR/externalpackages/cmake/install
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else 
Index: /issm/trunk/externalpackages/colpack/install.sh
===================================================================
--- /issm/trunk/externalpackages/colpack/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/colpack/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Erase install
@@ -15,5 +16,5 @@
 #compile
 cd src
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/cppcheck/install.sh
===================================================================
--- /issm/trunk/externalpackages/cppcheck/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/cppcheck/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Erase install
@@ -14,5 +15,5 @@
 #compile
 cd src
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make 
 else 
Index: /issm/trunk/externalpackages/dace/install.sh
===================================================================
--- /issm/trunk/externalpackages/dace/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/dace/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/dakota/install-altix64-cosmos.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-altix64-cosmos.sh	(revision 13394)
+++ /issm/trunk/externalpackages/dakota/install-altix64-cosmos.sh	(revision 13395)
@@ -1,6 +1,4 @@
 #!/bin/bash
-
-#Get number of cpus
-NUMCPUS=$1;
+set -eu
 
 #Some cleanup
@@ -84,11 +82,11 @@
 #Compile and install dakota
 cd src 
-if [ -z $NUMCPUS ];
+if [ $# -eq 0 ];
 then
 	make
 	make install
 else
-	make -j $NUMCPUS
-	make -j $NUMCPUS install
+	make -j $1
+	make -j $1 install
 fi
 cd ..
Index: /issm/trunk/externalpackages/dakota/install-discover.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-discover.sh	(revision 13394)
+++ /issm/trunk/externalpackages/dakota/install-discover.sh	(revision 13395)
@@ -1,6 +1,4 @@
 #!/bin/bash
-
-#Get number of cpus
-NUMCPUS=$1;
+set -eu
 
 #Some cleanup
@@ -84,11 +82,11 @@
 #Compile and install dakota
 cd src
-if [ -z $NUMCPUS ];
+if [ $# -eq 0 ];
 then
 	make
 	make install
 else
-	make -j $NUMCPUS
-	make -j $NUMCPUS install
+	make -j $1
+	make -j $1 install
 fi
 cd ..
Index: /issm/trunk/externalpackages/dakota/install-linux64-astrid.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-linux64-astrid.sh	(revision 13394)
+++ /issm/trunk/externalpackages/dakota/install-linux64-astrid.sh	(revision 13395)
@@ -1,6 +1,4 @@
 #!/bin/bash
-
-#Get number of cpus
-NUMCPUS=$1;
+set -eu
 
 #Some cleanup
@@ -84,11 +82,11 @@
 #Compile and install dakota
 cd src 
-if [ -z $NUMCPUS ];
+if [ $# -eq 0 ];
 then
 	make
 	make install
 else
-	make -j $NUMCPUS
-	make -j $NUMCPUS install
+	make -j $1
+	make -j $1 install
 fi
 cd ..
Index: /issm/trunk/externalpackages/dakota/install-linux64-murdo.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-linux64-murdo.sh	(revision 13394)
+++ /issm/trunk/externalpackages/dakota/install-linux64-murdo.sh	(revision 13395)
@@ -1,6 +1,4 @@
 #!/bin/bash
-
-#Get number of cpus
-NUMCPUS=$1;
+set -eu
 
 #Some cleanup
@@ -84,11 +82,11 @@
 #Compile and install dakota
 cd src 
-if [ -z $NUMCPUS ];
+if [ $# -eq 0 ];
 then
 	make
 	make install
 else
-	make -j $NUMCPUS
-	make -j $NUMCPUS install
+	make -j $1
+	make -j $1 install
 fi
 cd ..
Index: /issm/trunk/externalpackages/dakota/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-macosx64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/dakota/install-macosx64.sh	(revision 13395)
@@ -1,6 +1,4 @@
 #!/bin/bash
-
-#Get number of cpus
-NUMCPUS=$1;
+set -eu
 
 #Some cleanup
@@ -37,5 +35,5 @@
    --disable-mpi \
    --with-blas="-L$ISSM_DIR/externalpackages/petsc/install/lib -lfblas " \
-   --with-lapack="-L$ISSM_DIR/externalpackages/petsc/install/lib -lflapack -lPLAPACK "
+   --with-lapack="-L$ISSM_DIR/externalpackages/petsc/install/lib -lflapack "
 cd ..
 
@@ -84,11 +82,11 @@
 #Compile and install dakota
 cd src 
-if [ -z $NUMCPUS ];
+if [ $# -eq 0 ];
 then
 	make
 	make install
 else
-	make -j $NUMCPUS
-	make -j $NUMCPUS install
+	make -j $1
+	make -j $1 install
 fi
 cd ..
Index: /issm/trunk/externalpackages/dakota/install-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-pleiades.sh	(revision 13394)
+++ /issm/trunk/externalpackages/dakota/install-pleiades.sh	(revision 13395)
@@ -1,12 +1,10 @@
 #!/bin/bash
-
-#Get number of cpus
-NUMCPUS=$1;
+set -eu
 
 #Some cleanup
 rm -rf Dakota
-rm -rf src 
-rm -rf install 
-mkdir src install 
+rm -rf src
+rm -rf install
+mkdir src install
 
 #Download from ISSM server
@@ -31,11 +29,11 @@
 #Configure dakota
 cd src
-./configure \ 
-	--prefix="$ISSM_DIR/externalpackages/dakota/install" \
-	--without-graphics  \
-	--with-pic \
-	--disable-mpi \
-	--with-blas="-L/nasa/intel/mkl/10.0.011/lib/64/ -lmkl -lmkl_lapack -liomp5 -lpthread" \
-	--with-lapack="-L/nasa/intel/mkl/10.0.011/lib/64/ -lmkl -lmkl_lapack -liomp5 -lpthread" 
+./configure \
+--prefix="$ISSM_DIR/externalpackages/dakota/install/" \
+--without-graphics  \
+--with-pic \
+--disable-mpi \
+--with-blas="-L/nasa/intel/mkl/10.0.011/lib/64/ -lmkl -lmkl_lapack -liomp5 -lpthread" \
+--with-lapack="-L/nasa/intel/mkl/10.0.011/lib/64/ -lmkl -lmkl_lapack -liomp5 -lpthread"
 cd ..
 
@@ -53,17 +51,17 @@
 
 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 
+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 
+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 
+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 
+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 
+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
@@ -74,21 +72,21 @@
 
 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 
+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 
+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 
+mv temp  ./src/packages/ampl/Makefile
 
 #Compile and install dakota
-cd src 
-if [ -z $NUMCPUS ];
+cd src
+if [ $# -eq 0 ];
 then
 	make
 	make install
 else
-	make -j $NUMCPUS
-	make -j $NUMCPUS install
+	make -j $1
+	make -j $1 install
 fi
 cd ..
Index: /issm/trunk/externalpackages/distribute/install.sh
===================================================================
--- /issm/trunk/externalpackages/distribute/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/distribute/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Download from ISSM server
Index: /issm/trunk/externalpackages/doxygen/install.sh
===================================================================
--- /issm/trunk/externalpackages/doxygen/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/doxygen/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -9,5 +10,5 @@
 #Configure doxygen
 cd install && ./configure --prefix "$ISSM_DIR/externalpackages/doxygen/install"
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/esmf/install.sh
===================================================================
--- /issm/trunk/externalpackages/esmf/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/esmf/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #0: cleanup
@@ -32,5 +33,5 @@
 
 	#Compile and install esmf
-	if [ -z $1 ]; then
+	if [ $# -eq 0 ]; then
 		make
 		make install
@@ -43,5 +44,5 @@
 if [[ $install == "2" ]]; then
 	cd esmf
-	if [ -z $1 ]; then
+	if [ $# -eq 0 ]; then
 		make all_tests
 	else
Index: /issm/trunk/externalpackages/findbugs/install.sh
===================================================================
--- /issm/trunk/externalpackages/findbugs/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/findbugs/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Erase install
Index: /issm/trunk/externalpackages/flaim/install.sh
===================================================================
--- /issm/trunk/externalpackages/flaim/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/flaim/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Erase symlink
Index: /issm/trunk/externalpackages/freetype/install.sh
===================================================================
--- /issm/trunk/externalpackages/freetype/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/freetype/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -22,5 +23,5 @@
 
 #Compile and install freetype
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	sudo make
 else
Index: /issm/trunk/externalpackages/gdal/install-murdo.sh
===================================================================
--- /issm/trunk/externalpackages/gdal/install-murdo.sh	(revision 13395)
+++ /issm/trunk/externalpackages/gdal/install-murdo.sh	(revision 13395)
@@ -0,0 +1,39 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf gdal-1.6.0
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gdal-1.6.0.tar.gz' 'gdal-1.6.0.tar.gz'
+
+#Untar 
+tar -zxvf  gdal-1.6.0.tar.gz
+
+#Move gdal into src directory
+mv gdal-1.6.0/* src
+rm -rf gdal-1.6.0
+
+#Configure gdal
+cd src
+./configure --prefix="$ISSM_DIR/externalpackages/gdal/install" \
+	--without-python \
+	--without-png \
+	--with-netcdf=no \
+	--with-jasper=no \
+	--without-ld-shared \
+	--with-unix-stdio-64=no 
+
+#Patch GDALmake.opt
+patch GDALmake.opt ../GDALmake.opt.patch
+
+#Compile and install gdal
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/gdal/install.sh
===================================================================
--- /issm/trunk/externalpackages/gdal/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/gdal/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -22,4 +23,5 @@
 	--prefix="$ISSM_DIR/externalpackages/gdal/install" \
 	--without-python \
+	--without-png \
 	--with-netcdf=no \
 	--with-jasper=no \
@@ -32,5 +34,5 @@
 
 #Compile and install gdal
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/gdaltokmz/install.sh
===================================================================
--- /issm/trunk/externalpackages/gdaltokmz/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/gdaltokmz/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Download from ISSM server
Index: /issm/trunk/externalpackages/geos5/install.sh
===================================================================
--- /issm/trunk/externalpackages/geos5/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/geos5/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/git/install-nopython.sh
===================================================================
--- /issm/trunk/externalpackages/git/install-nopython.sh	(revision 13395)
+++ /issm/trunk/externalpackages/git/install-nopython.sh	(revision 13395)
@@ -0,0 +1,23 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install git-1.7.10.2
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/git-1.7.10.2.tar.gz' 'git-1.7.10.2.tar.gz'
+
+#Untar 
+tar -zxvf  git-1.7.10.2.tar.gz
+
+#Move git into install directory
+mv git-1.7.10.2/* src
+rm -rf git-1.7.10.2
+
+#install
+cd src 
+./configure  --prefix="$ISSM_DIR/externalpackages/git/install"
+	
+#Compile
+make install
Index: /issm/trunk/externalpackages/git/install.sh
===================================================================
--- /issm/trunk/externalpackages/git/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/git/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -17,5 +18,5 @@
 #install
 cd src 
-./configure  --prefix="$ISSM_DIR/externalpackages/git/install"
+./configure  --prefix="$ISSM_DIR/externalpackages/git/install" --with-python="$ISSM_DIR/externalpackages/python/install/bin/python"
 	
 #Compile
Index: /issm/trunk/externalpackages/gmake/install.sh
===================================================================
--- /issm/trunk/externalpackages/gmake/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/gmake/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -21,5 +22,5 @@
 ./configure --prefix=$ISSM_DIR/externalpackages/gmake/install
 
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 	make install
Index: /issm/trunk/externalpackages/googleearthtoolbox/install.sh
===================================================================
--- /issm/trunk/externalpackages/googleearthtoolbox/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/googleearthtoolbox/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/graphviz/install.sh
===================================================================
--- /issm/trunk/externalpackages/graphviz/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/graphviz/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -22,5 +23,5 @@
 #Compile and install
 cd src
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/gsl/install-android.sh
===================================================================
--- /issm/trunk/externalpackages/gsl/install-android.sh	(revision 13394)
+++ /issm/trunk/externalpackages/gsl/install-android.sh	(revision 13395)
@@ -1,33 +1,45 @@
 #!/bin/bash
-source $ANDROID_DIR/android_variables.sh
+set -eu
 
-#Some cleanup
-rm -rf src install gsl-1.15
-mkdir src install
+source $ANDROID_DIR/android_aux.sh
 
-#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'
+if [[ $step == "1" || $step == "0" ]]; then
 
-#Untar 
-tar -zxvf  gsl-1.15.tar.gz
+    #Some cleanup
+    rm -rf src install gsl-1.15
+    mkdir src install
 
-#Move gsl into src directory
-mv gsl-1.15/* src
-rm -rf gsl-1.15
+    #Download from ISSM server
+    $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gsl-1.' 'gsl-1.15.tar.gz'
+
+    #Untar 
+    tar -zxvf  gsl-1.15.tar.gz
+
+    #Move gsl into src directory
+    mv gsl-1.15/* src
+    rm -rf gsl-1.15
+fi
 
 #Configure gsl
-cd src
+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" 
+    ./configure \
+        --build="i386-apple-darwin10.8.0" \
+        --host=$host_triplet \
+	    --prefix="$ISSM_DIR/externalpackages/gsl/install/" \
+        --disable-static
+fi
 
 #Compile gsl
-if [ -z $1 ]; then
-	make
-else
-	make -j $1
+if [[ $step == "3" || $step == "0" ]]; then
+    if [ $# -eq 0 ]; then
+	    make $j 
+    else
+	    make -j $j 
+    fi
+
+    make install
 fi
-
-make install
Index: /issm/trunk/externalpackages/gsl/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/gsl/install-linux64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/gsl/install-linux64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -22,5 +23,5 @@
 
 #Compile gsl
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/gsl/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/gsl/install-macosx64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/gsl/install-macosx64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -24,5 +25,5 @@
 
 #Compile gsl
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/gsl/install-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/gsl/install-pleiades.sh	(revision 13394)
+++ /issm/trunk/externalpackages/gsl/install-pleiades.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -22,5 +23,5 @@
 
 #Compile gsl
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/gslib/install.sh
===================================================================
--- /issm/trunk/externalpackages/gslib/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/gslib/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/h5py/install.sh
===================================================================
--- /issm/trunk/externalpackages/h5py/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/h5py/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #needed further along
Index: /issm/trunk/externalpackages/hdf5/install.sh
===================================================================
--- /issm/trunk/externalpackages/hdf5/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/hdf5/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -19,5 +20,5 @@
 cd src
 ./configure  --prefix="$ISSM_DIR/externalpackages/hdf5/install" 
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/ipython/install.sh
===================================================================
--- /issm/trunk/externalpackages/ipython/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/ipython/install.sh	(revision 13395)
@@ -1,19 +1,19 @@
 #!/bin/bash
+set -eu 
 
 #Some cleanup
 rm -rf src
-rm -rf install
-rm -rf ipython-0.12
-mkdir src install
+rm -rf ipython-0.13
+mkdir src 
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ipython-0.12.tar.gz' 'ipython-0.12.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ipython-0.13.tar.gz' 'ipython-0.13.tar.gz'
 
 #Untar 
-tar -zxvf  ipython-0.12.tar.gz
+tar -zxvf  ipython-0.13.tar.gz
 
 #Move ipython into src directory
-mv ipython-0.12/* src
-rm -rf ipython-0.12
+mv ipython-0.13/* src
+rm -rf ipython-0.13
 
 #install  ipython
Index: /issm/trunk/externalpackages/kml/install.sh
===================================================================
--- /issm/trunk/externalpackages/kml/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/kml/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Download from ISSM server
Index: /issm/trunk/externalpackages/lapack/configs/linux64/make.inc
===================================================================
--- /issm/trunk/externalpackages/lapack/configs/linux64/make.inc	(revision 13394)
+++ /issm/trunk/externalpackages/lapack/configs/linux64/make.inc	(revision 13395)
@@ -16,5 +16,5 @@
 OPTS     = -fPIC -O2
 DRVOPTS  = $(OPTS)
-NOOPT    = -O0
+NOOPT    = -fPIC -O0
 LOADER   = gfortran
 LOADOPTS =
Index: /issm/trunk/externalpackages/lapack/configs/macosx64/make.inc
===================================================================
--- /issm/trunk/externalpackages/lapack/configs/macosx64/make.inc	(revision 13395)
+++ /issm/trunk/externalpackages/lapack/configs/macosx64/make.inc	(revision 13395)
@@ -0,0 +1,71 @@
+####################################################################
+#  LAPACK make include file.                                       #
+#  LAPACK, Version 3.4.0                                           #
+#  April 2012                                                   #
+####################################################################
+#
+SHELL = /bin/sh
+#  
+#  Modify the FORTRAN and OPTS definitions to refer to the
+#  compiler and desired compiler options for your machine.  NOOPT
+#  refers to the compiler options desired when NO OPTIMIZATION is
+#  selected.  Define LOADER and LOADOPTS to refer to the loader and 
+#  desired load options for your machine.
+#
+FORTRAN  = gfortran 
+OPTS     = -fPIC -O2
+DRVOPTS  = $(OPTS)
+NOOPT    = -fPIC -O0
+LOADER   = gfortran
+LOADOPTS =
+#
+# Timer for the SECOND and DSECND routines
+#
+# Default : SECOND and DSECND will use a call to the EXTERNAL FUNCTION ETIME
+#TIMER    = EXT_ETIME
+# For RS6K : SECOND and DSECND will use a call to the EXTERNAL FUNCTION ETIME_
+# TIMER    = EXT_ETIME_
+# For gfortran compiler: SECOND and DSECND will use a call to the INTERNAL FUNCTION ETIME
+TIMER    = INT_ETIME
+# If your Fortran compiler does not provide etime (like Nag Fortran Compiler, etc...)
+# SECOND and DSECND will use a call to the INTERNAL FUNCTION CPU_TIME
+# TIMER    = INT_CPU_TIME
+# If neither of this works...you can use the NONE value... In that case, SECOND and DSECND will always return 0
+# TIMER     = NONE
+#
+#  Configuration LAPACKE: Native C interface to LAPACK
+#  To generate LAPACKE library: type 'make lapackelib'
+#  Configuration file: turned off (default)
+#  Complex types: C99 (default)
+#  Name pattern: mixed case (default)
+#  (64-bit) Data model: LP64 (default)
+#
+# CC is the C compiler, normally invoked with options CFLAGS.
+#
+CC = gcc
+CFLAGS = -O3
+#
+#  The archiver and the flag(s) to use when building archive (library)
+#  If you system has no ranlib, set RANLIB = echo.
+#
+ARCH     = ar
+ARCHFLAGS= cr
+RANLIB   = ranlib
+#
+#  Location of the extended-precision BLAS (XBLAS) Fortran library
+#  used for building and testing extended-precision routines.  The
+#  relevant routines will be compiled and XBLAS will be linked only if
+#  USEXBLAS is defined.
+#
+# USEXBLAS    = Yes
+XBLASLIB     =
+# XBLASLIB    = -lxblas
+#
+#  The location of the libraries to which you will link.  (The 
+#  machine-specific, optimized BLAS library should be used whenever
+#  possible.)
+#
+BLASLIB      = ../../librefblas.a
+LAPACKLIB    = liblapack.a
+TMGLIB       = libtmglib.a
+LAPACKELIB   = liblapacke.a
Index: /issm/trunk/externalpackages/lapack/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/lapack/install-linux64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/lapack/install-linux64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -20,5 +21,5 @@
 
 #Compile and install lapack
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make lib
 else
Index: /issm/trunk/externalpackages/lapack/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/lapack/install-macosx64.sh	(revision 13395)
+++ /issm/trunk/externalpackages/lapack/install-macosx64.sh	(revision 13395)
@@ -0,0 +1,33 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install lapack-3.4.1 lapack-3.4.1.tgz
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/lapack-3.4.1.tgz' 'lapack-3.4.1.tgz'
+
+#Untar 
+tar -zxvf  lapack-3.4.1.tgz
+
+#Move lapack into install directory
+mv lapack-3.4.1/* src
+rm -rf lapack-3.4.1
+
+#install
+cd src 
+cp ../configs/macosx64/make.inc ./
+
+#Compile and install lapack
+if [ $# -eq 0 ]; then
+	make lib
+else
+	make -j $1 lib
+fi
+
+#Compile 
+cd ../install
+mkdir lib
+cd lib
+cp ../../src/liblapack.a .
Index: /issm/trunk/externalpackages/latex2rtf/install.sh
===================================================================
--- /issm/trunk/externalpackages/latex2rtf/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/latex2rtf/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/libermate/install.sh
===================================================================
--- /issm/trunk/externalpackages/libermate/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/libermate/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/libpng/install.sh
===================================================================
--- /issm/trunk/externalpackages/libpng/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/libpng/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -22,5 +23,5 @@
 
 #Compile and install libpng
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	sudo make
 else
Index: /issm/trunk/externalpackages/m2html/install.sh
===================================================================
--- /issm/trunk/externalpackages/m2html/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/m2html/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/matlab/install.sh
===================================================================
--- /issm/trunk/externalpackages/matlab/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/matlab/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Erase symlink
@@ -5,9 +6,9 @@
 
 #Select or create a new simlink
-ln -s /usr/local/pkgs/matlab-7.6/ install
+#ln -s /usr/local/pkgs/matlab-7.6/ install
 #ln -s /discover/vis/mathworks/matlab_r2011b/ install
 #ln -s /usr/local/matlab704/ install
 #ln -s /usr/local/matlab711/ install
-#ln -s /usr/local/matlab712/ install
+ln -s /usr/local/matlab712/ install
 
 # Macintosh (OSX) simlink 
@@ -16,3 +17,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/trunk/externalpackages/matplotlib/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/matplotlib/install-linux64.sh	(revision 13395)
+++ /issm/trunk/externalpackages/matplotlib/install-linux64.sh	(revision 13395)
@@ -0,0 +1,14 @@
+#/bin/bash
+set -eu
+export GIT_SSL_NO_VERIFY=true 
+export CC="gcc -fPIC "
+export CXX="g++ -fPIC -L$ISSM_DIR/externalpackages/tcl/install/lib"
+export F77="gfortran -fPIC"
+export FC="gfortran -fPIC"
+export FFLAGS=-ff2c
+
+git clone https://github.com/matplotlib/matplotlib
+mv matplotlib src
+cd src
+python setup.py build 
+python setup.py install 
Index: /issm/trunk/externalpackages/matplotlib/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/matplotlib/install-macosx64.sh	(revision 13395)
+++ /issm/trunk/externalpackages/matplotlib/install-macosx64.sh	(revision 13395)
@@ -0,0 +1,27 @@
+#/bin/bash
+set -eu
+
+export C_INCLUDE_PATH="$C_INCLUDE_PATH:/usr/include/c++/4.2.1"
+export GIT_SSL_NO_VERIFY=true 
+export CC="gcc -fPIC -arch x86_64 -I/usr/include/c++/4.2.1"
+export CXX="g++ -fPIC -arch x86_64 -I/usr/include/c++/4.2.1"
+export F77="gfortran -fPIC -arch x86_64 -I/usr/include/c++/4.2.1"
+export FC="gfortran -fPIC -arch x86_64 -I/usr/include/c++/4.2.1"
+export FFLAGS="-ff2c -arch x86_64 -I/usr/include/c++/4.2.1"
+export ARCHFLAGS="-arch x86_64 -I/usr/include/c++/4.2.1"
+
+git clone https://github.com/matplotlib/matplotlib
+mv matplotlib src
+mkdir deps
+cd src
+
+#only try this if the classic python setup.py build approach does not work. The approach in the next 3 lines can 
+#trigger issues of permissions with freetype. Sometimes it is better to independently install freetype2 (from the 
+#issm externalpackages) as sudo (or root), so that the python script can detect its existence automatically.
+#sudo make -f make.osx PREFIX=$ISSM_DIR/externalpackages/matplotlib/deps PYVERSION=$pythonversion fetch deps mpl_install_std
+#sudo make -f make.osx PREFIX=$ISSM_DIR/externalpackages/matplotlib/deps PYVERSION=$pythonversion mpl_install_std
+#python -c "import matplotlib; print 'Installed matplotlib', matplotlib.__version__, matplotlib.__file__"
+
+#to be tried:  first get freetype and zlib and libpng installed in sudo mode
+python setup.py build
+python setup.py install
Index: sm/trunk/externalpackages/matplotlib/install-osx.sh
===================================================================
--- /issm/trunk/externalpackages/matplotlib/install-osx.sh	(revision 13394)
+++ 	(revision )
@@ -1,10 +1,0 @@
-#/bin/bash
-pythonversion=2.7
-PYTHON=python${pythonversion}
-
-git clone https://github.com/matplotlib/matplotlib
-mv matplotlib src
-mkdir deps
-cd src
-make -f make.osx PREFIX=$ISSM_DIR/externalpackages/matplotlib/deps PYVERSION=$pythonversion fetch deps mpl_install_std
-${PYTHON} -c "import matplotlib; print 'Installed matplotlib', matplotlib.__version__, matplotlib.__file__"
Index: sm/trunk/externalpackages/matplotlib/install.sh
===================================================================
--- /issm/trunk/externalpackages/matplotlib/install.sh	(revision 13394)
+++ 	(revision )
@@ -1,7 +1,0 @@
-#/bin/bash
-
-git clone https://github.com/matplotlib/matplotlib
-mv matplotlib src
-cd src
-python setup.py build
-python setup.py install
Index: /issm/trunk/externalpackages/mercurial/install.sh
===================================================================
--- /issm/trunk/externalpackages/mercurial/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/mercurial/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/metis/install-4.0-altix64.sh
===================================================================
--- /issm/trunk/externalpackages/metis/install-4.0-altix64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/metis/install-4.0-altix64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/metis/install-4.0-cosmos.sh
===================================================================
--- /issm/trunk/externalpackages/metis/install-4.0-cosmos.sh	(revision 13394)
+++ /issm/trunk/externalpackages/metis/install-4.0-cosmos.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/metis/install-4.0-discover.sh
===================================================================
--- /issm/trunk/externalpackages/metis/install-4.0-discover.sh	(revision 13394)
+++ /issm/trunk/externalpackages/metis/install-4.0-discover.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/metis/install-4.0-greenplanet.sh
===================================================================
--- /issm/trunk/externalpackages/metis/install-4.0-greenplanet.sh	(revision 13394)
+++ /issm/trunk/externalpackages/metis/install-4.0-greenplanet.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/metis/install-4.0-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/metis/install-4.0-linux64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/metis/install-4.0-linux64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/metis/install-4.0-macosx32.sh
===================================================================
--- /issm/trunk/externalpackages/metis/install-4.0-macosx32.sh	(revision 13394)
+++ /issm/trunk/externalpackages/metis/install-4.0-macosx32.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/metis/install-4.0-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/metis/install-4.0-macosx64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/metis/install-4.0-macosx64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/metis/install-4.0-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/metis/install-4.0-pleiades.sh	(revision 13394)
+++ /issm/trunk/externalpackages/metis/install-4.0-pleiades.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/metis/install-4.0-win32.sh
===================================================================
--- /issm/trunk/externalpackages/metis/install-4.0-win32.sh	(revision 13394)
+++ /issm/trunk/externalpackages/metis/install-4.0-win32.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/metis/install-4.0-win7.sh
===================================================================
--- /issm/trunk/externalpackages/metis/install-4.0-win7.sh	(revision 13394)
+++ /issm/trunk/externalpackages/metis/install-4.0-win7.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/metis/install-5.0.1-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/metis/install-5.0.1-linux64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/metis/install-5.0.1-linux64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 #metis 5.0 should be used: srand48 and drand48 are being redefined in conflict to the stdlib equivalent functions.
 
Index: /issm/trunk/externalpackages/mitgcm/install.sh
===================================================================
--- /issm/trunk/externalpackages/mitgcm/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/mitgcm/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Do these commands once:
Index: /issm/trunk/externalpackages/modelE/install.sh
===================================================================
--- /issm/trunk/externalpackages/modelE/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/modelE/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 #modelE  downloaded from the gis repository of the GISS (Goddard Institute for Space Studies)
 #at  http://www.giss.nasa.gov/tools/modelE/
Index: /issm/trunk/externalpackages/modules/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/modules/install-macosx64.sh	(revision 13395)
+++ /issm/trunk/externalpackages/modules/install-macosx64.sh	(revision 13395)
@@ -0,0 +1,39 @@
+#!/bin/bash
+set -eu
+
+#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 [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/modules/install.sh
===================================================================
--- /issm/trunk/externalpackages/modules/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/modules/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/mpich2/install-1.0.2-altix64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.0.2-altix64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/mpich2/install-1.0.2-altix64.sh	(revision 13395)
@@ -31,5 +31,5 @@
 
 #Compile mpich2
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/mpich2/install-1.0.2-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.0.2-linux64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/mpich2/install-1.0.2-linux64.sh	(revision 13395)
@@ -31,5 +31,5 @@
 
 #Compile mpich2
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/mpich2/install-1.0.2-macosx32.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.0.2-macosx32.sh	(revision 13394)
+++ /issm/trunk/externalpackages/mpich2/install-1.0.2-macosx32.sh	(revision 13395)
@@ -30,5 +30,5 @@
 
 #Compile mpich2
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/mpich2/install-1.0.2-win32.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.0.2-win32.sh	(revision 13394)
+++ /issm/trunk/externalpackages/mpich2/install-1.0.2-win32.sh	(revision 13395)
@@ -28,5 +28,5 @@
 
 #Compile mpich2
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/mpich2/install-1.3.1-linux64-berg.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.3.1-linux64-berg.sh	(revision 13395)
+++ /issm/trunk/externalpackages/mpich2/install-1.3.1-linux64-berg.sh	(revision 13395)
@@ -0,0 +1,48 @@
+#!/bin/bash
+
+#version of mpich2
+#version=1.0.2p1
+version=1.3.1
+#version=1.4
+
+#Some cleanup
+rm -rf src install mpich2-$version
+
+#Create src and install directories
+mkdir src install
+
+#Untar 
+tar -zxvf  mpich2-$version.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-$version/* src
+rm -rf mpich2-$version
+
+#Configure mpich2
+cd src
+if [[ "$version" == "1.0.2p1" ]];
+then
+	make distclean
+fi
+
+source ../configure.sh
+
+if [[ "$version" == "1.0.2p1" ]];
+then
+	#Apply Patch to examples
+	patch ./examples/Makefile ../Examples.Makefile.patch
+	patch -R ./src/binding/cxx/mpicxx.h ../mpicxx.h.patch
+	patch -R ./src/include/mpicxx.h ../mpicxx.h.patch
+fi
+
+#Compile mpich2
+if [ $# -eq 0 ];
+then
+	make
+else
+	make -j $1
+fi
+make install 
+
+cd ../install/lib
+rm -rf *.so
Index: /issm/trunk/externalpackages/mpich2/install-1.4-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.4-linux64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/mpich2/install-1.4-linux64.sh	(revision 13395)
@@ -17,4 +17,5 @@
 #Configure mpich2
 cd src
+export -n F90 
 export CFLAGS="$CFLAGS -fPIC"
 export FFLAGS="$FFLAGS -fPIC"
@@ -26,5 +27,5 @@
 
 #Compile mpich2
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
@@ -32,6 +33,2 @@
 fi
 make install 
-
-#remove so files
-cd ../install/lib
-rm -rf *.so
Index: /issm/trunk/externalpackages/mpich2/install-1.4-macosx32.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.4-macosx32.sh	(revision 13394)
+++ /issm/trunk/externalpackages/mpich2/install-1.4-macosx32.sh	(revision 13395)
@@ -29,5 +29,5 @@
 
 #Compile mpich2
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
@@ -35,6 +35,2 @@
 fi
 make install 
-
-#remove so files
-cd ../install/lib
-rm -rf *.so
Index: /issm/trunk/externalpackages/mpich2/install-1.4-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.4-macosx64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/mpich2/install-1.4-macosx64.sh	(revision 13395)
@@ -29,5 +29,5 @@
 
 #Compile mpich2
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
@@ -35,6 +35,2 @@
 fi
 make install 
-
-#remove so files
-cd ../install/lib
-rm -rf *.so
Index: /issm/trunk/externalpackages/ncview/install.sh
===================================================================
--- /issm/trunk/externalpackages/ncview/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/ncview/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/netcdf-python/install.sh
===================================================================
--- /issm/trunk/externalpackages/netcdf-python/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/netcdf-python/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/netcdf/install-4.0.sh
===================================================================
--- /issm/trunk/externalpackages/netcdf/install-4.0.sh	(revision 13395)
+++ /issm/trunk/externalpackages/netcdf/install-4.0.sh	(revision 13395)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+#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 [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/netcdf/install-4.2.sh
===================================================================
--- /issm/trunk/externalpackages/netcdf/install-4.2.sh	(revision 13395)
+++ /issm/trunk/externalpackages/netcdf/install-4.2.sh	(revision 13395)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+#you need hdf5 compiled
+
+#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"  \
+ --disable-doxygen
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: sm/trunk/externalpackages/netcdf/install.sh
===================================================================
--- /issm/trunk/externalpackages/netcdf/install.sh	(revision 13394)
+++ 	(revision )
@@ -1,35 +1,0 @@
-#!/bin/bash
-
-version=4.0.1
-#version=4.2
-
-#for versions 4.2, you need hdf5 compiled, as well as doxygen for the 
-#documentation!
-
-#Some cleanup
-rm -rf src install netcdf-$version
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py "http://issm.jpl.nasa.gov/files/externalpackages/netcdf-$version.tar.gz" "netcdf-$version.tar.gz"
-
-#Untar 
-tar -zxvf  netcdf-$version.tar.gz
-
-#Move netcdf to install directory
-rm -rf src/*
-mv netcdf-$version/* src/
-rm -rf netcdf-$version
-
-#Configure and compile
-cd src
-
-#version dependent: 
-./configure  --prefix="$ISSM_DIR/externalpackages/netcdf/install"  
-
-if [ -z $1 ]; then
-	make
-else
-	make -j $1
-fi
-make install
Index: /issm/trunk/externalpackages/nose/install-linux64-python2.sh
===================================================================
--- /issm/trunk/externalpackages/nose/install-linux64-python2.sh	(revision 13395)
+++ /issm/trunk/externalpackages/nose/install-linux64-python2.sh	(revision 13395)
@@ -0,0 +1,14 @@
+#!/bin/bash
+#Install Python nose module
+
+rm -rf src 
+
+#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
Index: /issm/trunk/externalpackages/nose/install-linux64-python3.sh
===================================================================
--- /issm/trunk/externalpackages/nose/install-linux64-python3.sh	(revision 13395)
+++ /issm/trunk/externalpackages/nose/install-linux64-python3.sh	(revision 13395)
@@ -0,0 +1,11 @@
+#!/bin/bash
+#Install Python nose module
+
+rm -rf src 
+
+svn checkout http://python-nose.googlecode.com/svn/branches/py3k
+mv py3k src
+
+cd src
+python ./setup.py build
+python ./setup.py install
Index: /issm/trunk/externalpackages/nose/install-macosx64-python2.sh
===================================================================
--- /issm/trunk/externalpackages/nose/install-macosx64-python2.sh	(revision 13395)
+++ /issm/trunk/externalpackages/nose/install-macosx64-python2.sh	(revision 13395)
@@ -0,0 +1,14 @@
+#!/bin/bash
+#Install Python nose module
+
+rm -rf src 
+
+#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
Index: /issm/trunk/externalpackages/nose/install-macosx64-python3.sh
===================================================================
--- /issm/trunk/externalpackages/nose/install-macosx64-python3.sh	(revision 13395)
+++ /issm/trunk/externalpackages/nose/install-macosx64-python3.sh	(revision 13395)
@@ -0,0 +1,11 @@
+#!/bin/bash
+#Install Python nose module
+
+rm -rf src 
+
+svn checkout http://python-nose.googlecode.com/svn/branches/py3k
+mv py3k src
+
+cd src
+python ./setup.py build
+python ./setup.py install
Index: sm/trunk/externalpackages/nose/install-macosx64sh
===================================================================
--- /issm/trunk/externalpackages/nose/install-macosx64sh	(revision 13394)
+++ 	(revision )
@@ -1,29 +1,0 @@
-#!/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/trunk/externalpackages/numpy/README
===================================================================
--- /issm/trunk/externalpackages/numpy/README	(revision 13395)
+++ /issm/trunk/externalpackages/numpy/README	(revision 13395)
@@ -0,0 +1,9 @@
+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/trunk/externalpackages/numpy/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/numpy/install-linux64.sh	(revision 13395)
+++ /issm/trunk/externalpackages/numpy/install-linux64.sh	(revision 13395)
@@ -0,0 +1,23 @@
+#!/bin/bash
+set -eu
+
+export CC="gcc -fPIC"
+export CXX="g++ -fPIC"
+export F77="gfortran -fPIC"
+export FC="gfortran -fPIC"
+export FFLAGS=-ff2c
+
+#clean up
+rm -rf numpy
+
+#download numpy first
+export GIT_SSL_NO_VERIFY=true 
+git clone https://github.com/numpy/numpy.git
+
+#install numpy
+cd numpy
+python setup.py build
+python setup.py install
+cd ..
+python -c "import numpy; print 'Installed NumPy', numpy.__version__"
+python -c "import numpy; numpy.test()"
Index: /issm/trunk/externalpackages/numpy/install-macosx-lion.sh
===================================================================
--- /issm/trunk/externalpackages/numpy/install-macosx-lion.sh	(revision 13395)
+++ /issm/trunk/externalpackages/numpy/install-macosx-lion.sh	(revision 13395)
@@ -0,0 +1,14 @@
+#!/bin/bash
+set -eu
+
+export CC=gcc
+export CXX=g++
+export FFLAGS=-ff2c
+
+#download numpy first
+git clone https://github.com/numpy/numpy.git
+
+#install numpy
+cd numpy
+python setup.py build
+python setup.py install
Index: /issm/trunk/externalpackages/numpy/install-macosx-snowleopard.sh
===================================================================
--- /issm/trunk/externalpackages/numpy/install-macosx-snowleopard.sh	(revision 13395)
+++ /issm/trunk/externalpackages/numpy/install-macosx-snowleopard.sh	(revision 13395)
@@ -0,0 +1,17 @@
+#!/bin/bash
+set -eu
+
+# On OSX 10.6, gfortran gets installed in /usr/local/gfortran 
+export CC="/usr/local/gfortran/bin/gcc"
+export CXX="/usr/local/gfortran/bin/g++"
+
+#download numpy first
+git clone https://github.com/numpy/numpy.git
+
+#install numpy
+cd numpy
+python setup.py build
+python setup.py install
+cd ..
+python -c "import numpy; print 'Installed NumPy', numpy.__version__"
+python -c "import numpy; numpy.test()"
Index: /issm/trunk/externalpackages/octave/install.sh
===================================================================
--- /issm/trunk/externalpackages/octave/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/octave/install.sh	(revision 13395)
@@ -1,30 +1,31 @@
 #!/bin/bash
+set -eu
 
 #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 [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
Index: /issm/trunk/externalpackages/oofem/install.sh
===================================================================
--- /issm/trunk/externalpackages/oofem/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/oofem/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -23,5 +24,5 @@
 #Compile oofem 
 cd targets/oofem-2.0
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/openanalysis/install.sh
===================================================================
--- /issm/trunk/externalpackages/openanalysis/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/openanalysis/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/packagemaker/install.sh
===================================================================
--- /issm/trunk/externalpackages/packagemaker/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/packagemaker/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Erase symlink
Index: /issm/trunk/externalpackages/pcre/install.sh
===================================================================
--- /issm/trunk/externalpackages/pcre/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/pcre/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Cleaning
Index: /issm/trunk/externalpackages/petsc/install-2.3.2-altix64-castor.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-altix64-castor.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-2.3.2-altix64-castor.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 #Step 1: unzip and install
 #Step 2: After Plapack implodes
Index: /issm/trunk/externalpackages/petsc/install-2.3.2-cosmos.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-cosmos.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-2.3.2-cosmos.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-2.3.2-linux64-astrid.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-linux64-astrid.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-2.3.2-linux64-astrid.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-2.3.2-macosx32-eric.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-macosx32-eric.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-2.3.2-macosx32-eric.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 #Step 1: unzip and install
 #Step 2: After MUMPS Crashes
Index: /issm/trunk/externalpackages/petsc/install-2.3.2-macosx32-ogive.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-macosx32-ogive.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-2.3.2-macosx32-ogive.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-2.3.2-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-macosx64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-2.3.2-macosx64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-2.3.2-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-pleiades.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-2.3.2-pleiades.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 #Step 1: unzip and install
 #Step 2: After Plapack implodes
Index: /issm/trunk/externalpackages/petsc/install-2.3.2-win32-eric.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-win32-eric.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-2.3.2-win32-eric.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-2.3.2-win7.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-2.3.2-win7.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-2.3.2-win7.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-3.1-altix64-castor.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-altix64-castor.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.1-altix64-castor.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 #Step 1: unzip and install
 #Step 2: After Plapack implodes
Index: /issm/trunk/externalpackages/petsc/install-3.1-cosmos.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-cosmos.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.1-cosmos.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-3.1-linux64-astrid.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-linux64-astrid.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.1-linux64-astrid.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-3.1-macosx32-mathieu.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-macosx32-mathieu.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.1-macosx32-mathieu.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-3.1-macosx32-ogive.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-macosx32-ogive.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.1-macosx32-ogive.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-3.1-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-pleiades.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.1-pleiades.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 #Step 1: unzip and install
 #Step 2: After Plapack implodes
Index: /issm/trunk/externalpackages/petsc/install-3.1-ubuntu64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-ubuntu64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.1-ubuntu64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-3.1-win7.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.1-win7.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.1-win7.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-3.2-discover.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.2-discover.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.2-discover.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -21,5 +22,5 @@
 	--with-batch=1 \
 	--with-debugging=0 \
-	--with-shared-libraries=0 \
+	--with-shared-libraries=1 \
 	--known-mpi-shared-libraries=1 \
 	--with-mpi-dir=/usr/local/intel/mpi/4.0.3.008/lib64/ \
@@ -32,5 +33,5 @@
 	--download-scalapack=no \
 	--download-blacs=no \
-	--download-plapack=yes \
+	--download-plapack=no \
 	--download-parmetis=yes \
 	--with-pic=1
Index: /issm/trunk/externalpackages/petsc/install-3.2-greenplanet.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.2-greenplanet.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.2-greenplanet.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/petsc/install-3.2-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.2-linux64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.2-linux64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -22,5 +23,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/trunk/externalpackages/petsc/install-3.2-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.2-macosx64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.2-macosx64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -18,13 +19,13 @@
   --prefix="$ISSM_DIR/externalpackages/petsc/install" \
   --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
-  --PETSC_ARCH=macosx-gnu \
+  --PETSC_ARCH="macosx-gnu" \
   --with-mpi-dir="$ISSM_DIR/externalpackages/mpich2/install" \
   --with-debugging=0 \
-  --with-shared-libraries=0 \
+  --with-shared-libraries=1 \
   --download-mumps=yes \
   --download-scalapack=yes \
   --download-blacs=yes \
   --download-blas=yes \
-  --download-plapack=yes  \
+  --download-plapack=no  \
   --download-parmetis=yes \
   --download-f-blas-lapack=yes 
Index: /issm/trunk/externalpackages/petsc/install-3.2-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.2-pleiades.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-3.2-pleiades.sh	(revision 13395)
@@ -1,6 +1,7 @@
 #!/bin/bash
+set -eu
 #Step 1: unzip and install
 #Step 2: After Plapack implodes
-STEP=1
+STEP=2
 
 if [ $STEP -eq 1 ]; then
@@ -25,5 +26,5 @@
 		--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
 		--with-debugging=0 \
-		--with-shared-libraries=0 \
+		--with-shared-libraries=1 \
 		--with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
 		--known-mpi-shared-libraries=1 \
@@ -52,5 +53,5 @@
 	 --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
 	 --with-debugging=0 \
-	 --with-shared-libraries=0 \
+	 --with-shared-libraries=1 \
 	 --with-blas-lapack-dir=/nasa/intel/mkl/10.0.011/ \
 	 --with-mpi-lib=/nasa/sgi/mpt/1.25/lib/libmpi.so \
Index: /issm/trunk/externalpackages/petsc/install-3.3-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.3-linux64.sh	(revision 13395)
+++ /issm/trunk/externalpackages/petsc/install-3.3-linux64.sh	(revision 13395)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#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/trunk/externalpackages/petsc/install-3.3-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.3-macosx64.sh	(revision 13395)
+++ /issm/trunk/externalpackages/petsc/install-3.3-macosx64.sh	(revision 13395)
@@ -0,0 +1,36 @@
+#!/bin/bash
+set -eu
+
+#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/trunk/externalpackages/petsc/install-dev-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-dev-linux64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-dev-linux64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 STEP=2
@@ -21,6 +22,6 @@
 # configure script
 # Note: using metis from externalpackages did not work...
-# for now downloading new metis
-#   -then rename metis in externalpackages to metis2
+#       -for now download new metis
+#       -rename metis in externalpackages to metis2
 
 
@@ -35,14 +36,22 @@
 	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
 	--with-debugging=0 \
-	--with-shared-libraries=0 \
-	--download-metis=yes \
+	--with-shared-libraries=1 \
 	--download-mumps=yes \
+	--download-plapack=yes \
 	--download-scalapack=yes \
-	--download-blacs=yes \
+	--download-blacs=yes  \
 	--download-blas=yes \
 	--download-f-blas-lapack=yes \
-	--download-plapack=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=yes \
+	--download-hypre=yes \
+	--download-prometheus=yes \
 	--with-pic=1
 
Index: /issm/trunk/externalpackages/petsc/install-dev-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-dev-pleiades.sh	(revision 13394)
+++ /issm/trunk/externalpackages/petsc/install-dev-pleiades.sh	(revision 13395)
@@ -1,6 +1,6 @@
 #!/bin/bash
+set -eu
 #Step 0: download
-#Step 1: install before plapack crasehs
-#Step 2: After Plapack implodes
+#Step 1: install and write script
 STEP=0
 
@@ -19,5 +19,4 @@
 #      cd config/BuildSystem
 #      hg pull -u
-
 
 # configure script
@@ -56,6 +55,9 @@
 		--download-spooles=yes \
 		--download-spai=yes \
-		--download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
+		--download-superlu=yes \
+		--download-hypre=yes \
+		--download-prometheus=yes \
 		--FFLAGS=-I/usr/include \
+		--with-cxx=icpc \
 		--with-cc=icc \
 		--with-fc=ifort \
@@ -64,46 +66,5 @@
 		--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
+		cat > script.queue << EOF
 #PBS -S /bin/bash
 #PBS -q debug 
Index: /issm/trunk/externalpackages/polygonclipper/install.sh
===================================================================
--- /issm/trunk/externalpackages/polygonclipper/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/polygonclipper/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/pyclips/install.sh
===================================================================
--- /issm/trunk/externalpackages/pyclips/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/pyclips/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/pysvn/install.sh
===================================================================
--- /issm/trunk/externalpackages/pysvn/install.sh	(revision 13395)
+++ /issm/trunk/externalpackages/pysvn/install.sh	(revision 13395)
@@ -0,0 +1,26 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf pysvn-1.7.6
+mkdir src 
+
+export CC=/usr/local/gfortran/bin/gcc
+export CXX=/usr/local/gfortran/bin/g++
+export FFLAGS=-ff2c
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/pysvn-1.7.6.tar.gz' 'pysvn-1.7.6.tar.gz'
+
+#Untar 
+tar -zxvf  pysvn-1.7.6.tar.gz
+
+#Move pysvn into src directory
+mv pysvn-1.7.6/* src
+rm -rf pysvn-1.7.6
+
+$install
+cd src
+python setup.py build
+python setup.py install
Index: /issm/trunk/externalpackages/python/install-2.7.3-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-2.7.3-linux64.sh	(revision 13395)
+++ /issm/trunk/externalpackages/python/install-2.7.3-linux64.sh	(revision 13395)
@@ -0,0 +1,33 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-2.7.3
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-2.7.3.tgz Python-2.7.3.tgz
+
+#Untar and move python into install directory
+tar -zxvf  Python-2.7.3.tgz
+mv Python-2.7.3/* src
+rm -rf Python-2.7.3
+
+#Configure python
+cd src 
+./configure \
+ --prefix="$ISSM_DIR/externalpackages/python/install" \
+ --enable-shared
+
+if [ $# -eq 0 ]; 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/trunk/externalpackages/python/install-2.7.3-macosx-lion.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-2.7.3-macosx-lion.sh	(revision 13395)
+++ /issm/trunk/externalpackages/python/install-2.7.3-macosx-lion.sh	(revision 13395)
@@ -0,0 +1,40 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-2.7.3
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-2.7.3.tgz Python-2.7.3.tgz
+
+#Untar and move python into install directory
+tar -zxvf  Python-2.7.3.tgz
+mv Python-2.7.3/* src
+rm -rf Python-2.7.3
+
+#Configure and compile
+cd src 
+./configure \
+ --enable-framework="$ISSM_DIR/externalpackages/python/install/Library/Frameworks" 
+if [ $# -eq 0 ]; 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/trunk/externalpackages/python/install-2.7.3-macosx-snowleopard.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-2.7.3-macosx-snowleopard.sh	(revision 13395)
+++ /issm/trunk/externalpackages/python/install-2.7.3-macosx-snowleopard.sh	(revision 13395)
@@ -0,0 +1,40 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+rm -rf Python-2.7.3
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py http://issm.jpl.nasa.gov/files/externalpackages/Python-2.7.3.tgz Python-2.7.3.tgz
+
+#exports
+export MACOSX_DEPLOYMENT_TARGET=10.6
+
+#Untar and move python into install directory
+tar -zxvf  Python-2.7.3.tgz
+mv Python-2.7.3/* src
+rm -rf Python-2.7.3
+
+#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 [ $# -eq 0 ]; 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 $ISSM_DIR/externalpackages/python/patches/pyport.h.patch
Index: /issm/trunk/externalpackages/python/install-3.2.2-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-3.2.2-linux64.sh	(revision 13395)
+++ /issm/trunk/externalpackages/python/install-3.2.2-linux64.sh	(revision 13395)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#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 [ $# -eq 0 ]; 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/trunk/externalpackages/python/install-3.2.2-macosx-lion.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-3.2.2-macosx-lion.sh	(revision 13395)
+++ /issm/trunk/externalpackages/python/install-3.2.2-macosx-lion.sh	(revision 13395)
@@ -0,0 +1,40 @@
+#!/bin/bash
+set -eu
+
+#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 [ $# -eq 0 ]; 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/trunk/externalpackages/python/install-3.2.2-macosx-snowleopard.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-3.2.2-macosx-snowleopard.sh	(revision 13395)
+++ /issm/trunk/externalpackages/python/install-3.2.2-macosx-snowleopard.sh	(revision 13395)
@@ -0,0 +1,41 @@
+#!/bin/bash
+set -eu
+
+#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 [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+cd ..
+
+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/trunk/externalpackages/python/install-linux64-astrid.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-linux64-astrid.sh	(revision 13394)
+++ 	(revision )
@@ -1,48 +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 python
-cd src 
-./configure --prefix="$ISSM_DIR/externalpackages/python/install" --enable-shared
-
-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
-if [[ $version == "2.7.2" ]]; then 
-	cd ../install/include
-	cp python2.7/* ./
-	cd ../lib
-	ln -s  libpython2.7.so.1.0 libpython.so
-	
-fi
Index: sm/trunk/externalpackages/python/install-macosx-lion.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-macosx-lion.sh	(revision 13394)
+++ 	(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/trunk/externalpackages/python/install-macosx-snowleopard.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-macosx-snowleopard.sh	(revision 13394)
+++ 	(revision )
@@ -1,50 +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 
-# --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" 
-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
-
-#Some modifications to be done in case version is 2.7
-if [[ $version == "2.7.2" ]]; then 
-	cd ../install
-	ln -s Library/Frameworks/Python.framework/Headers include
-	ln -s Library/Frameworks/Python.framework/Versions/2.7/lib lib
-fi
Index: /issm/trunk/externalpackages/python/patches/pyport.h.patch
===================================================================
--- /issm/trunk/externalpackages/python/patches/pyport.h.patch	(revision 13395)
+++ /issm/trunk/externalpackages/python/patches/pyport.h.patch	(revision 13395)
@@ -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/trunk/externalpackages/python/patches/pyport.h.patch.bugreport
===================================================================
--- /issm/trunk/externalpackages/python/patches/pyport.h.patch.bugreport	(revision 13395)
+++ /issm/trunk/externalpackages/python/patches/pyport.h.patch.bugreport	(revision 13395)
@@ -0,0 +1,1 @@
+http://bugs.python.org/issue10910
Index: /issm/trunk/externalpackages/qhull/install.sh
===================================================================
--- /issm/trunk/externalpackages/qhull/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/qhull/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/rats/install.sh
===================================================================
--- /issm/trunk/externalpackages/rats/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/rats/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Erase install
Index: /issm/trunk/externalpackages/readline/install.sh
===================================================================
--- /issm/trunk/externalpackages/readline/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/readline/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/rose/install.sh
===================================================================
--- /issm/trunk/externalpackages/rose/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/rose/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -22,5 +23,5 @@
 	--srcdir=$ISSM_DIR/externalpackages/rose/source
 
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/satstress/install.sh
===================================================================
--- /issm/trunk/externalpackages/satstress/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/satstress/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/scipy/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/scipy/install-linux64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/scipy/install-linux64.sh	(revision 13395)
@@ -1,9 +1,4 @@
 #!/bin/bash
-
-#1: install numpy
-#2 install scipy
-#3 erase
-install=2
-
+set -eu
 
 export CC="gcc -fPIC"
@@ -13,37 +8,21 @@
 export FFLAGS=-ff2c
 
+#clean up
+rm -rf scipy
 
-if [[ $install == "1" ]];then 
+#download scipy
+export GIT_SSL_NO_VERIFY=true 
+git clone https://github.com/scipy/scipy.git
 
-	#download numpy first
+#install scipy
+cd scipy
+export  BLAS_SRC=$ISSM_DIR/externalpackages/blas/install/lib
+export  BLAS=$ISSM_DIR/externalpackages/blas/install/lib
+export  LAPACK_SRC=$ISSM_DIR/externalpackages/lapack/install/lib
+export  LAPACK=$ISSM_DIR/externalpackages/lapack/install/lib
 
-	export GIT_SSL_NO_VERIFY=true 
-	git clone https://github.com/numpy/numpy.git
-
-	#install numpy
-	cd numpy
-	python setup.py build
-	python setup.py install
-
-	
-elif [[ $install == "2" ]];then 
-	
-	#download scipy
-	export GIT_SSL_NO_VERIFY=true 
-	git clone https://github.com/scipy/scipy.git
-
-	#install scipy
-	cd scipy
-	export  BLAS_SRC=$ISSM_DIR/externalpackages/blas/install/lib
-	export  BLAS=$ISSM_DIR/externalpackages/blas/install/lib
-	export  LAPACK_SRC=$ISSM_DIR/externalpackages/lapack/install/lib
-	export  LAPACK=$ISSM_DIR/externalpackages/lapack/install/lib
-
-	python setup.py build
-	python setup.py install
-
-elif [[ $install == "3" ]];then 
-	rm -rf numpy scipy
-else 
-	echo "Choice not covered"
-fi
+python setup.py build
+python setup.py install
+cd ..
+python -c "import scipy; print 'Installed SciPy', scipy.__version__"
+#python -c "import scipy; scipy.test()"
Index: /issm/trunk/externalpackages/scipy/install-macosx-lion.sh
===================================================================
--- /issm/trunk/externalpackages/scipy/install-macosx-lion.sh	(revision 13394)
+++ /issm/trunk/externalpackages/scipy/install-macosx-lion.sh	(revision 13395)
@@ -1,39 +1,20 @@
 #!/bin/bash
-
-#1: install numpy
-#2 install scipy
-#3 erase
-install=2
-
+set -eu
 
 export CC=gcc
 export CXX=g++
 export FFLAGS=-ff2c
+	
+#download scipy
+git clone https://github.com/scipy/scipy.git
 
+#install scipy
+cd scipy
+export  BLAS_SRC=$ISSM_DIR/externalpackages/blas/install/lib
+export  BLAS=$ISSM_DIR/externalpackages/blas/install/lib
+export  LAPACK_SRC=$ISSM_DIR/externalpackages/lapack/install/lib
+export  LAPACK=$ISSM_DIR/externalpackages/lapack/install/lib
 
-if [[ $install == "1" ]];then 
-
-	#download numpy first
-	git clone https://github.com/numpy/numpy.git
-
-	#install numpy
-	cd numpy
-	python setup.py build
-	python setup.py install
-
-	
-elif [[ $install == "2" ]];then 
-	
-	#download scipy
-	git clone https://github.com/scipy/scipy.git
-
-	#install scipy
-	cd scipy
-	python setup.py build
-	python setup.py install
-
-elif [[ $install == "3" ]];then 
-	rm -rf numpy scipy
-else 
-	echo "Choice not covered"
-fi
+#install scipy
+python setup.py build
+python setup.py install
Index: /issm/trunk/externalpackages/scipy/install-macosx-snowleopard.sh
===================================================================
--- /issm/trunk/externalpackages/scipy/install-macosx-snowleopard.sh	(revision 13394)
+++ /issm/trunk/externalpackages/scipy/install-macosx-snowleopard.sh	(revision 13395)
@@ -1,45 +1,17 @@
 #!/bin/bash
-PYVERSION=2.7
-PYTHON=python${PYVERSION}
+set -eu
 
-#1: install numpy
-#2 install scipy
-#3 erase
-install=2
+# On OSX 10.6, fgortran gets installed in /usr/local/gfortran 
+export CC="/usr/local/gfortran/bin/gcc"
+export CXX="/usr/local/gfortran/bin/g++"
 
-# 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++
+#download scipy
+git clone https://github.com/scipy/scipy.git
 
-if [[ $install == "1" ]];then 
-
-	#download numpy first
-	git clone https://github.com/numpy/numpy.git
-
-	#install numpy
-	cd numpy
-	python setup.py build
-	python setup.py install
-	cd ..
-	${PYTHON} -c "import numpy; print 'Installed NumPy', numpy.__version__"
-	${PYTHON} -c "import numpy; numpy.test()"
-	
-elif [[ $install == "2" ]];then 
-	
-	#download scipy
-	git clone https://github.com/scipy/scipy.git
-
-	#install scipy
-	cd scipy
-	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 
-	rm -rf numpy scipy
-else 
-	echo "Choice not covered"
-fi
+#install scipy
+cd scipy
+python setup.py build
+python setup.py install
+cd ..
+python -c "import scipy; print 'Installed SciPy', scipy.__version__"
+python -c "import scipy; scipy.test()"
Index: /issm/trunk/externalpackages/scotch/install.sh
===================================================================
--- /issm/trunk/externalpackages/scotch/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/scotch/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 # Some cleanup
Index: /issm/trunk/externalpackages/shapelib/install.sh
===================================================================
--- /issm/trunk/externalpackages/shapelib/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/shapelib/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 # Some cleanup
@@ -25,5 +26,5 @@
 # Build shapelib and run self-tests
 cd src
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/slepc/install.sh
===================================================================
--- /issm/trunk/externalpackages/slepc/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/slepc/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -18,5 +19,5 @@
 cd install
 ./config/configure.py
-if [ -z $1 ]; then
+if [ $# -eq 0 ]; then
 	make
 else
Index: /issm/trunk/externalpackages/sqlite/install.sh
===================================================================
--- /issm/trunk/externalpackages/sqlite/install.sh	(revision 13395)
+++ /issm/trunk/externalpackages/sqlite/install.sh	(revision 13395)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf sqlite-autoconf-3071300
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/sqlite-autoconf-3071300.tar.gz' 'sqlite-autoconf-3071300.tar.gz'
+
+#Untar 
+tar -zxvf  sqlite-autoconf-3071300.tar.gz
+
+#Move sqlite-autoconf into src directory
+mv sqlite-autoconf-3071300/* src
+rm -rf sqlite-autoconf-3071300
+
+#Configure sqlite-autoconf
+cd src
+./configure  --prefix="$ISSM_DIR/externalpackages/sqlite/install" 
+
+#Compile and install sqlite-autoconf
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/svn/install.sh
===================================================================
--- /issm/trunk/externalpackages/svn/install.sh	(revision 13395)
+++ /issm/trunk/externalpackages/svn/install.sh	(revision 13395)
@@ -0,0 +1,33 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf subversion-1.6.18
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/subversion-1.6.18.tar.gz' 'subversion-1.6.18.tar.gz'
+
+#Untar 
+tar -zxvf  subversion-1.6.18.tar.gz
+
+#Move subversion into src directory
+mv subversion-1.6.18/* src
+rm -rf subversion-1.6.18
+
+#Configure subversion
+cd src
+./configure --prefix="$ISSM_DIR/externalpackages/svn/install" \
+	--with-swig="$ISSM_DIR/externalpackages/swig/install"  \
+	PYTHON2="$ISSM_DIR/externalpackages/python/install/bin/python" \
+	--with-sqlite="$ISSM_DIR/externalpackages/sqlite/install"
+
+#Compile and install subversion
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/swig/install.sh
===================================================================
--- /issm/trunk/externalpackages/swig/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/swig/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
@@ -18,12 +19,19 @@
 #cp $ISSM_DIR/externalpackages/pcre/install/pcre.h  ./Source/Include/
 #cp $ISSM_DIR/externalpackages/pcre/install/.libs/*  ./Source/Include/
-export CFLAGS="$CFLAGS -I$ISSM_DIR/externalpackages/pcre/install"
+export CFLAGS="-I$ISSM_DIR/externalpackages/pcre/install"
 export LDFLAGS="-L$ISSM_DIR/externalpackages/pcre/install/.libs/"
 export LIBS="-lpcre"
-#Configure doxygen
+#Configure swig
 ./configure \
- --prefix="$ISSM_DIR/externalpackages/python/install" \
+ --prefix="$ISSM_DIR/externalpackages/swig/install" \
  --with-pcre-prefix="$ISSM_DIR/externalpackages/pcre/install" \
- --with-pcre-exec-prefix="$ISSM_DIR/externalpackages/pcre/install"
-make 
+ --with-pcre-exec-prefix="$ISSM_DIR/externalpackages/pcre/install" \
+ --with-python="$ISSM_DIR/externalpackages/python/install/bin/python"
+
+#Compile and install gdal
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
 make install
Index: /issm/trunk/externalpackages/tao/install-2.0.sh
===================================================================
--- /issm/trunk/externalpackages/tao/install-2.0.sh	(revision 13395)
+++ /issm/trunk/externalpackages/tao/install-2.0.sh	(revision 13395)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+#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/trunk/externalpackages/tao/install-2.1.sh
===================================================================
--- /issm/trunk/externalpackages/tao/install-2.1.sh	(revision 13395)
+++ /issm/trunk/externalpackages/tao/install-2.1.sh	(revision 13395)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+#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/trunk/externalpackages/tao/install.sh
===================================================================
--- /issm/trunk/externalpackages/tao/install.sh	(revision 13394)
+++ 	(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/trunk/externalpackages/tcl/install.sh
===================================================================
--- /issm/trunk/externalpackages/tcl/install.sh	(revision 13395)
+++ /issm/trunk/externalpackages/tcl/install.sh	(revision 13395)
@@ -0,0 +1,49 @@
+#!/bin/bash
+set -eu
+
+sudochoice=0;
+
+#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/unix
+
+#User mode: 
+if [[ $sudochoice == "0" ]]; 
+then 
+	./configure --prefix=$ISSM_DIR/externalpackages/tcl/install
+	if [ $# -eq 0 ]; then
+		make
+	else
+		make -j $1
+	fi
+	make install 
+fi
+
+#sudo mode: 
+if [[ $sudochoice == "1" ]]; 
+then
+	sudo ./configure 
+	if [ $# -eq 0 ]; then
+		sudo make
+	else
+		sudo make -j $1
+	fi
+	sudo make install 
+fi
Index: /issm/trunk/externalpackages/tclx/install.sh
===================================================================
--- /issm/trunk/externalpackages/tclx/install.sh	(revision 13395)
+++ /issm/trunk/externalpackages/tclx/install.sh	(revision 13395)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#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 [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/tex2im/install.sh
===================================================================
--- /issm/trunk/externalpackages/tex2im/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/tex2im/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/tk/install.sh
===================================================================
--- /issm/trunk/externalpackages/tk/install.sh	(revision 13395)
+++ /issm/trunk/externalpackages/tk/install.sh	(revision 13395)
@@ -0,0 +1,46 @@
+#!/bin/bash
+set -eu
+
+sudochoice=0;
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf tk8.5.12
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/tk8.5.12-src.tar.gz' 'tk8.5.12.tar.gz'
+
+#Untar 
+tar -zxvf  tk8.5.12.tar.gz
+
+#Move tk into src directory
+mv tk8.5.12/* src
+rm -rf tk8.5.12
+
+cd src/unix
+
+#User mode: 
+if [[ $sudochoice == "0" ]]; 
+then 
+	./configure --prefix=$ISSM_DIR/externalpackages/tk/install
+	if [ $# -eq 0 ]; then
+		make
+	else
+		make -j $1
+	fi
+	make install 
+fi
+
+#sudo mode: 
+if [[ $sudochoice == "1" ]]; 
+then
+	sudo ./configure 
+	if [ $# -eq 0 ]; then
+		sudo make
+	else
+		sudo make -j $1
+	fi
+	sudo make install 
+fi
Index: /issm/trunk/externalpackages/triangle/configs/android/configure.make
===================================================================
--- /issm/trunk/externalpackages/triangle/configs/android/configure.make	(revision 13394)
+++ /issm/trunk/externalpackages/triangle/configs/android/configure.make	(revision 13395)
@@ -1,6 +1,6 @@
 # This makefile configures build process to cross-compile to the android platform.
-# The binary tools referenced below are specifically configuered to target armeabi-v7a.
+# 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 complient.
+# produce binaries that are EABI compliant.
 #
 # Note that the AAPCS standard defines 'EABI' as a moniker used to specify
@@ -9,4 +9,7 @@
 #
 # 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
Index: /issm/trunk/externalpackages/triangle/install-altix64.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-altix64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/triangle/install-altix64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup 
Index: /issm/trunk/externalpackages/triangle/install-android.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-android.sh	(revision 13394)
+++ /issm/trunk/externalpackages/triangle/install-android.sh	(revision 13395)
@@ -1,8 +1,4 @@
 #!/bin/bash
-source $ANDROID_DIR/android_variables.sh
-export toolchain_path
-
-#use matlab? 
-matlab=0
+set -eu
 
 #Some cleanup 
@@ -19,13 +15,9 @@
 
 #copy new makefile
-cp ../configs//android/configure.make ./
+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
+patch triangle.c ../triangle.c.patch
 
 #Compile triangle
Index: /issm/trunk/externalpackages/triangle/install-discover.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-discover.sh	(revision 13394)
+++ /issm/trunk/externalpackages/triangle/install-discover.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup 
Index: /issm/trunk/externalpackages/triangle/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-linux64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/triangle/install-linux64.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup 
Index: /issm/trunk/externalpackages/triangle/install-macosx32.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-macosx32.sh	(revision 13394)
+++ /issm/trunk/externalpackages/triangle/install-macosx32.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup 
Index: /issm/trunk/externalpackages/triangle/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-macosx64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/triangle/install-macosx64.sh	(revision 13395)
@@ -1,7 +1,4 @@
 #!/bin/bash
-
-#use matlab? 
-matlab=0
-
+set -eu
 
 #Some cleanup 
@@ -22,9 +19,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/trunk/externalpackages/triangle/install-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-pleiades.sh	(revision 13394)
+++ /issm/trunk/externalpackages/triangle/install-pleiades.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup 
Index: /issm/trunk/externalpackages/triangle/install-win32.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-win32.sh	(revision 13394)
+++ /issm/trunk/externalpackages/triangle/install-win32.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup 
Index: /issm/trunk/externalpackages/triangle/install-win7.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-win7.sh	(revision 13394)
+++ /issm/trunk/externalpackages/triangle/install-win7.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup 
Index: /issm/trunk/externalpackages/triangle/triangle.c.patch
===================================================================
--- /issm/trunk/externalpackages/triangle/triangle.c.patch	(revision 13394)
+++ /issm/trunk/externalpackages/triangle/triangle.c.patch	(revision 13395)
@@ -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/trunk/externalpackages/triangle/triangle.c.patch.matlab
===================================================================
--- /issm/trunk/externalpackages/triangle/triangle.c.patch.matlab	(revision 13394)
+++ 	(revision )
@@ -1,164 +1,0 @@
-0a1,10
-> /*Notes for the Ice code: 
->  * to be able to compile Triangle within a mex function that can run within 
->  * matlab, we had to change the allocation routine trimalloc, as well as the 
->  * double precision activation in exactinit(); The rest is not changed. 
->  * We also created the ice_makefile to compile Triangle into a library. */
-> #include <mat.h>
-> #include <matrix.h>
-> #define ANSI_DECLARATORS
-> #define NO_TIMER
-> 
-347a358
-> #ifndef _WIN_
-348a360
-> #endif
-641d652
-< 
-817a829,922
-> /*Some missing prototypes: */
-> int scale_expansion_zeroelim(int elen, REAL *e, REAL b, REAL *h);
-> int fast_expansion_sum_zeroelim(int elen, REAL *e, int flen, REAL *f, REAL *h);
-> void poolzero(struct memorypool *pool);
-> int triunsuitable(vertex triorg, vertex tridest, vertex triapex, REAL area);
-> triangle *triangletraverse(struct mesh *m);
-> void pooldeinit(struct memorypool *pool);
-> void printtriangle(struct mesh *m, struct behavior *b, struct otri *t);
-> VOID *poolalloc(struct memorypool *pool);
-> void enqueuebadtriang(struct mesh *m, struct behavior *b,
->                       struct badtriang *badtri);
-> void triangulatepolygon(struct mesh *m, struct behavior *b,
->                         struct otri *firstedge, struct otri *lastedge,
->                         int edgecount, int doflip, int triflaws);
-> void triangledealloc(struct mesh *m, triangle *dyingtriangle);
-> void unflip(struct mesh *m, struct behavior *b, struct otri *flipedge);
-> void vertexmedian(vertex *sortarray, int arraysize, int median, int axis);
-> REAL counterclockwiseadapt(vertex pa, vertex pb, vertex pc, REAL detsum);
-> REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent);
-> void enqueuebadtri(struct mesh *m, struct behavior *b, struct otri *enqtri,
->                    REAL minedge, vertex enqapex, vertex enqorg, vertex enqdest);
-> void alternateaxes(vertex *sortarray, int arraysize, int axis);
-> REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent);
-> void maketriangle(struct mesh *m, struct behavior *b, struct otri *newotri);
-> REAL counterclockwise(struct mesh *m, struct behavior *b,
->                       vertex pa, vertex pb, vertex pc);
-> vertex vertextraverse(struct mesh *m);
-> void mergehulls(struct mesh *m, struct behavior *b, struct otri *farleft,
->                 struct otri *innerleft, struct otri *innerright,
->                 struct otri *farright, int axis);
-> REAL incircle(struct mesh *m, struct behavior *b,
->               vertex pa, vertex pb, vertex pc, vertex pd);
-> void poolrestart(struct memorypool *pool);
-> void trifree(VOID *memptr);
-> struct splaynode *splay(struct mesh *m, struct splaynode *splaytree,
->                         vertex searchpoint, struct otri *searchtri);
-> void eventheapdelete(struct event **heap, int heapsize, int eventnum);
-> void eventheapdelete(struct event **heap, int heapsize, int eventnum);
-> void flip(struct mesh *m, struct behavior *b, struct otri *flipedge);
-> void check4deadevent(struct otri *checktri, struct event **freeevents,
->                      struct event **eventheap, int *heapsize);
-> REAL orient3d(struct mesh *m, struct behavior *b,
->               vertex pa, vertex pb, vertex pc, vertex pd,
->               REAL aheight, REAL bheight, REAL cheight, REAL dheight);
-> REAL circletop(struct mesh *m, vertex pa, vertex pb, vertex pc, REAL ccwabc);
-> void poolinit(struct memorypool *pool, int bytecount, int itemcount,
->               int firstitemcount, int alignment);
-> void eventheapinsert(struct event **heap, int heapsize, struct event *newevent);
-> int rightofhyperbola(struct mesh *m, struct otri *fronttri, vertex newsite);
-> void insertsubseg(struct mesh *m, struct behavior *b, struct otri *tri,
->                   int subsegmark);
-> int scoutsegment(struct mesh *m, struct behavior *b, struct otri *searchtri,
->                  vertex endpoint2, int newmark);
-> vertex getvertex(struct mesh *m, struct behavior *b, int number);
-> void internalerror();
-> unsigned long randomnation(unsigned int choices);
-> struct splaynode *splayinsert(struct mesh *m, struct splaynode *splayroot,
->                               struct otri *newkey, vertex searchpoint);
-> void delaunayfixup(struct mesh *m, struct behavior *b,
->                    struct otri *fixuptri, int leftside);
-> void traversalinit(struct memorypool *pool);
-> enum insertvertexresult insertvertex(struct mesh *m, struct behavior *b,
->                                      vertex newvertex, struct otri *searchtri,
->                                      struct osub *splitseg,
->                                      int segmentflaws, int triflaws);
-> void conformingedge(struct mesh *m, struct behavior *b,
->                     vertex endpoint1, vertex endpoint2, int newmark);
-> enum finddirectionresult finddirection(struct mesh *m, struct behavior *b,
->                                        struct otri *searchtri,
->                                        vertex searchpoint);
-> VOID *traverse(struct memorypool *pool);
-> void deletevertex(struct mesh *m, struct behavior *b, struct otri *deltri);
-> void pooldealloc(struct memorypool *pool, VOID *dyingitem);
-> int checkseg4encroach(struct mesh *m, struct behavior *b,
->                       struct osub *testsubseg);
-> void badsubsegdealloc(struct mesh *m, struct badsubseg *dyingseg);
-> void vertexdealloc(struct mesh *m, vertex dyingvertex);
-> void vertexsort(vertex *sortarray, int arraysize);
-> void tallyencs(struct mesh *m, struct behavior *b);
-> void splittriangle(struct mesh *m, struct behavior *b,
->                    struct badtriang *badtri);
-> subseg *subsegtraverse(struct mesh *m);
-> enum locateresult locate(struct mesh *m, struct behavior *b,
->                          vertex searchpoint, struct otri *searchtri);
-> void writenodes(struct mesh *m, struct behavior *b, REAL **pointlist,
->                 REAL **pointattriblist, int **pointmarkerlist);
-> void writevoronoi(struct mesh *m, struct behavior *b, REAL **vpointlist,
->                   REAL **vpointattriblist, int **vpointmarkerlist,
->                   int **vedgelist, int **vedgemarkerlist, REAL **vnormlist);
-> void writeneighbors(struct mesh *m, struct behavior *b, int **neighborlist);
-> void testtriangle(struct mesh *m, struct behavior *b, struct otri *testtri);
-> void triangleinit(struct mesh *m);
-> 
-> 
-1408a1514
-> void triexit(int status);
-1410d1515
-< #ifdef ANSI_DECLARATORS
-1412,1416d1516
-< #else /* not ANSI_DECLARATORS */
-< void triexit(status)
-< int status;
-< #endif /* not ANSI_DECLARATORS */
-< 
-1421c1521
-< #ifdef ANSI_DECLARATORS
----
-> VOID *trimalloc(int size);
-1423,1427d1522
-< #else /* not ANSI_DECLARATORS */
-< VOID *trimalloc(size)
-< int size;
-< #endif /* not ANSI_DECLARATORS */
-< 
-1431c1526,1527
-<   memptr = (VOID *) malloc((unsigned int) size);
----
->   memptr = (VOID *) mxMalloc((unsigned int) size);
->   //memptr = (VOID *) malloc((unsigned int) size);
-1447c1543,1544
-<   free(memptr);
----
->   //free(memptr);
->   mxFree(memptr);
-3665,3670c3762,3767
-< void printtriangle(struct mesh *m, struct behavior *b, struct otri *t)
-< #else /* not ANSI_DECLARATORS */
-< void printtriangle(m, b, t)
-< struct mesh *m;
-< struct behavior *b;
-< struct otri *t;
----
-> void printtriangle(struct mesh *m, struct behavior *b, struct otri *t){
-> //#else /* not ANSI_DECLARATORS */
-> //void printtriangle(m, b, t)
-> //struct mesh *m;
-> //struct behavior *b;
-> //struct otri *t;
-3673c3770
-< {
----
-> //{
-4910c5007
-<   _FPU_SETCW(cword);
----
->   //_FPU_SETCW(cword); //taken care of by Matlab
Index: sm/trunk/externalpackages/triangle/triangle.c.patch.python
===================================================================
--- /issm/trunk/externalpackages/triangle/triangle.c.patch.python	(revision 13394)
+++ 	(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/trunk/externalpackages/valgrind/install-altix64.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-altix64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/valgrind/install-altix64.sh	(revision 13395)
@@ -1,17 +1,18 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
-rm -rf install valgrind-3.7.0
+rm -rf install valgrind-3.8.0
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.7.0.tar.bz2' 'valgrind-3.7.0.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.0.tar.bz2' 'valgrind-3.8.0.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.7.0.tar.bz2
+tar -jxvf  valgrind-3.8.0.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.7.0/* install
-rm -rf valgrind-3.7.0
+mv valgrind-3.8.0/* install
+rm -rf valgrind-3.8.0
 
 #configure
Index: /issm/trunk/externalpackages/valgrind/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-linux64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/valgrind/install-linux64.sh	(revision 13395)
@@ -1,17 +1,18 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
-rm -rf install valgrind-3.7.0
+rm -rf install valgrind-3.8.0
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.7.0.tar.bz2' 'valgrind-3.7.0.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.0.tar.bz2' 'valgrind-3.8.0.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.7.0.tar.bz2
+tar -jxvf  valgrind-3.8.0.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.7.0/* install
-rm -rf valgrind-3.7.0
+mv valgrind-3.8.0/* install
+rm -rf valgrind-3.8.0
 
 #configure
@@ -25,3 +26,3 @@
 #final thing: if mpi is compiled in, soft link its target to a simpler name
 cd lib
-ln -s valgrind/libmpi*  ./libmpidebug.so
+ln -s valgrind/libmpiwrap-*  ./libmpidebug.so
Index: /issm/trunk/externalpackages/valgrind/install-macosx32.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-macosx32.sh	(revision 13394)
+++ /issm/trunk/externalpackages/valgrind/install-macosx32.sh	(revision 13395)
@@ -1,17 +1,18 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
-rm -rf install valgrind-3.7.0
+rm -rf install valgrind-3.8.0
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.7.0.tar.bz2' 'valgrind-3.7.0.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.0.tar.bz2' 'valgrind-3.8.0.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.7.0.tar.bz2
+tar -jxvf  valgrind-3.8.0.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.7.0/* install
-rm -rf valgrind-3.7.0
+mv valgrind-3.8.0/* install
+rm -rf valgrind-3.8.0
 
 #configure
Index: /issm/trunk/externalpackages/valgrind/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-macosx64.sh	(revision 13394)
+++ /issm/trunk/externalpackages/valgrind/install-macosx64.sh	(revision 13395)
@@ -1,17 +1,18 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
-rm -rf install valgrind-3.7.0
+rm -rf install valgrind-3.8.0
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.7.0.tar.bz2' 'valgrind-3.7.0.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.0.tar.bz2' 'valgrind-3.8.0.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.7.0.tar.bz2
+tar -jxvf  valgrind-3.8.0.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.7.0/* install
-rm -rf valgrind-3.7.0
+mv valgrind-3.8.0/* install
+rm -rf valgrind-3.8.0
 
 #configure
Index: /issm/trunk/externalpackages/valgrind/install-win32.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-win32.sh	(revision 13394)
+++ /issm/trunk/externalpackages/valgrind/install-win32.sh	(revision 13395)
@@ -1,17 +1,18 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
-rm -rf install valgrind-3.7.0
+rm -rf install valgrind-3.8.0
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.7.0.tar.bz2' 'valgrind-3.7.0.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.0.tar.bz2' 'valgrind-3.8.0.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.7.0.tar.bz2
+tar -jxvf  valgrind-3.8.0.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.7.0/* install
-rm -rf valgrind-3.7.0
+mv valgrind-3.8.0/* install
+rm -rf valgrind-3.8.0
 
 #configure
Index: /issm/trunk/externalpackages/vim/addons/vim/syntax/Synchronize.sh
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 13394)
+++ /issm/trunk/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 13395)
@@ -6,14 +6,14 @@
 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 "[a-z]Enum," -e "[A-Z]Enum," | grep -v StringToEnum | sed -e "s/,//g" | awk '{ printf "syn keyword cConstant " $1 "\n"}' >> temp
 echo "\"ISSM's Enums end" >> temp
 cat c.vim | sed "1,/ISSM's Enums end/d" >> temp
-
 mv temp c.vim
+exit 1
 
 #Synchronize objects
 cat c.vim | sed "/ISSM's objects begin/,/vim: ts=8/d" > temp
 echo "\"ISSM's objects begin" >> temp
-cat ../../../../../src/c/objects/objects.h  | grep "\.h" | sed -e "s/\// /g" -e "s/\.h\"//" | awk '{print  $(NF)}' | awk '{ printf "syn keyword cType " $1 "\n"}' >> temp
+find ../../../../../src/c/classes -name "*.h" | sed -e "s/\// /g" -e "s/\.h//"| awk '{print  $(NF)}' | awk '{ printf "syn keyword cType " $1 "\n"}'>> temp
 echo "\"ISSM's objects end" >> temp
 cat c.vim | sed "1,/ISSM's objects end/d" >> temp
Index: /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 13394)
+++ /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 13395)
@@ -408,152 +408,164 @@
 syn keyword	cType		Vec Mat SeqVec SeqMat
 "other ISSM's syntax
-syn keyword	cType		mxArray ErrorException QuadtreeBox IssmDouble IssmPDouble
+syn keyword	cType		mxArray ErrorException QuadtreeBox IssmDouble IssmPDouble Observations
 
 "ISSM's objects begin
-syn keyword cType objects.h
-syn keyword cType Object
-syn keyword cType Hook
-syn keyword cType DofIndexing
-syn keyword cType Vertex
-syn keyword cType Node
-syn keyword cType Segment
-syn keyword cType IoModel
-syn keyword cType Patch
-syn keyword cType Update
-syn keyword cType Constraint
-syn keyword cType SpcStatic
-syn keyword cType SpcTransient
-syn keyword cType SpcDynamic
+syn keyword cType GaussPenta
+syn keyword cType gaussobjects
 syn keyword cType GaussTria
-syn keyword cType GaussPenta
-syn keyword cType Load
-syn keyword cType Friction
-syn keyword cType Icefront
-syn keyword cType Numericalflux
-syn keyword cType Riftfront
-syn keyword cType Penpair
-syn keyword cType Pengrid
-syn keyword cType Element
-syn keyword cType Penta
-syn keyword cType PentaHook
-syn keyword cType PentaRef
-syn keyword cType Tria
-syn keyword cType TriaHook
-syn keyword cType TriaRef
-syn keyword cType KML_Attribute
-syn keyword cType KML_Comment
-syn keyword cType KML_ColorStyle
-syn keyword cType KML_Container
-syn keyword cType KML_Document
-syn keyword cType KML_Feature
-syn keyword cType KML_File
-syn keyword cType KML_Folder
-syn keyword cType KML_Geometry
-syn keyword cType KML_GroundOverlay
-syn keyword cType KML_Icon
-syn keyword cType KML_LatLonBox
-syn keyword cType KML_LinearRing
-syn keyword cType KML_LineString
-syn keyword cType KML_LineStyle
-syn keyword cType KML_MultiGeometry
-syn keyword cType KML_Object
-syn keyword cType KML_Overlay
-syn keyword cType KML_Point
-syn keyword cType KML_Placemark
-syn keyword cType KML_Polygon
-syn keyword cType KML_PolyStyle
-syn keyword cType KML_Style
-syn keyword cType KML_StyleSelector
-syn keyword cType KML_SubStyle
-syn keyword cType KML_Unknown
-syn keyword cType KMLFileReadUtils
-syn keyword cType Option
-syn keyword cType OptionDouble
-syn keyword cType OptionLogical
-syn keyword cType OptionChar
-syn keyword cType OptionStruct
-syn keyword cType OptionCell
-syn keyword cType OptionUtilities
-syn keyword cType Input
-syn keyword cType BoolInput
-syn keyword cType DoubleInput
-syn keyword cType IntInput
-syn keyword cType PentaP1Input
-syn keyword cType TriaP1Input
-syn keyword cType ControlInput
-syn keyword cType DatasetInput
-syn keyword cType TransientInput
-syn keyword cType ElementResult
-syn keyword cType DoubleElementResult
-syn keyword cType TriaP1ElementResult
-syn keyword cType PentaP1ElementResult
-syn keyword cType BoolElementResult
-syn keyword cType ExternalResult
-syn keyword cType BoolExternalResult
-syn keyword cType DoubleExternalResult
-syn keyword cType DoubleVecExternalResult
-syn keyword cType DoubleMatExternalResult
-syn keyword cType IntExternalResult
-syn keyword cType PetscVecExternalResult
-syn keyword cType StringExternalResult
+syn keyword cType objects
 syn keyword cType Material
 syn keyword cType Matice
 syn keyword cType Matpar
+syn keyword cType objects
+syn keyword cType Contour
+syn keyword cType DoubleInput
+syn keyword cType Input
+syn keyword cType ControlInput
+syn keyword cType DatasetInput
+syn keyword cType IntInput
+syn keyword cType BoolInput
+syn keyword cType TriaP1Input
+syn keyword cType TransientInput
+syn keyword cType PentaP1Input
+syn keyword cType KML_Icon
+syn keyword cType KML_Point
+syn keyword cType KML_LinearRing
+syn keyword cType KML_Feature
+syn keyword cType KMLFileReadUtils
+syn keyword cType KML_StyleSelector
+syn keyword cType KML_LatLonBox
+syn keyword cType KML_Attribute
+syn keyword cType KML_PolyStyle
+syn keyword cType KML_Object
+syn keyword cType KML_SubStyle
+syn keyword cType KML_LineString
+syn keyword cType KML_Overlay
+syn keyword cType KML_Container
+syn keyword cType KML_Polygon
+syn keyword cType KML_Geometry
+syn keyword cType KML_ColorStyle
+syn keyword cType KML_Placemark
+syn keyword cType KML_Unknown
+syn keyword cType KML_GroundOverlay
+syn keyword cType KML_Style
+syn keyword cType KML_Comment
+syn keyword cType KML_MultiGeometry
+syn keyword cType KML_LineStyle
+syn keyword cType KML_Folder
+syn keyword cType KML_Document
+syn keyword cType KML_File
+syn keyword cType DoubleVecParam
+syn keyword cType DoubleParam
+syn keyword cType DoubleMatArrayParam
+syn keyword cType DoubleMatParam
+syn keyword cType Param
+syn keyword cType FileParam
+syn keyword cType IntVecParam
+syn keyword cType IntParam
+syn keyword cType BoolParam
+syn keyword cType IntMatParam
+syn keyword cType VectorParam
+syn keyword cType DoubleTransientMatParam
+syn keyword cType MatrixParam
+syn keyword cType StringArrayParam
+syn keyword cType StringParam
+syn keyword cType TransientParam
+syn keyword cType OptionStruct
+syn keyword cType OptionDouble
+syn keyword cType OptionLogical
+syn keyword cType OptionUtilities
+syn keyword cType OptionChar
+syn keyword cType Option
+syn keyword cType OptionCell
+syn keyword cType Segment
+syn keyword cType Icefront
+syn keyword cType Friction
+syn keyword cType Riftfront
+syn keyword cType Numericalflux
+syn keyword cType Penpair
+syn keyword cType Load
+syn keyword cType Pengrid
+syn keyword cType Object
+syn keyword cType DoubleVecExternalResult
+syn keyword cType DoubleExternalResult
+syn keyword cType IntExternalResult
+syn keyword cType BoolExternalResult
+syn keyword cType DoubleMatExternalResult
+syn keyword cType PetscVecExternalResult
+syn keyword cType ExternalResult
+syn keyword cType StringExternalResult
+syn keyword cType Vertex
+syn keyword cType SpcDynamic
+syn keyword cType SpcStatic
+syn keyword cType SpcTransient
+syn keyword cType Constraint
+syn keyword cType TriaP1ElementResult
+syn keyword cType PentaP1ElementResult
+syn keyword cType DoubleElementResult
+syn keyword cType ElementResultLocal
+syn keyword cType BoolElementResult
+syn keyword cType ElementResult
+syn keyword cType Node
+syn keyword cType TriaRef
+syn keyword cType TriaHook
+syn keyword cType PentaRef
+syn keyword cType PentaHook
+syn keyword cType Tria
+syn keyword cType Element
+syn keyword cType Penta
+syn keyword cType classes
+syn keyword cType DofIndexing
+syn keyword cType Patch
+syn keyword cType Hook
+syn keyword cType Quadtree
+syn keyword cType Observation
+syn keyword cType ExponentialVariogram
+syn keyword cType GaussianVariogram
+syn keyword cType SphericalVariogram
+syn keyword cType PowerVariogram
+syn keyword cType krigingobjects
+syn keyword cType Variogram
+syn keyword cType DakotaPlugin
+syn keyword cType ElementVector
 syn keyword cType ElementMatrix
-syn keyword cType ElementVector
+syn keyword cType matrixobjects
 syn keyword cType Vector
 syn keyword cType Matrix
-syn keyword cType BoolParam
-syn keyword cType DoubleMatParam
-syn keyword cType DoubleTransientMatParam
-syn keyword cType DoubleMatArrayParam
-syn keyword cType DoubleParam
-syn keyword cType DoubleVecParam
-syn keyword cType IntParam
-syn keyword cType IntVecParam
-syn keyword cType IntMatParam
-syn keyword cType FileParam
-syn keyword cType Param
-syn keyword cType MatrixParam
-syn keyword cType VectorParam
-syn keyword cType StringArrayParam
-syn keyword cType StringParam
-syn keyword cType Contour
-syn keyword cType FemModel
-syn keyword cType OptArgs
-syn keyword cType OptPars
+syn keyword cType GeomSubDomain
+syn keyword cType Geometry
+syn keyword cType AdjacentTriangle
+syn keyword cType VertexOnEdge
+syn keyword cType BamgQuadtree
+syn keyword cType Edge
+syn keyword cType BamgVertex
+syn keyword cType SetOfE4
+syn keyword cType GeomEdge
+syn keyword cType Direction
+syn keyword cType VertexOnGeom
+syn keyword cType R2
+syn keyword cType Mesh
+syn keyword cType ListofIntersectionTriangles
+syn keyword cType Triangle
+syn keyword cType DoubleAndInt
+syn keyword cType VertexOnVertex
 syn keyword cType BamgOpts
 syn keyword cType BamgGeom
+syn keyword cType bamgobjects
+syn keyword cType CrackedEdge
+syn keyword cType SubDomain
 syn keyword cType BamgMesh
 syn keyword cType Metric
-syn keyword cType DoubleAndInt
-syn keyword cType Direction
-syn keyword cType BamgVertex
-syn keyword cType AdjacentTriangle
-syn keyword cType Edge
+syn keyword cType include
+syn keyword cType typedefs
+syn keyword cType Curve
+syn keyword cType macros
 syn keyword cType GeomVertex
-syn keyword cType GeomEdge
-syn keyword cType Curve
-syn keyword cType Triangle
-syn keyword cType ListofIntersectionTriangles
-syn keyword cType GeomSubDomain
-syn keyword cType SubDomain
-syn keyword cType VertexOnGeom
-syn keyword cType VertexOnVertex
-syn keyword cType VertexOnEdge
-syn keyword cType CrackedEdge
-syn keyword cType Mesh
-syn keyword cType Geometry
-syn keyword cType BamgQuadtree
-syn keyword cType SetOfE4
-syn keyword cType Variogram
-syn keyword cType GaussianVariogram
-syn keyword cType ExponentialVariogram
-syn keyword cType SphericalVariogram
-syn keyword cType PowerVariogram
-syn keyword cType Quadtree
-syn keyword cType Observation
+syn keyword cType OptArgs
+syn keyword cType Update
+syn keyword cType OptPars
+syn keyword cType IoModel
+syn keyword cType FemModel
 "ISSM's objects end
-
 "ISSM's Enums begin
 syn keyword cConstant AutodiffForwardEnum
@@ -694,8 +706,14 @@
 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 SurfaceforcingsDelta18oSurfaceEnum
+syn keyword cConstant SurfaceforcingsIsdelta18oEnum
+syn keyword cConstant SurfaceforcingsPrecipitationsPresentdayEnum
+syn keyword cConstant SurfaceforcingsTemperaturesPresentdayEnum
+syn keyword cConstant SurfaceforcingsTemperaturesLgmEnum
+syn keyword cConstant DebugProfilingEnum
+syn keyword cConstant ProfilingCurrentMemEnum
+syn keyword cConstant ProfilingCurrentFlopsEnum
+syn keyword cConstant ProfilingSolutionTimeEnum
 syn keyword cConstant MaxIterationConvergenceFlagEnum
 syn keyword cConstant SteadystateMaxiterEnum
@@ -807,4 +825,5 @@
 syn keyword cConstant IntParamEnum
 syn keyword cConstant IntVecParamEnum
+syn keyword cConstant TransientParamEnum
 syn keyword cConstant MacAyeal2dIceFrontEnum
 syn keyword cConstant MacAyeal3dIceFrontEnum
@@ -926,4 +945,7 @@
 syn keyword cConstant StressTensorzzEnum
 syn keyword cConstant IceVolumeEnum
+syn keyword cConstant TotalSmbEnum
+syn keyword cConstant ThicknessAlongGradientEnum
+syn keyword cConstant ThicknessAcrossGradientEnum
 syn keyword cConstant P0Enum
 syn keyword cConstant P1Enum
@@ -1009,22 +1031,22 @@
 
 if !exists("c_no_ansi") || exists("c_ansi_typedefs")
-  syn keyword   cType		size_t ssize_t wchar_t ptrdiff_t sig_atomic_t fpos_t
-  syn keyword   cType		clock_t time_t va_list jmp_buf FILE DIR div_t ldiv_t
-  syn keyword   cType		mbstate_t wctrans_t wint_t wctype_t
-  syn keyword   cType		lldiv_t float_t double_t fenv_t fexcept_t
+	syn keyword   cType		size_t ssize_t wchar_t ptrdiff_t sig_atomic_t fpos_t
+	syn keyword   cType		clock_t time_t va_list jmp_buf FILE DIR div_t ldiv_t
+	syn keyword   cType		mbstate_t wctrans_t wint_t wctype_t
+	syn keyword   cType		lldiv_t float_t double_t fenv_t fexcept_t
 endif
 if !exists("c_no_c99") " ISO C99
-  syn keyword	cType		bool complex imaginary
-  syn keyword	cType		int8_t int16_t int32_t int64_t
-  syn keyword	cType		uint8_t uint16_t uint32_t uint64_t
-  syn keyword	cType		int_least8_t int_least16_t int_least32_t int_least64_t
-  syn keyword	cType		uint_least8_t uint_least16_t uint_least32_t uint_least64_t
-  syn keyword	cType		int_fast8_t int_fast16_t int_fast32_t int_fast64_t
-  syn keyword	cType		uint_fast8_t uint_fast16_t uint_fast32_t uint_fast64_t
-  syn keyword	cType		intptr_t uintptr_t
-  syn keyword	cType		intmax_t uintmax_t
+	syn keyword	cType		bool complex imaginary
+	syn keyword	cType		int8_t int16_t int32_t int64_t
+	syn keyword	cType		uint8_t uint16_t uint32_t uint64_t
+	syn keyword	cType		int_least8_t int_least16_t int_least32_t int_least64_t
+	syn keyword	cType		uint_least8_t uint_least16_t uint_least32_t uint_least64_t
+	syn keyword	cType		int_fast8_t int_fast16_t int_fast32_t int_fast64_t
+	syn keyword	cType		uint_fast8_t uint_fast16_t uint_fast32_t uint_fast64_t
+	syn keyword	cType		intptr_t uintptr_t
+	syn keyword	cType		intmax_t uintmax_t
 endif
 if exists("c_gnu")
-  syn keyword	cType		__label__ __complex__ __volatile__
+	syn keyword	cType		__label__ __complex__ __volatile__
 endif
 
@@ -1032,89 +1054,89 @@
 syn keyword	cStorageClass	static register auto volatile extern const VOL
 if exists("c_gnu")
-  syn keyword	cStorageClass	inline __attribute__
+	syn keyword	cStorageClass	inline __attribute__
 endif
 if !exists("c_no_c99")
-  syn keyword	cStorageClass	inline restrict
+	syn keyword	cStorageClass	inline restrict
 endif
 
 if !exists("c_no_ansi") || exists("c_ansi_constants") || exists("c_gnu")
-  if exists("c_gnu")
-    syn keyword cConstant __GNUC__ __FUNCTION__ __PRETTY_FUNCTION__
-  endif
-  syn keyword cConstant __LINE__ __FILE__ __DATE__ __TIME__ __STDC__ __func__
-  syn keyword cConstant __STDC_VERSION__
-  syn keyword cConstant CHAR_BIT MB_LEN_MAX MB_CUR_MAX
-  syn keyword cConstant UCHAR_MAX UINT_MAX ULONG_MAX USHRT_MAX
-  syn keyword cConstant CHAR_MIN INT_MIN LONG_MIN SHRT_MIN
-  syn keyword cConstant CHAR_MAX INT_MAX LONG_MAX SHRT_MAX
-  syn keyword cConstant SCHAR_MIN SINT_MIN SLONG_MIN SSHRT_MIN
-  syn keyword cConstant SCHAR_MAX SINT_MAX SLONG_MAX SSHRT_MAX
-  if !exists("c_no_c99")
-    syn keyword cConstant LLONG_MIN LLONG_MAX ULLONG_MAX
-    syn keyword cConstant INT8_MIN INT16_MIN INT32_MIN INT64_MIN
-    syn keyword cConstant INT8_MAX INT16_MAX INT32_MAX INT64_MAX
-    syn keyword cConstant UINT8_MAX UINT16_MAX UINT32_MAX UINT64_MAX
-    syn keyword cConstant INT_LEAST8_MIN INT_LEAST16_MIN INT_LEAST32_MIN INT_LEAST64_MIN
-    syn keyword cConstant INT_LEAST8_MAX INT_LEAST16_MAX INT_LEAST32_MAX INT_LEAST64_MAX
-    syn keyword cConstant UINT_LEAST8_MAX UINT_LEAST16_MAX UINT_LEAST32_MAX UINT_LEAST64_MAX
-    syn keyword cConstant INT_FAST8_MIN INT_FAST16_MIN INT_FAST32_MIN INT_FAST64_MIN
-    syn keyword cConstant INT_FAST8_MAX INT_FAST16_MAX INT_FAST32_MAX INT_FAST64_MAX
-    syn keyword cConstant UINT_FAST8_MAX UINT_FAST16_MAX UINT_FAST32_MAX UINT_FAST64_MAX
-    syn keyword cConstant INTPTR_MIN INTPTR_MAX UINTPTR_MAX
-    syn keyword cConstant INTMAX_MIN INTMAX_MAX UINTMAX_MAX
-    syn keyword cConstant PTRDIFF_MIN PTRDIFF_MAX SIG_ATOMIC_MIN SIG_ATOMIC_MAX
-    syn keyword cConstant SIZE_MAX WCHAR_MIN WCHAR_MAX WINT_MIN WINT_MAX
-  endif
-  syn keyword cConstant FLT_RADIX FLT_ROUNDS
-  syn keyword cConstant FLT_DIG FLT_MANT_DIG FLT_EPSILON
-  syn keyword cConstant DBL_DIG DBL_MANT_DIG DBL_EPSILON
-  syn keyword cConstant LDBL_DIG LDBL_MANT_DIG LDBL_EPSILON
-  syn keyword cConstant FLT_MIN FLT_MAX FLT_MIN_EXP FLT_MAX_EXP
-  syn keyword cConstant FLT_MIN_10_EXP FLT_MAX_10_EXP
-  syn keyword cConstant DBL_MIN DBL_MAX DBL_MIN_EXP DBL_MAX_EXP
-  syn keyword cConstant DBL_MIN_10_EXP DBL_MAX_10_EXP
-  syn keyword cConstant LDBL_MIN LDBL_MAX LDBL_MIN_EXP LDBL_MAX_EXP
-  syn keyword cConstant LDBL_MIN_10_EXP LDBL_MAX_10_EXP
-  syn keyword cConstant HUGE_VAL CLOCKS_PER_SEC NULL _NO_LEAP_SECONDS _LOCALTIME
-  syn keyword cConstant LC_ALL LC_COLLATE LC_CTYPE LC_MONETARY
-  syn keyword cConstant LC_NUMERIC LC_TIME
-" syn keyword cConstant SIG_DFL SIG_ERR SIG_IGN
-  syn keyword cAnsiFuncPtr SIG_DFL SIG_ERR SIG_IGN
-  syn keyword cConstant SIGABRT SIGFPE SIGILL SIGHUP SIGINT SIGSEGV SIGTERM
-  syn keyword cConstant INFINITY     FP_SUBNORMAL FP_ILOGB0
-  syn keyword cConstant NAN          FP_ZERO      FP_ILOGBNAN
-  syn keyword cConstant FP_INFINITE  FP_FAST_FMA
-  syn keyword cConstant HUGE_VALF    FP_NAN       FP_FAST_FMAF
-  syn keyword cConstant HUGE_VALL    FP_NORMAL    FP_FAST_FMAL
-  syn keyword cConstant FE_OVERFLOW      FE_TOWARDZERO
-  syn keyword cConstant FE_UNDERFLOW     FE_UPWARD
-  syn keyword cConstant FE_DIVBYZERO     FE_ALL_EXCEPT    FE_DFL_ENV
-  syn keyword cConstant FE_INEXACT       FE_DOWNWARD
-  syn keyword cConstant FE_INVALID       FE_TONEAREST
-  syn keyword cConstant	_Complex_I _Imaginary_I 
-  " Add POSIX signals as well...
-  syn keyword cConstant SIGABRT SIGALRM SIGCHLD SIGCONT SIGFPE SIGHUP
-  syn keyword cConstant SIGILL SIGINT SIGKILL SIGPIPE SIGQUIT SIGSEGV
-  syn keyword cConstant SIGSTOP SIGTERM SIGTRAP SIGTSTP SIGTTIN SIGTTOU
-  syn keyword cConstant SIGUSR1 SIGUSR2
-  syn keyword cConstant _IOFBF _IOLBF _IONBF BUFSIZ EOF WEOF
-  syn keyword cConstant FOPEN_MAX FILENAME_MAX L_tmpnam
-  syn keyword cConstant SEEK_CUR SEEK_END SEEK_SET
-  syn keyword cConstant TMP_MAX stderr stdin stdout
-  syn keyword cConstant EXIT_FAILURE EXIT_SUCCESS RAND_MAX
-  " Add POSIX errors as well
-  syn keyword cConstant E2BIG EACCES EAGAIN EBADF EBADMSG EBUSY
-  syn keyword cConstant ECANCELED ECHILD EDEADLK EDOM EEXIST EFAULT
-  syn keyword cConstant EFBIG EILSEQ EINPROGRESS EINTR EINVAL EIO EISDIR
-  syn keyword cConstant EMFILE EMLINK EMSGSIZE ENAMETOOLONG ENFILE ENODEV
-  syn keyword cConstant ENOENT ENOEXEC ENOLCK ENOMEM ENOSPC ENOSYS
-  syn keyword cConstant ENOTDIR ENOTEMPTY ENOTSUP ENOTTY ENXIO EPERM
-  syn keyword cConstant EPIPE ERANGE EROFS ESPIPE ESRCH ETIMEDOUT EXDEV
-  " math.h
-  syn keyword cConstant M_E M_LOG2E M_LOG10E M_LN2 M_LN10 M_PI M_PI_2 M_PI_4
-  syn keyword cConstant M_1_PI M_2_PI M_2_SQRTPI M_SQRT2 M_SQRT1_2
+	if exists("c_gnu")
+		syn keyword cConstant __GNUC__ __FUNCTION__ __PRETTY_FUNCTION__
+	endif
+	syn keyword cConstant __LINE__ __FILE__ __DATE__ __TIME__ __STDC__ __func__
+	syn keyword cConstant __STDC_VERSION__
+	syn keyword cConstant CHAR_BIT MB_LEN_MAX MB_CUR_MAX
+	syn keyword cConstant UCHAR_MAX UINT_MAX ULONG_MAX USHRT_MAX
+	syn keyword cConstant CHAR_MIN INT_MIN LONG_MIN SHRT_MIN
+	syn keyword cConstant CHAR_MAX INT_MAX LONG_MAX SHRT_MAX
+	syn keyword cConstant SCHAR_MIN SINT_MIN SLONG_MIN SSHRT_MIN
+	syn keyword cConstant SCHAR_MAX SINT_MAX SLONG_MAX SSHRT_MAX
+	if !exists("c_no_c99")
+		syn keyword cConstant LLONG_MIN LLONG_MAX ULLONG_MAX
+		syn keyword cConstant INT8_MIN INT16_MIN INT32_MIN INT64_MIN
+		syn keyword cConstant INT8_MAX INT16_MAX INT32_MAX INT64_MAX
+		syn keyword cConstant UINT8_MAX UINT16_MAX UINT32_MAX UINT64_MAX
+		syn keyword cConstant INT_LEAST8_MIN INT_LEAST16_MIN INT_LEAST32_MIN INT_LEAST64_MIN
+		syn keyword cConstant INT_LEAST8_MAX INT_LEAST16_MAX INT_LEAST32_MAX INT_LEAST64_MAX
+		syn keyword cConstant UINT_LEAST8_MAX UINT_LEAST16_MAX UINT_LEAST32_MAX UINT_LEAST64_MAX
+		syn keyword cConstant INT_FAST8_MIN INT_FAST16_MIN INT_FAST32_MIN INT_FAST64_MIN
+		syn keyword cConstant INT_FAST8_MAX INT_FAST16_MAX INT_FAST32_MAX INT_FAST64_MAX
+		syn keyword cConstant UINT_FAST8_MAX UINT_FAST16_MAX UINT_FAST32_MAX UINT_FAST64_MAX
+		syn keyword cConstant INTPTR_MIN INTPTR_MAX UINTPTR_MAX
+		syn keyword cConstant INTMAX_MIN INTMAX_MAX UINTMAX_MAX
+		syn keyword cConstant PTRDIFF_MIN PTRDIFF_MAX SIG_ATOMIC_MIN SIG_ATOMIC_MAX
+		syn keyword cConstant SIZE_MAX WCHAR_MIN WCHAR_MAX WINT_MIN WINT_MAX
+	endif
+	syn keyword cConstant FLT_RADIX FLT_ROUNDS
+	syn keyword cConstant FLT_DIG FLT_MANT_DIG FLT_EPSILON
+	syn keyword cConstant DBL_DIG DBL_MANT_DIG DBL_EPSILON
+	syn keyword cConstant LDBL_DIG LDBL_MANT_DIG LDBL_EPSILON
+	syn keyword cConstant FLT_MIN FLT_MAX FLT_MIN_EXP FLT_MAX_EXP
+	syn keyword cConstant FLT_MIN_10_EXP FLT_MAX_10_EXP
+	syn keyword cConstant DBL_MIN DBL_MAX DBL_MIN_EXP DBL_MAX_EXP
+	syn keyword cConstant DBL_MIN_10_EXP DBL_MAX_10_EXP
+	syn keyword cConstant LDBL_MIN LDBL_MAX LDBL_MIN_EXP LDBL_MAX_EXP
+	syn keyword cConstant LDBL_MIN_10_EXP LDBL_MAX_10_EXP
+	syn keyword cConstant HUGE_VAL CLOCKS_PER_SEC NULL _NO_LEAP_SECONDS _LOCALTIME
+	syn keyword cConstant LC_ALL LC_COLLATE LC_CTYPE LC_MONETARY
+	syn keyword cConstant LC_NUMERIC LC_TIME
+	" syn keyword cConstant SIG_DFL SIG_ERR SIG_IGN
+	syn keyword cAnsiFuncPtr SIG_DFL SIG_ERR SIG_IGN
+	syn keyword cConstant SIGABRT SIGFPE SIGILL SIGHUP SIGINT SIGSEGV SIGTERM
+	syn keyword cConstant INFINITY     FP_SUBNORMAL FP_ILOGB0
+	syn keyword cConstant NAN          FP_ZERO      FP_ILOGBNAN
+	syn keyword cConstant FP_INFINITE  FP_FAST_FMA
+	syn keyword cConstant HUGE_VALF    FP_NAN       FP_FAST_FMAF
+	syn keyword cConstant HUGE_VALL    FP_NORMAL    FP_FAST_FMAL
+	syn keyword cConstant FE_OVERFLOW      FE_TOWARDZERO
+	syn keyword cConstant FE_UNDERFLOW     FE_UPWARD
+	syn keyword cConstant FE_DIVBYZERO     FE_ALL_EXCEPT    FE_DFL_ENV
+	syn keyword cConstant FE_INEXACT       FE_DOWNWARD
+	syn keyword cConstant FE_INVALID       FE_TONEAREST
+	syn keyword cConstant	_Complex_I _Imaginary_I 
+	" Add POSIX signals as well...
+	syn keyword cConstant SIGABRT SIGALRM SIGCHLD SIGCONT SIGFPE SIGHUP
+	syn keyword cConstant SIGILL SIGINT SIGKILL SIGPIPE SIGQUIT SIGSEGV
+	syn keyword cConstant SIGSTOP SIGTERM SIGTRAP SIGTSTP SIGTTIN SIGTTOU
+	syn keyword cConstant SIGUSR1 SIGUSR2
+	syn keyword cConstant _IOFBF _IOLBF _IONBF BUFSIZ EOF WEOF
+	syn keyword cConstant FOPEN_MAX FILENAME_MAX L_tmpnam
+	syn keyword cConstant SEEK_CUR SEEK_END SEEK_SET
+	syn keyword cConstant TMP_MAX stderr stdin stdout
+	syn keyword cConstant EXIT_FAILURE EXIT_SUCCESS RAND_MAX
+	" Add POSIX errors as well
+	syn keyword cConstant E2BIG EACCES EAGAIN EBADF EBADMSG EBUSY
+	syn keyword cConstant ECANCELED ECHILD EDEADLK EDOM EEXIST EFAULT
+	syn keyword cConstant EFBIG EILSEQ EINPROGRESS EINTR EINVAL EIO EISDIR
+	syn keyword cConstant EMFILE EMLINK EMSGSIZE ENAMETOOLONG ENFILE ENODEV
+	syn keyword cConstant ENOENT ENOEXEC ENOLCK ENOMEM ENOSPC ENOSYS
+	syn keyword cConstant ENOTDIR ENOTEMPTY ENOTSUP ENOTTY ENXIO EPERM
+	syn keyword cConstant EPIPE ERANGE EROFS ESPIPE ESRCH ETIMEDOUT EXDEV
+	" math.h
+	syn keyword cConstant M_E M_LOG2E M_LOG10E M_LN2 M_LN10 M_PI M_PI_2 M_PI_4
+	syn keyword cConstant M_1_PI M_2_PI M_2_SQRTPI M_SQRT2 M_SQRT1_2
 endif
 if !exists("c_no_c99") " ISO C99
-  syn keyword cConstant true false __bool_true_false_are_defined
+	syn keyword cConstant true false __bool_true_false_are_defined
 endif
 
@@ -1126,163 +1148,163 @@
 syn match	cPreCondit	display "^\s*\(%:\|#\)\s*\(else\|endif\)\>"
 if !exists("c_no_if0")
-  syn region	cCppOut		start="^\s*\(%:\|#\)\s*if\s\+0\+\>" end=".\@=\|$" contains=cCppOut2
-  syn region	cCppOut2	contained start="0" end="^\s*\(%:\|#\)\s*\(endif\>\|else\>\|elif\>\)" contains=cSpaceError,cCppSkip
-  syn region	cCppSkip	contained start="^\s*\(%:\|#\)\s*\(if\>\|ifdef\>\|ifndef\>\)" skip="\\$" end="^\s*\(%:\|#\)\s*endif\>" contains=cSpaceError,cCppSkip
-endif
-syn region	cIncluded	display contained start=+"+ skip=+\\\\\|\\"+ end=+"+
-syn match	cIncluded	display contained "<[^>]*>"
-syn match	cInclude	display "^\s*\(%:\|#\)\s*include\>\s*["<]" contains=cIncluded
-syn match cLineSkip	"\\$"
-syn cluster	cPreProcGroup	contains=cPreConditIf,cPreCondit,cIncluded,cInclude,cDefined,cDefine,cErrInParen,cErrInBracket,cUserLabel,cUserLabel2,cGotoLabel,cSpecial,cOctalZero,cCppOut,cCppOut2,cCppSkip,cFormat,cNumber,cFloat,cOctal,cOctalError,cNumbersCom,cString,cCommentSkip,cCommentString,cComment2String,@cCommentGroup,cCommentStartError,cParen,cBracket,cMulti
-"syn region	cDefine		start="^\s*\(%:\|#\)\s*\(define\|undef\)\>" skip="\\$" end="$" end="//"me=s-1 contains=ALLBUT,@cPreProcGroup,@Spell
-syn region	cDefine		start="^\s*\(%:\|#\)\s*\(define\|undef\)\>" skip="\\$" end="$" end="//"me=s-1 contains=ALLBUT,@cPreProcGroup,cName,cFunction,cAnsiFunction,@Spell
-syn region	cPreProc	start="^\s*\(%:\|#\)\s*\(pragma\>\|line\>\|warning\>\|warn\>\|error\>\)" skip="\\$" end="$" keepend contains=ALLBUT,@cPreProcGroup,@Spell
-
-" Highlight User Labels
-syn cluster	cMultiGroup	contains=cIncluded,cSpecial,cCommentSkip,cCommentString,cComment2String,@cCommentGroup,cCommentStartError,cUserCont,cUserLabel,cUserLabel2,cGotoLabel,cBitField,cOctalZero,cCppOut,cCppOut2,cCppSkip,cFormat,cNumber,cFloat,cOctal,cOctalError,cNumbersCom,cCppParen,cCppBracket,cCppString
-syn region	cMulti		transparent start='?' skip='::' end=':' contains=ALLBUT,@cMultiGroup,@Spell
-" Avoid matching foo::bar() in C++ by requiring that the next char is not ':'
-syn cluster	cLabelGroup	contains=cUserLabel
-syn match	cUserCont	display "^\s*\I\i*\s*:$" contains=@cLabelGroup
-syn match	cUserCont	display ";\s*\I\i*\s*:$" contains=@cLabelGroup
-syn match	cUserCont	display "^\s*\I\i*\s*:[^:]"me=e-1 contains=@cLabelGroup
-syn match	cUserCont	display ";\s*\I\i*\s*:[^:]"me=e-1 contains=@cLabelGroup
-
-syn match	cUserLabel	display "\I\i*" contained
-syn match	cUserLabel2	display "\I\i*:;\+"me=e-2
-syn match	cGotoLabel	display "\<goto\s\+\I\i*;"me=e-1,hs=s+5 contains=cGoto
-syn keyword	cGoto		contained goto
-
-" Avoid recognizing most bitfields as labels
-syn match	cBitField	display "^\s*\I\i*\s*:\s*[1-9]"me=e-1
-syn match	cBitField	display ";\s*\I\i*\s*:\s*[1-9]"me=e-1
-
-syn match cOperator	"\(<<\|>>\|[-+*/%&^|<>!=]\)="
-syn match cOperator	"<<\|>>\|&&\|||\|++\|--\|->"
-syn match cOperator	"[.!~*&%<>^|=+-]"
-syn match cOperator	"/[^/*=]"me=e-1
-syn match cOperator	"/$"
-syn match cOperator	"[\\]"
-syn match cOperator	"&&\|||"
-syn match cSpecialCharacter	"[,;]"
-syn match cDelimiter    "[][(){}]"
-syn keyword	cType		CHAR byte BYTE uchar ushort uint ulong
-syn keyword	cType		WORD DWORD QWORD INT INT2 INT4 UNS UNS2 UNS4 INT8 UNS8
-syn keyword	cType		CFG_t cfap_t cBYTE cvoid
-syn keyword	cType		_Bool _Complex _Imaginary __int64
-if !exists("c_no_ansi") || exists("c_ansi_typedefs")
-  syn keyword   cMC	__near __far FAR __io __direct DIR
-endif
-
-if exists("c_minlines")
-  let b:c_minlines = c_minlines
-else
-  if !exists("c_no_if0")
-    let b:c_minlines = 50	" #if 0 constructs can be long
-  else
-    let b:c_minlines = 15	" mostly for () constructs
-  endif
-endif
-exec "syn sync ccomment cComment minlines=" . b:c_minlines
-
-" Define the default highlighting.
-" For version 5.7 and earlier: only when not done already
-" For version 5.8 and later: only when an item doesn't have highlighting yet
-if version >= 508 || !exists("did_c_syn_inits")
-  if version < 508
-    let did_c_syn_inits = 1
-    command -nargs=+ HiLink hi link <args>
-  else
-    command -nargs=+ HiLink hi def link <args>
-  endif
-
-  HiLink cFormat	cSpecial
-  HiLink cCppString	cString
-  HiLink cCommentL	cComment
-  HiLink cCommentStart	cComment
-  HiLink cLabel		Label
-" HiLink cUserLabel	Label
-  HiLink cUserLabel	UserLabel2
-  HiLink cUserLabel2	UserLabel2
-  HiLink cGotoLabel	UserLabel2
-  HiLink cGoto		Statement
-  HiLink cConditional	Conditional
-  HiLink cRepeat	Repeat
-  HiLink cCharacter	Character
-  HiLink cSpecialCharacter cSpecial
-  HiLink cNumber	Number
-  HiLink cOctal		Number
-  HiLink cOctalZero	PreProc		" link this to Error if you want
-  HiLink cFloat		Float
-  HiLink cOctalError	cError
-  HiLink cParenError	cError
-  HiLink cErrInParen	cError
-  HiLink cErrInBracket	cError
-  HiLink cCommentError	cError
-  HiLink cCommentStartError	cError
-  HiLink cSpaceError	cError
-  HiLink cSpecialError	cError
-  HiLink cOperator	Operator
-  HiLink cOperatorBold	OperatorBold
-  HiLink cStructure	Structure
-  HiLink cStorageClass	StorageClass
-  HiLink cInclude	Include
-  HiLink cPreProc	PreProc
-  HiLink cDefine	Macro
-  HiLink cDefined	PreCondit
-  HiLink cIncluded	cString
-  HiLink cError		Error
-  HiLink cStatement	Statement
-  HiLink cPreCondit	PreCondit
-  HiLink cPreConditIf	PreCondit
-  HiLink cType		Type
-  HiLink cConstant	Constant
-  HiLink cCommentString cString
-  HiLink cComment2String cString
-  HiLink cCommentSkip	cComment
-  HiLink cString	String
-  HiLink cComment	Comment
-  HiLink cDelimiter     Delimiter
-  HiLink cSpecial	SpecialChar
-  HiLink cTodo		Todo
-  HiLink cCppSkip	cCppOut
-  HiLink cCppOut2	cCppOut
-  HiLink cCppOut	Comment
-  HiLink cMulti		Operator
-  HiLink cMultiMG	Operator
-  HiLink cFunction	Function
-  HiLink cAnsiFunction	StdFunction
-  HiLink cName		Name
-  HiLink cBitField	Name
-  HiLink cAnsiName	StdName
-  "HiLink cBlock	BlockBraces
-  HiLink cBraces	BlockBraces
-  "HiLink cBraceError	Error
-  HiLink cMC		MicroController
-  HiLink cAnsiFuncPtr	AnsiFuncPtr
-
-  hi Function		gui=NONE guifg=#e86f00
-  "hi StdFunction	gui=bold guifg=#ee0040
-  hi StdFunction	gui=bold guifg=#e86f00
-  hi Statement		gui=bold guifg=#a06129
-  hi UserLabel2		gui=bold guifg=#c96129
-  hi Operator		gui=NONE guifg=#000000
-  hi OperatorBold	gui=bold guifg=#000000
-  hi StdName		gui=bold guifg=#5276e6
-  hi Name		gui=NONE guifg=#5276e6
-  hi BlockBraces	gui=bold guifg=#000000
-  hi Special		gui=NONE guifg=#a000a0
-  hi Comment		gui=NONE guifg=grey62
-  hi MicroController	gui=bold guifg=#d00000
-  hi AnsiFuncPtr	gui=NONE guifg=#ff0000
-" hi PreProc        	gui=NONE guifg=#6a5acd
-  hi PreCondit      	gui=NONE guifg=#6a5acd
-" hi Macro          	gui=NONE guifg=#0000ff
-
-  delcommand HiLink
-endif
-hi Normal		gui=NONE guifg=#000000 guibg=Ivory1
-
-let b:current_syntax = "c"
-
-" vim: ts=8
+	syn region	cCppOut		start="^\s*\(%:\|#\)\s*if\s\+0\+\>" end=".\@=\|$" contains=cCppOut2
+	syn region	cCppOut2	contained start="0" end="^\s*\(%:\|#\)\s*\(endif\>\|else\>\|elif\>\)" contains=cSpaceError,cCppSkip
+		syn region	cCppSkip	contained start="^\s*\(%:\|#\)\s*\(if\>\|ifdef\>\|ifndef\>\)" skip="\\$" end="^\s*\(%:\|#\)\s*endif\>" contains=cSpaceError,cCppSkip
+	endif
+	syn region	cIncluded	display contained start=+"+ skip=+\\\\\|\\"+ end=+"+
+	syn match	cIncluded	display contained "<[^>]*>"
+	syn match	cInclude	display "^\s*\(%:\|#\)\s*include\>\s*["<]" contains=cIncluded
+	syn match cLineSkip	"\\$"
+	syn cluster	cPreProcGroup	contains=cPreConditIf,cPreCondit,cIncluded,cInclude,cDefined,cDefine,cErrInParen,cErrInBracket,cUserLabel,cUserLabel2,cGotoLabel,cSpecial,cOctalZero,cCppOut,cCppOut2,cCppSkip,cFormat,cNumber,cFloat,cOctal,cOctalError,cNumbersCom,cString,cCommentSkip,cCommentString,cComment2String,@cCommentGroup,cCommentStartError,cParen,cBracket,cMulti
+	"syn region	cDefine		start="^\s*\(%:\|#\)\s*\(define\|undef\)\>" skip="\\$" end="$" end="//"me=s-1 contains=ALLBUT,@cPreProcGroup,@Spell
+	syn region	cDefine		start="^\s*\(%:\|#\)\s*\(define\|undef\)\>" skip="\\$" end="$" end="//"me=s-1 contains=ALLBUT,@cPreProcGroup,cName,cFunction,cAnsiFunction,@Spell
+	syn region	cPreProc	start="^\s*\(%:\|#\)\s*\(pragma\>\|line\>\|warning\>\|warn\>\|error\>\)" skip="\\$" end="$" keepend contains=ALLBUT,@cPreProcGroup,@Spell
+
+	" Highlight User Labels
+	syn cluster	cMultiGroup	contains=cIncluded,cSpecial,cCommentSkip,cCommentString,cComment2String,@cCommentGroup,cCommentStartError,cUserCont,cUserLabel,cUserLabel2,cGotoLabel,cBitField,cOctalZero,cCppOut,cCppOut2,cCppSkip,cFormat,cNumber,cFloat,cOctal,cOctalError,cNumbersCom,cCppParen,cCppBracket,cCppString
+	syn region	cMulti		transparent start='?' skip='::' end=':' contains=ALLBUT,@cMultiGroup,@Spell
+	" Avoid matching foo::bar() in C++ by requiring that the next char is not ':'
+	syn cluster	cLabelGroup	contains=cUserLabel
+	syn match	cUserCont	display "^\s*\I\i*\s*:$" contains=@cLabelGroup
+	syn match	cUserCont	display ";\s*\I\i*\s*:$" contains=@cLabelGroup
+	syn match	cUserCont	display "^\s*\I\i*\s*:[^:]"me=e-1 contains=@cLabelGroup
+	syn match	cUserCont	display ";\s*\I\i*\s*:[^:]"me=e-1 contains=@cLabelGroup
+
+	syn match	cUserLabel	display "\I\i*" contained
+	syn match	cUserLabel2	display "\I\i*:;\+"me=e-2
+	syn match	cGotoLabel	display "\<goto\s\+\I\i*;"me=e-1,hs=s+5 contains=cGoto
+	syn keyword	cGoto		contained goto
+
+	" Avoid recognizing most bitfields as labels
+	syn match	cBitField	display "^\s*\I\i*\s*:\s*[1-9]"me=e-1
+	syn match	cBitField	display ";\s*\I\i*\s*:\s*[1-9]"me=e-1
+
+	syn match cOperator	"\(<<\|>>\|[-+*/%&^|<>!=]\)="
+	syn match cOperator	"<<\|>>\|&&\|||\|++\|--\|->"
+	syn match cOperator	"[.!~*&%<>^|=+-]"
+	syn match cOperator	"/[^/*=]"me=e-1
+	syn match cOperator	"/$"
+	syn match cOperator	"[\\]"
+	syn match cOperator	"&&\|||"
+	syn match cSpecialCharacter	"[,;]"
+	syn match cDelimiter    "[][(){}]"
+	syn keyword	cType		CHAR byte BYTE uchar ushort uint ulong
+	syn keyword	cType		WORD DWORD QWORD INT INT2 INT4 UNS UNS2 UNS4 INT8 UNS8
+	syn keyword	cType		CFG_t cfap_t cBYTE cvoid
+	syn keyword	cType		_Bool _Complex _Imaginary __int64
+	if !exists("c_no_ansi") || exists("c_ansi_typedefs")
+		syn keyword   cMC	__near __far FAR __io __direct DIR
+	endif
+
+	if exists("c_minlines")
+		let b:c_minlines = c_minlines
+	else
+		if !exists("c_no_if0")
+			let b:c_minlines = 50	" #if 0 constructs can be long
+		else
+			let b:c_minlines = 15	" mostly for () constructs
+		endif
+	endif
+	exec "syn sync ccomment cComment minlines=" . b:c_minlines
+
+	" Define the default highlighting.
+	" For version 5.7 and earlier: only when not done already
+	" For version 5.8 and later: only when an item doesn't have highlighting yet
+	if version >= 508 || !exists("did_c_syn_inits")
+		if version < 508
+			let did_c_syn_inits = 1
+			command -nargs=+ HiLink hi link <args>
+		else
+			command -nargs=+ HiLink hi def link <args>
+		endif
+
+		HiLink cFormat	cSpecial
+		HiLink cCppString	cString
+		HiLink cCommentL	cComment
+		HiLink cCommentStart	cComment
+		HiLink cLabel		Label
+		" HiLink cUserLabel	Label
+		HiLink cUserLabel	UserLabel2
+		HiLink cUserLabel2	UserLabel2
+		HiLink cGotoLabel	UserLabel2
+		HiLink cGoto		Statement
+		HiLink cConditional	Conditional
+		HiLink cRepeat	Repeat
+		HiLink cCharacter	Character
+		HiLink cSpecialCharacter cSpecial
+		HiLink cNumber	Number
+		HiLink cOctal		Number
+		HiLink cOctalZero	PreProc		" link this to Error if you want
+		HiLink cFloat		Float
+		HiLink cOctalError	cError
+		HiLink cParenError	cError
+		HiLink cErrInParen	cError
+		HiLink cErrInBracket	cError
+		HiLink cCommentError	cError
+		HiLink cCommentStartError	cError
+		HiLink cSpaceError	cError
+		HiLink cSpecialError	cError
+		HiLink cOperator	Operator
+		HiLink cOperatorBold	OperatorBold
+		HiLink cStructure	Structure
+		HiLink cStorageClass	StorageClass
+		HiLink cInclude	Include
+		HiLink cPreProc	PreProc
+		HiLink cDefine	Macro
+		HiLink cDefined	PreCondit
+		HiLink cIncluded	cString
+		HiLink cError		Error
+		HiLink cStatement	Statement
+		HiLink cPreCondit	PreCondit
+		HiLink cPreConditIf	PreCondit
+		HiLink cType		Type
+		HiLink cConstant	Constant
+		HiLink cCommentString cString
+		HiLink cComment2String cString
+		HiLink cCommentSkip	cComment
+		HiLink cString	String
+		HiLink cComment	Comment
+		HiLink cDelimiter     Delimiter
+		HiLink cSpecial	SpecialChar
+		HiLink cTodo		Todo
+		HiLink cCppSkip	cCppOut
+		HiLink cCppOut2	cCppOut
+		HiLink cCppOut	Comment
+		HiLink cMulti		Operator
+		HiLink cMultiMG	Operator
+		HiLink cFunction	Function
+		HiLink cAnsiFunction	StdFunction
+		HiLink cName		Name
+		HiLink cBitField	Name
+		HiLink cAnsiName	StdName
+		"HiLink cBlock	BlockBraces
+		HiLink cBraces	BlockBraces
+		"HiLink cBraceError	Error
+		HiLink cMC		MicroController
+		HiLink cAnsiFuncPtr	AnsiFuncPtr
+
+		hi Function		gui=NONE guifg=#e86f00
+		"hi StdFunction	gui=bold guifg=#ee0040
+		hi StdFunction	gui=bold guifg=#e86f00
+		hi Statement		gui=bold guifg=#a06129
+		hi UserLabel2		gui=bold guifg=#c96129
+		hi Operator		gui=NONE guifg=#000000
+		hi OperatorBold	gui=bold guifg=#000000
+		hi StdName		gui=bold guifg=#5276e6
+		hi Name		gui=NONE guifg=#5276e6
+		hi BlockBraces	gui=bold guifg=#000000
+		hi Special		gui=NONE guifg=#a000a0
+		hi Comment		gui=NONE guifg=grey62
+		hi MicroController	gui=bold guifg=#d00000
+		hi AnsiFuncPtr	gui=NONE guifg=#ff0000
+		" hi PreProc        	gui=NONE guifg=#6a5acd
+		hi PreCondit      	gui=NONE guifg=#6a5acd
+		" hi Macro          	gui=NONE guifg=#0000ff
+
+		delcommand HiLink
+	endif
+	hi Normal		gui=NONE guifg=#000000 guibg=Ivory1
+
+	let b:current_syntax = "c"
+
+	" vim: ts=8
Index: /issm/trunk/externalpackages/vim/addons/vimrc
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vimrc	(revision 13394)
+++ /issm/trunk/externalpackages/vim/addons/vimrc	(revision 13395)
@@ -99,4 +99,8 @@
 map <F8> :w <Enter> :make <Enter><Enter>
 map! <F8>  <ESC> :w <Enter> :make <Enter><Enter>
+" make update: nice for longer documents
+map <F7> :w <Enter> :make update <Enter><Enter>
+map! <F7> <ESC> :w <Enter> :make update <Enter><Enter>
+
 
 "use paste P: re-indent and re-format at the same time
@@ -190,36 +194,40 @@
 " Abbreviations {{{1
 " ----------------------------------------------------------------------
-func Eatchar(pat)
-	let c = nr2char(getchar())
-	return (c =~ a:pat) ? '' : c
-endfunc
-au BufRead,BufNewFile *.html     iabbr <silent> H1 <h1></h1><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.html     iabbr <silent> H2 <h2></h2><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.html     iabbr <silent> H3 <h3></h3><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.html     iabbr <silent> CO <code></code><Left><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.html     iabbr <silent> PP <p></p><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.m        iabbr <silent> p1  disp('');<Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.m        iab <expr> p0  "disp('-------------- file: ".expand('%')." line: ".line(".")."');"
-au BufRead,BufNewFile *.c*       iabbr <silent> p1  printf("\n");<Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.c*,*.h   iabbr <silent> ER  _error_("");<Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.c*       ab VV VecView(ug,PETSC_VIEWER_STDOUT_WORLD);
-au BufRead,BufNewFile *.c*       ab AS _assert_();
-au BufRead,BufNewFile *.c*       iab <expr> p0  "printf(\"-------------- file: ".expand('%')." line: %i\\n\",__LINE__);"
-au BufRead,BufNewFile *.c*       iab <expr> pp0 "PetscSynchronizedPrintf(MPI_COMM_WORLD,\"-------------- file: ".expand('%')." line: %i\\n\",__LINE__);\nPetscSynchronizedFlush(MPI_COMM_WORLD);"
-"tex
-au BufRead,BufNewFile *.tex iab EQ 
-			\\begin{equation}
-			\<CR>\end{equation}<up><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.tex iab IT 
-			\\begin{itemize}
-			\<CR>\item 
-			\<CR>\end{itemize}<up><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.tex iab EN 
-			\\begin{enumerate}
-			\<CR>\item 
-			\<CR>\end{enumerate}<up><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.tex ab (()) \left( \right)
+"func Eatchar(pat)
+"	let c = nr2char(getchar())
+"	return (c =~ a:pat) ? '' : c
+"endfunc
+"au BufRead,BufNewFile *.html     iabbr <silent> H1 <h1></h1><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.html     iabbr <silent> H2 <h2></h2><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.html     iabbr <silent> H3 <h3></h3><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.html     iabbr <silent> CO <code></code><Left><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.html     iabbr <silent> PP <p></p><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.m        iabbr <silent> p1  disp('');<Left><Left><Left><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.m        iab <expr> p0  "disp('-------------- file: ".expand('%')." line: ".line(".")."');"
+"au BufRead,BufNewFile *.c*       iabbr <silent> p1  printf("\n");<Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.c*,*.h   iabbr <silent> ER  _error_("");<Left><Left><Left><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.c*       ab VV VecView(ug,PETSC_VIEWER_STDOUT_WORLD);
+"au BufRead,BufNewFile *.c*       ab AS _assert_();
+"au BufRead,BufNewFile *.c*       iab <expr> p0  "printf(\"-------------- file: ".expand('%')." line: %i\\n\",__LINE__);"
+"au BufRead,BufNewFile *.c*       iab <expr> pp0 "PetscSynchronizedPrintf(MPI_COMM_WORLD,\"-------------- file: ".expand('%')." line: %i\\n\",__LINE__);\nPetscSynchronizedFlush(MPI_COMM_WORLD);"
+""tex
+"au BufRead,BufNewFile *.tex iab EQ 
+"			\\begin{equation}
+"			\<CR>\end{equation}<up><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.tex iab IT 
+"			\\begin{itemize}
+"			\<CR>\item 
+"			\<CR>\end{itemize}<up><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.tex iab EN 
+"			\\begin{enumerate}
+"			\<CR>\item 
+"			\<CR>\end{enumerate}<up><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.tex ab (()) \left( \right)
 "}}}
 " Skeletons {{{1
 au BufNewFile letter.tex   0r ~/.vim/xtr/skeleton/letter.tex
 "}}}
+" Copy and Paste{{{
+"vmap <C-c> y:call system("pbcopy", getreg("\""))<CR>
+"nmap <C-v> :call setreg("\"",system("pbpaste"))<CR>p
+"}}}
Index: /issm/trunk/externalpackages/vim/install.sh
===================================================================
--- /issm/trunk/externalpackages/vim/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/vim/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/windows/install.sh
===================================================================
--- /issm/trunk/externalpackages/windows/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/windows/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Download from ISSM server
Index: /issm/trunk/externalpackages/xaifbooster/install.sh
===================================================================
--- /issm/trunk/externalpackages/xaifbooster/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/xaifbooster/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/externalpackages/xerces/install.sh
===================================================================
--- /issm/trunk/externalpackages/xerces/install.sh	(revision 13394)
+++ /issm/trunk/externalpackages/xerces/install.sh	(revision 13395)
@@ -1,3 +1,4 @@
 #!/bin/bash
+set -eu
 
 #Some cleanup
Index: /issm/trunk/ltmain.sh
===================================================================
--- /issm/trunk/ltmain.sh	(revision 13394)
+++ /issm/trunk/ltmain.sh	(revision 13395)
@@ -1,8 +1,8 @@
-# Generated from ltmain.m4sh.
-
-# ltmain.sh (GNU libtool) 2.2.6b
+
+# libtool (GNU libtool) 2.4.2
 # Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
 
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007 2008 Free Software Foundation, Inc.
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006,
+# 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
 # This is free software; see the source for copying conditions.  There is NO
 # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
@@ -33,27 +33,32 @@
 # Provide generalized library-building support services.
 #
-#     --config             show all configuration variables
-#     --debug              enable verbose shell tracing
-# -n, --dry-run            display commands without modifying any files
-#     --features           display basic configuration information and exit
-#     --mode=MODE          use operation mode MODE
-#     --preserve-dup-deps  don't remove duplicate dependency libraries
-#     --quiet, --silent    don't print informational messages
-#     --tag=TAG            use configuration variables from tag TAG
-# -v, --verbose            print informational messages (default)
-#     --version            print version information
-# -h, --help               print short or long help message
+#       --config             show all configuration variables
+#       --debug              enable verbose shell tracing
+#   -n, --dry-run            display commands without modifying any files
+#       --features           display basic configuration information and exit
+#       --mode=MODE          use operation mode MODE
+#       --preserve-dup-deps  don't remove duplicate dependency libraries
+#       --quiet, --silent    don't print informational messages
+#       --no-quiet, --no-silent
+#                            print informational messages (default)
+#       --no-warn            don't display warning messages
+#       --tag=TAG            use configuration variables from tag TAG
+#   -v, --verbose            print more informational messages than default
+#       --no-verbose         don't print the extra informational messages
+#       --version            print version information
+#   -h, --help, --help-all   print short, long, or detailed help message
 #
 # MODE must be one of the following:
 #
-#       clean              remove files from the build directory
-#       compile            compile a source file into a libtool object
-#       execute            automatically set library path, then run a program
-#       finish             complete the installation of libtool libraries
-#       install            install libraries or executables
-#       link               create a library or an executable
-#       uninstall          remove libraries from an installed directory
+#         clean              remove files from the build directory
+#         compile            compile a source file into a libtool object
+#         execute            automatically set library path, then run a program
+#         finish             complete the installation of libtool libraries
+#         install            install libraries or executables
+#         link               create a library or an executable
+#         uninstall          remove libraries from an installed directory
 #
-# MODE-ARGS vary depending on the MODE.
+# MODE-ARGS vary depending on the MODE.  When passed as first option,
+# `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that.
 # Try `$progname --help --mode=MODE' for a more detailed description of MODE.
 #
@@ -61,20 +66,22 @@
 # include the following information:
 #
-#       host-triplet:	$host
-#       shell:		$SHELL
-#       compiler:		$LTCC
-#       compiler flags:		$LTCFLAGS
-#       linker:		$LD (gnu? $with_gnu_ld)
-#       $progname:		(GNU libtool) 2.2.6b
-#       automake:		$automake_version
-#       autoconf:		$autoconf_version
+#         host-triplet:	$host
+#         shell:		$SHELL
+#         compiler:		$LTCC
+#         compiler flags:		$LTCFLAGS
+#         linker:		$LD (gnu? $with_gnu_ld)
+#         $progname:	(GNU libtool) 2.4.2
+#         automake:	$automake_version
+#         autoconf:	$autoconf_version
 #
 # Report bugs to <bug-libtool@gnu.org>.
-
-PROGRAM=ltmain.sh
+# GNU libtool home page: <http://www.gnu.org/software/libtool/>.
+# General help using GNU software: <http://www.gnu.org/gethelp/>.
+
+PROGRAM=libtool
 PACKAGE=libtool
-VERSION=2.2.6b
+VERSION=2.4.2
 TIMESTAMP=""
-package_revision=1.3017
+package_revision=1.3337
 
 # Be Bourne compatible
@@ -92,8 +99,13 @@
 DUALCASE=1; export DUALCASE # for MKS sh
 
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+$1
+_LTECHO_EOF'
+}
+
 # NLS nuisances: We save the old values to restore during execute mode.
-# Only set LANG and LC_ALL to C if already set.
-# These must not be set unconditionally because not all systems understand
-# e.g. LANG=C (notably SCO).
 lt_user_locale=
 lt_safe_locale=
@@ -108,22 +120,26 @@
 	fi"
 done
+LC_ALL=C
+LANGUAGE=C
+export LANGUAGE LC_ALL
 
 $lt_unset CDPATH
 
 
+# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
+# is ksh but when the shell is invoked as "sh" and the current value of
+# the _XPG environment variable is not equal to 1 (one), the special
+# positional parameter $0, within a function call, is the name of the
+# function.
+progpath="$0"
 
 
 
 : ${CP="cp -f"}
-: ${ECHO="echo"}
-: ${EGREP="/bin/grep -E"}
-: ${FGREP="/bin/grep -F"}
-: ${GREP="/bin/grep"}
-: ${LN_S="ln -s"}
+test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'}
 : ${MAKE="make"}
 : ${MKDIR="mkdir"}
 : ${MV="mv -f"}
 : ${RM="rm -f"}
-: ${SED="/bin/sed"}
 : ${SHELL="${CONFIG_SHELL-/bin/sh}"}
 : ${Xsed="$SED -e 1s/^X//"}
@@ -144,4 +160,25 @@
 dirname="s,/[^/]*$,,"
 basename="s,^.*/,,"
+
+# 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 ()
+{
+    func_dirname_result=`$ECHO "${1}" | $SED "$dirname"`
+    if test "X$func_dirname_result" = "X${1}"; then
+      func_dirname_result="${3}"
+    else
+      func_dirname_result="$func_dirname_result${2}"
+    fi
+} # func_dirname may be replaced by extended shell implementation
+
+
+# func_basename file
+func_basename ()
+{
+    func_basename_result=`$ECHO "${1}" | $SED "$basename"`
+} # func_basename may be replaced by extended shell implementation
+
 
 # func_dirname_and_basename file append nondir_replacement
@@ -159,31 +196,181 @@
 func_dirname_and_basename ()
 {
-  # 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}"
+    # Extract subdirectory from the argument.
+    func_dirname_result=`$ECHO "${1}" | $SED -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_result=`$ECHO "${1}" | $SED -e "$basename"`
+} # func_dirname_and_basename may be replaced by extended shell implementation
+
+
+# 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 "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
+      *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
+    esac
+} # func_stripname may be replaced by extended shell implementation
+
+
+# These SED scripts presuppose an absolute path with a trailing slash.
+pathcar='s,^/\([^/]*\).*$,\1,'
+pathcdr='s,^/[^/]*,,'
+removedotparts=':dotsl
+		s@/\./@/@g
+		t dotsl
+		s,/\.$,/,'
+collapseslashes='s@/\{1,\}@/@g'
+finalslash='s,/*$,/,'
+
+# func_normal_abspath PATH
+# Remove doubled-up and trailing slashes, "." path components,
+# and cancel out any ".." path components in PATH after making
+# it an absolute path.
+#             value returned in "$func_normal_abspath_result"
+func_normal_abspath ()
+{
+  # Start from root dir and reassemble the path.
+  func_normal_abspath_result=
+  func_normal_abspath_tpath=$1
+  func_normal_abspath_altnamespace=
+  case $func_normal_abspath_tpath in
+    "")
+      # Empty path, that just means $cwd.
+      func_stripname '' '/' "`pwd`"
+      func_normal_abspath_result=$func_stripname_result
+      return
+    ;;
+    # The next three entries are used to spot a run of precisely
+    # two leading slashes without using negated character classes;
+    # we take advantage of case's first-match behaviour.
+    ///*)
+      # Unusual form of absolute path, do nothing.
+    ;;
+    //*)
+      # Not necessarily an ordinary path; POSIX reserves leading '//'
+      # and for example Cygwin uses it to access remote file shares
+      # over CIFS/SMB, so we conserve a leading double slash if found.
+      func_normal_abspath_altnamespace=/
+    ;;
+    /*)
+      # Absolute path, do nothing.
+    ;;
+    *)
+      # Relative path, prepend $cwd.
+      func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath
+    ;;
+  esac
+  # Cancel out all the simple stuff to save iterations.  We also want
+  # the path to end with a slash for ease of parsing, so make sure
+  # there is one (and only one) here.
+  func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"`
+  while :; do
+    # Processed it all yet?
+    if test "$func_normal_abspath_tpath" = / ; then
+      # If we ascended to the root using ".." the result may be empty now.
+      if test -z "$func_normal_abspath_result" ; then
+        func_normal_abspath_result=/
+      fi
+      break
+    fi
+    func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$pathcar"`
+    func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$pathcdr"`
+    # Figure out what to do with it
+    case $func_normal_abspath_tcomponent in
+      "")
+        # Trailing empty path component, ignore it.
+      ;;
+      ..)
+        # Parent dir; strip last assembled component from result.
+        func_dirname "$func_normal_abspath_result"
+        func_normal_abspath_result=$func_dirname_result
+      ;;
+      *)
+        # Actual path component, append it.
+        func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent
+      ;;
+    esac
+  done
+  # Restore leading double-slash if one was found on entry.
+  func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result
+}
+
+# func_relative_path SRCDIR DSTDIR
+# generates a relative path from SRCDIR to DSTDIR, with a trailing
+# slash if non-empty, suitable for immediately appending a filename
+# without needing to append a separator.
+#             value returned in "$func_relative_path_result"
+func_relative_path ()
+{
+  func_relative_path_result=
+  func_normal_abspath "$1"
+  func_relative_path_tlibdir=$func_normal_abspath_result
+  func_normal_abspath "$2"
+  func_relative_path_tbindir=$func_normal_abspath_result
+
+  # Ascend the tree starting from libdir
+  while :; do
+    # check if we have found a prefix of bindir
+    case $func_relative_path_tbindir in
+      $func_relative_path_tlibdir)
+        # found an exact match
+        func_relative_path_tcancelled=
+        break
+        ;;
+      $func_relative_path_tlibdir*)
+        # found a matching prefix
+        func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir"
+        func_relative_path_tcancelled=$func_stripname_result
+        if test -z "$func_relative_path_result"; then
+          func_relative_path_result=.
+        fi
+        break
+        ;;
+      *)
+        func_dirname $func_relative_path_tlibdir
+        func_relative_path_tlibdir=${func_dirname_result}
+        if test "x$func_relative_path_tlibdir" = x ; then
+          # Have to descend all the way to the root!
+          func_relative_path_result=../$func_relative_path_result
+          func_relative_path_tcancelled=$func_relative_path_tbindir
+          break
+        fi
+        func_relative_path_result=../$func_relative_path_result
+        ;;
+    esac
+  done
+
+  # Now calculate path; take care to avoid doubling-up slashes.
+  func_stripname '' '/' "$func_relative_path_result"
+  func_relative_path_result=$func_stripname_result
+  func_stripname '/' '/' "$func_relative_path_tcancelled"
+  if test "x$func_stripname_result" != x ; then
+    func_relative_path_result=${func_relative_path_result}/${func_stripname_result}
   fi
-  func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"`
-}
-
-# Generated shell functions inserted here.
-
-# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
-# is ksh but when the shell is invoked as "sh" and the current value of
-# the _XPG environment variable is not equal to 1 (one), the special
-# positional parameter $0, within a function call, is the name of the
-# function.
-progpath="$0"
+
+  # Normalisation. If bindir is libdir, return empty string,
+  # else relative path ending with a slash; either way, target
+  # file name can be directly appended.
+  if test ! -z "$func_relative_path_result"; then
+    func_stripname './' '' "$func_relative_path_result/"
+    func_relative_path_result=$func_stripname_result
+  fi
+}
 
 # The name of this program:
-# In the unlikely event $progname began with a '-', it would play havoc with
-# func_echo (imagine progname=-n), so we prepend ./ in that case:
 func_dirname_and_basename "$progpath"
 progname=$func_basename_result
-case $progname in
-  -*) progname=./$progname ;;
-esac
 
 # Make sure we have an absolute path for reexecution:
@@ -197,5 +384,5 @@
   *)
      save_IFS="$IFS"
-     IFS=:
+     IFS=${PATH_SEPARATOR-:}
      for progdir in $PATH; do
        IFS="$save_IFS"
@@ -215,4 +402,13 @@
 # Same as above, but do not quote variable references.
 double_quote_subst='s/\(["`\\]\)/\\\1/g'
+
+# Sed substitution that turns a string into a regex matching for the
+# string literally.
+sed_make_literal_regex='s,[].[^$\\*\/],\\&,g'
+
+# Sed substitution that converts a w32 file name or path
+# which contains forward slashes, into one that contains
+# (escaped) backslashes.  A very naive implementation.
+lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
 
 # Re-`\' parameter expansions in output of double_quote_subst that were
@@ -244,5 +440,5 @@
 func_echo ()
 {
-    $ECHO "$progname${mode+: }$mode: $*"
+    $ECHO "$progname: ${opt_mode+$opt_mode: }$*"
 }
 
@@ -259,9 +455,16 @@
 }
 
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO "$*"
+}
+
 # func_error arg...
 # Echo program name prefixed message to standard error.
 func_error ()
 {
-    $ECHO "$progname${mode+: }$mode: "${1+"$@"} 1>&2
+    $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2
 }
 
@@ -270,5 +473,5 @@
 func_warning ()
 {
-    $opt_warning && $ECHO "$progname${mode+: }$mode: warning: "${1+"$@"} 1>&2
+    $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2
 
     # bash bug again:
@@ -327,7 +530,7 @@
 
         # ...otherwise throw away the child directory and loop
-        my_directory_path=`$ECHO "X$my_directory_path" | $Xsed -e "$dirname"`
+        my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"`
       done
-      my_dir_list=`$ECHO "X$my_dir_list" | $Xsed -e 's,:*$,,'`
+      my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'`
 
       save_mkdir_p_IFS="$IFS"; IFS=':'
@@ -379,5 +582,5 @@
     fi
 
-    $ECHO "X$my_tmpdir" | $Xsed
+    $ECHO "$my_tmpdir"
 }
 
@@ -393,5 +596,5 @@
     case $1 in
       *[\\\`\"\$]*)
-	func_quote_for_eval_unquoted_result=`$ECHO "X$1" | $Xsed -e "$sed_quote_subst"` ;;
+	func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;;
       *)
         func_quote_for_eval_unquoted_result="$1" ;;
@@ -420,5 +623,5 @@
     case $1 in
       *[\\\`\"]*)
-	my_arg=`$ECHO "X$1" | $Xsed \
+	my_arg=`$ECHO "$1" | $SED \
 	    -e "$double_quote_subst" -e "$sed_double_backslash"` ;;
       *)
@@ -489,6 +692,20 @@
 }
 
-
-
+# func_tr_sh
+# Turn $1 into a string suitable for a shell variable name.
+# Result is stored in $func_tr_sh_result.  All characters
+# not in the set a-zA-Z0-9_ are replaced with '_'. Further,
+# if $1 begins with a digit, a '_' is prepended as well.
+func_tr_sh ()
+{
+  case $1 in
+  [0-9]* | *[!a-zA-Z0-9_]*)
+    func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'`
+    ;;
+  * )
+    func_tr_sh_result=$1
+    ;;
+  esac
+}
 
 
@@ -497,5 +714,15 @@
 func_version ()
 {
-    $SED -n '/^# '$PROGRAM' (GNU /,/# warranty; / {
+    $opt_debug
+
+    $SED -n '/(C)/!b go
+	:more
+	/\./!{
+	  N
+	  s/\n# / /
+	  b more
+	}
+	:go
+	/^# '$PROGRAM' (GNU /,/# warranty; / {
         s/^# //
 	s/^# *$//
@@ -510,5 +737,7 @@
 func_usage ()
 {
-    $SED -n '/^# Usage:/,/# -h/ {
+    $opt_debug
+
+    $SED -n '/^# Usage:/,/^#  *.*--help/ {
         s/^# //
 	s/^# *$//
@@ -516,14 +745,18 @@
 	p
     }' < "$progpath"
-    $ECHO
+    echo
     $ECHO "run \`$progname --help | more' for full usage"
     exit $?
 }
 
-# func_help
-# Echo long help message to standard output and exit.
+# func_help [NOEXIT]
+# Echo long help message to standard output and exit,
+# unless 'noexit' is passed as argument.
 func_help ()
 {
+    $opt_debug
+
     $SED -n '/^# Usage:/,/# Report bugs to/ {
+	:print
         s/^# //
 	s/^# *$//
@@ -535,9 +768,16 @@
 	s*\$LD*'"$LD"'*
 	s/\$with_gnu_ld/'"$with_gnu_ld"'/
-	s/\$automake_version/'"`(automake --version) 2>/dev/null |$SED 1q`"'/
-	s/\$autoconf_version/'"`(autoconf --version) 2>/dev/null |$SED 1q`"'/
+	s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/
+	s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/
 	p
-     }' < "$progpath"
-    exit $?
+	d
+     }
+     /^# .* home page:/b print
+     /^# General help using/b print
+     ' < "$progpath"
+    ret=$?
+    if test -z "$1"; then
+      exit $ret
+    fi
 }
 
@@ -547,8 +787,36 @@
 func_missing_arg ()
 {
-    func_error "missing argument for $1"
+    $opt_debug
+
+    func_error "missing argument for $1."
     exit_cmd=exit
 }
 
+
+# func_split_short_opt shortopt
+# Set func_split_short_opt_name and func_split_short_opt_arg shell
+# variables after splitting SHORTOPT after the 2nd character.
+func_split_short_opt ()
+{
+    my_sed_short_opt='1s/^\(..\).*$/\1/;q'
+    my_sed_short_rest='1s/^..\(.*\)$/\1/;q'
+
+    func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"`
+    func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"`
+} # func_split_short_opt may be replaced by extended shell implementation
+
+
+# func_split_long_opt longopt
+# Set func_split_long_opt_name and func_split_long_opt_arg shell
+# variables after splitting LONGOPT at the `=' sign.
+func_split_long_opt ()
+{
+    my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q'
+    my_sed_long_arg='1s/^--[^=]*=//'
+
+    func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"`
+    func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"`
+} # func_split_long_opt may be replaced by extended shell implementation
+
 exit_cmd=:
 
@@ -556,28 +824,4 @@
 
 
-
-# Check that we have a working $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, and then maybe $ECHO will work.
-  exec $SHELL "$progpath" --no-reexec ${1+"$@"}
-fi
-
-if test "X$1" = X--fallback-echo; then
-  # used as fallback echo
-  shift
-  cat <<EOF
-$*
-EOF
-  exit $EXIT_SUCCESS
-fi
 
 magic="%%%MAGIC variable%%%"
@@ -585,7 +829,5 @@
 
 # Global variables.
-# $mode is unset
 nonopt=
-execute_dlfiles=
 preserve_args=
 lo2o="s/\\.lo\$/.${objext}/"
@@ -594,9 +836,4 @@
 extracted_serial=0
 
-opt_dry_run=false
-opt_duplicate_deps=false
-opt_silent=false
-opt_debug=:
-
 # If this variable is set in any of the actions, the command in it
 # will be execed at the end.  This prevents here-documents from being
@@ -604,4 +841,50 @@
 exec_cmd=
 
+# func_append var value
+# Append VALUE to the end of shell variable VAR.
+func_append ()
+{
+    eval "${1}=\$${1}\${2}"
+} # func_append may be replaced by extended shell implementation
+
+# func_append_quoted var value
+# Quote VALUE and append to the end of shell variable VAR, separated
+# by a space.
+func_append_quoted ()
+{
+    func_quote_for_eval "${2}"
+    eval "${1}=\$${1}\\ \$func_quote_for_eval_result"
+} # func_append_quoted may be replaced by extended shell implementation
+
+
+# func_arith arithmetic-term...
+func_arith ()
+{
+    func_arith_result=`expr "${@}"`
+} # func_arith may be replaced by extended shell implementation
+
+
+# func_len string
+# STRING may not start with a hyphen.
+func_len ()
+{
+    func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len`
+} # func_len may be replaced by extended shell implementation
+
+
+# func_lo2o object
+func_lo2o ()
+{
+    func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"`
+} # func_lo2o may be replaced by extended shell implementation
+
+
+# func_xform libobj-or-source
+func_xform ()
+{
+    func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'`
+} # func_xform may be replaced by extended shell implementation
+
+
 # func_fatal_configuration arg...
 # Echo program name prefixed message to standard error, followed by
@@ -637,14 +920,14 @@
 func_features ()
 {
-    $ECHO "host: $host"
+    echo "host: $host"
     if test "$build_libtool_libs" = yes; then
-      $ECHO "enable shared libraries"
+      echo "enable shared libraries"
     else
-      $ECHO "disable shared libraries"
+      echo "disable shared libraries"
     fi
     if test "$build_old_libs" = yes; then
-      $ECHO "enable static libraries"
+      echo "enable static libraries"
     else
-      $ECHO "disable static libraries"
+      echo "disable static libraries"
     fi
 
@@ -691,131 +974,4 @@
       ;;
   esac
-}
-
-# Parse options once, thoroughly.  This comes as soon as possible in
-# the script to make things like `libtool --version' happen quickly.
-{
-
-  # Shorthand for --mode=foo, only valid as the first argument
-  case $1 in
-  clean|clea|cle|cl)
-    shift; set dummy --mode clean ${1+"$@"}; shift
-    ;;
-  compile|compil|compi|comp|com|co|c)
-    shift; set dummy --mode compile ${1+"$@"}; shift
-    ;;
-  execute|execut|execu|exec|exe|ex|e)
-    shift; set dummy --mode execute ${1+"$@"}; shift
-    ;;
-  finish|finis|fini|fin|fi|f)
-    shift; set dummy --mode finish ${1+"$@"}; shift
-    ;;
-  install|instal|insta|inst|ins|in|i)
-    shift; set dummy --mode install ${1+"$@"}; shift
-    ;;
-  link|lin|li|l)
-    shift; set dummy --mode link ${1+"$@"}; shift
-    ;;
-  uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
-    shift; set dummy --mode uninstall ${1+"$@"}; shift
-    ;;
-  esac
-
-  # Parse non-mode specific arguments:
-  while test "$#" -gt 0; do
-    opt="$1"
-    shift
-
-    case $opt in
-      --config)		func_config					;;
-
-      --debug)		preserve_args="$preserve_args $opt"
-			func_echo "enabling shell trace mode"
-			opt_debug='set -x'
-			$opt_debug
-			;;
-
-      -dlopen)		test "$#" -eq 0 && func_missing_arg "$opt" && break
-			execute_dlfiles="$execute_dlfiles $1"
-			shift
-			;;
-
-      --dry-run | -n)	opt_dry_run=:					;;
-      --features)       func_features					;;
-      --finish)		mode="finish"					;;
-
-      --mode)		test "$#" -eq 0 && func_missing_arg "$opt" && break
-			case $1 in
-			  # Valid mode arguments:
-			  clean)	;;
-			  compile)	;;
-			  execute)	;;
-			  finish)	;;
-			  install)	;;
-			  link)		;;
-			  relink)	;;
-			  uninstall)	;;
-
-			  # Catch anything else as an error
-			  *) func_error "invalid argument for $opt"
-			     exit_cmd=exit
-			     break
-			     ;;
-		        esac
-
-			mode="$1"
-			shift
-			;;
-
-      --preserve-dup-deps)
-			opt_duplicate_deps=:				;;
-
-      --quiet|--silent)	preserve_args="$preserve_args $opt"
-			opt_silent=:
-			;;
-
-      --verbose| -v)	preserve_args="$preserve_args $opt"
-			opt_silent=false
-			;;
-
-      --tag)		test "$#" -eq 0 && func_missing_arg "$opt" && break
-			preserve_args="$preserve_args $opt $1"
-			func_enable_tag "$1"	# tagname is set here
-			shift
-			;;
-
-      # Separate optargs to long options:
-      -dlopen=*|--mode=*|--tag=*)
-			func_opt_split "$opt"
-			set dummy "$func_opt_split_opt" "$func_opt_split_arg" ${1+"$@"}
-			shift
-			;;
-
-      -\?|-h)		func_usage					;;
-      --help)		opt_help=:					;;
-      --version)	func_version					;;
-
-      -*)		func_fatal_help "unrecognized option \`$opt'"	;;
-
-      *)		nonopt="$opt"
-			break
-			;;
-    esac
-  done
-
-
-  case $host in
-    *cygwin* | *mingw* | *pw32* | *cegcc*)
-      # don't eliminate duplications in $postdeps and $predeps
-      opt_duplicate_compiler_generated_deps=:
-      ;;
-    *)
-      opt_duplicate_compiler_generated_deps=$opt_duplicate_deps
-      ;;
-  esac
-
-  # Having warned about all mis-specified options, bail out if
-  # anything was wrong.
-  $exit_cmd $EXIT_FAILURE
 }
 
@@ -856,35 +1012,216 @@
 
 
+# Shorthand for --mode=foo, only valid as the first argument
+case $1 in
+clean|clea|cle|cl)
+  shift; set dummy --mode clean ${1+"$@"}; shift
+  ;;
+compile|compil|compi|comp|com|co|c)
+  shift; set dummy --mode compile ${1+"$@"}; shift
+  ;;
+execute|execut|execu|exec|exe|ex|e)
+  shift; set dummy --mode execute ${1+"$@"}; shift
+  ;;
+finish|finis|fini|fin|fi|f)
+  shift; set dummy --mode finish ${1+"$@"}; shift
+  ;;
+install|instal|insta|inst|ins|in|i)
+  shift; set dummy --mode install ${1+"$@"}; shift
+  ;;
+link|lin|li|l)
+  shift; set dummy --mode link ${1+"$@"}; shift
+  ;;
+uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
+  shift; set dummy --mode uninstall ${1+"$@"}; shift
+  ;;
+esac
+
+
+
+# Option defaults:
+opt_debug=:
+opt_dry_run=false
+opt_config=false
+opt_preserve_dup_deps=false
+opt_features=false
+opt_finish=false
+opt_help=false
+opt_help_all=false
+opt_silent=:
+opt_warning=:
+opt_verbose=:
+opt_silent=false
+opt_verbose=false
+
+
+# Parse options once, thoroughly.  This comes as soon as possible in the
+# script to make things like `--version' happen as quickly as we can.
+{
+  # this just eases exit handling
+  while test $# -gt 0; do
+    opt="$1"
+    shift
+    case $opt in
+      --debug|-x)	opt_debug='set -x'
+			func_echo "enabling shell trace mode"
+			$opt_debug
+			;;
+      --dry-run|--dryrun|-n)
+			opt_dry_run=:
+			;;
+      --config)
+			opt_config=:
+func_config
+			;;
+      --dlopen|-dlopen)
+			optarg="$1"
+			opt_dlopen="${opt_dlopen+$opt_dlopen
+}$optarg"
+			shift
+			;;
+      --preserve-dup-deps)
+			opt_preserve_dup_deps=:
+			;;
+      --features)
+			opt_features=:
+func_features
+			;;
+      --finish)
+			opt_finish=:
+set dummy --mode finish ${1+"$@"}; shift
+			;;
+      --help)
+			opt_help=:
+			;;
+      --help-all)
+			opt_help_all=:
+opt_help=': help-all'
+			;;
+      --mode)
+			test $# = 0 && func_missing_arg $opt && break
+			optarg="$1"
+			opt_mode="$optarg"
+case $optarg in
+  # Valid mode arguments:
+  clean|compile|execute|finish|install|link|relink|uninstall) ;;
+
+  # Catch anything else as an error
+  *) func_error "invalid argument for $opt"
+     exit_cmd=exit
+     break
+     ;;
+esac
+			shift
+			;;
+      --no-silent|--no-quiet)
+			opt_silent=false
+func_append preserve_args " $opt"
+			;;
+      --no-warning|--no-warn)
+			opt_warning=false
+func_append preserve_args " $opt"
+			;;
+      --no-verbose)
+			opt_verbose=false
+func_append preserve_args " $opt"
+			;;
+      --silent|--quiet)
+			opt_silent=:
+func_append preserve_args " $opt"
+        opt_verbose=false
+			;;
+      --verbose|-v)
+			opt_verbose=:
+func_append preserve_args " $opt"
+opt_silent=false
+			;;
+      --tag)
+			test $# = 0 && func_missing_arg $opt && break
+			optarg="$1"
+			opt_tag="$optarg"
+func_append preserve_args " $opt $optarg"
+func_enable_tag "$optarg"
+			shift
+			;;
+
+      -\?|-h)		func_usage				;;
+      --help)		func_help				;;
+      --version)	func_version				;;
+
+      # Separate optargs to long options:
+      --*=*)
+			func_split_long_opt "$opt"
+			set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"}
+			shift
+			;;
+
+      # Separate non-argument short options:
+      -\?*|-h*|-n*|-v*)
+			func_split_short_opt "$opt"
+			set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"}
+			shift
+			;;
+
+      --)		break					;;
+      -*)		func_fatal_help "unrecognized option \`$opt'" ;;
+      *)		set dummy "$opt" ${1+"$@"};	shift; break  ;;
+    esac
+  done
+
+  # Validate options:
+
+  # save first non-option argument
+  if test "$#" -gt 0; then
+    nonopt="$opt"
+    shift
+  fi
+
+  # preserve --debug
+  test "$opt_debug" = : || func_append preserve_args " --debug"
+
+  case $host in
+    *cygwin* | *mingw* | *pw32* | *cegcc*)
+      # don't eliminate duplications in $postdeps and $predeps
+      opt_duplicate_compiler_generated_deps=:
+      ;;
+    *)
+      opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps
+      ;;
+  esac
+
+  $opt_help || {
+    # Sanity checks first:
+    func_check_version_match
+
+    if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
+      func_fatal_configuration "not configured to build any kind of library"
+    fi
+
+    # Darwin sucks
+    eval std_shrext=\"$shrext_cmds\"
+
+    # Only execute mode is allowed to have -dlopen flags.
+    if test -n "$opt_dlopen" && test "$opt_mode" != execute; then
+      func_error "unrecognized option \`-dlopen'"
+      $ECHO "$help" 1>&2
+      exit $EXIT_FAILURE
+    fi
+
+    # Change the help message to a mode-specific one.
+    generic_help="$help"
+    help="Try \`$progname --help --mode=$opt_mode' for more information."
+  }
+
+
+  # Bail if the options were screwed
+  $exit_cmd $EXIT_FAILURE
+}
+
+
+
+
 ## ----------- ##
 ##    Main.    ##
 ## ----------- ##
-
-$opt_help || {
-  # Sanity checks first:
-  func_check_version_match
-
-  if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
-    func_fatal_configuration "not configured to build any kind of library"
-  fi
-
-  test -z "$mode" && func_fatal_error "error: you must specify a MODE."
-
-
-  # Darwin sucks
-  eval std_shrext=\"$shrext_cmds\"
-
-
-  # Only execute mode is allowed to have -dlopen flags.
-  if test -n "$execute_dlfiles" && test "$mode" != execute; then
-    func_error "unrecognized option \`-dlopen'"
-    $ECHO "$help" 1>&2
-    exit $EXIT_FAILURE
-  fi
-
-  # Change the help message to a mode-specific one.
-  generic_help="$help"
-  help="Try \`$progname --help --mode=$mode' for more information."
-}
-
 
 # func_lalib_p file
@@ -951,10 +1288,7 @@
 func_ltwrapper_scriptname ()
 {
-    func_ltwrapper_scriptname_result=""
-    if func_ltwrapper_executable_p "$1"; then
-	func_dirname_and_basename "$1" "" "."
-	func_stripname '' '.exe' "$func_basename_result"
-	func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper"
-    fi
+    func_dirname_and_basename "$1" "" "."
+    func_stripname '' '.exe' "$func_basename_result"
+    func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper"
 }
 
@@ -1002,4 +1336,35 @@
 
 
+# func_resolve_sysroot PATH
+# Replace a leading = in PATH with a sysroot.  Store the result into
+# func_resolve_sysroot_result
+func_resolve_sysroot ()
+{
+  func_resolve_sysroot_result=$1
+  case $func_resolve_sysroot_result in
+  =*)
+    func_stripname '=' '' "$func_resolve_sysroot_result"
+    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result
+    ;;
+  esac
+}
+
+# func_replace_sysroot PATH
+# If PATH begins with the sysroot, replace it with = and
+# store the result into func_replace_sysroot_result.
+func_replace_sysroot ()
+{
+  case "$lt_sysroot:$1" in
+  ?*:"$lt_sysroot"*)
+    func_stripname "$lt_sysroot" '' "$1"
+    func_replace_sysroot_result="=$func_stripname_result"
+    ;;
+  *)
+    # Including no sysroot.
+    func_replace_sysroot_result=$1
+    ;;
+  esac
+}
+
 # func_infer_tag arg
 # Infer tagged configuration to use if any are available and
@@ -1014,11 +1379,13 @@
       CC_quoted=
       for arg in $CC; do
-        func_quote_for_eval "$arg"
-	CC_quoted="$CC_quoted $func_quote_for_eval_result"
+	func_append_quoted CC_quoted "$arg"
       done
+      CC_expanded=`func_echo_all $CC`
+      CC_quoted_expanded=`func_echo_all $CC_quoted`
       case $@ in
       # Blanks in the command may have been stripped by the calling shell,
       # but not from the CC environment variable when configure was run.
-      " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) ;;
+      " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
+      " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;;
       # Blanks at the start of $base_compile will cause this to fail
       # if we don't check for them as well.
@@ -1031,9 +1398,11 @@
 	    for arg in $CC; do
 	      # Double-quote args containing other shell metacharacters.
-	      func_quote_for_eval "$arg"
-	      CC_quoted="$CC_quoted $func_quote_for_eval_result"
+	      func_append_quoted CC_quoted "$arg"
 	    done
+	    CC_expanded=`func_echo_all $CC`
+	    CC_quoted_expanded=`func_echo_all $CC_quoted`
 	    case "$@ " in
-	      " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*)
+	    " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
+	    " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*)
 	      # The compiler in the base compile command matches
 	      # the one in the tagged configuration.
@@ -1098,4 +1467,484 @@
 }
 
+
+##################################################
+# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #
+##################################################
+
+# func_convert_core_file_wine_to_w32 ARG
+# Helper function used by file name conversion functions when $build is *nix,
+# and $host is mingw, cygwin, or some other w32 environment. Relies on a
+# correctly configured wine environment available, with the winepath program
+# in $build's $PATH.
+#
+# ARG is the $build file name to be converted to w32 format.
+# Result is available in $func_convert_core_file_wine_to_w32_result, and will
+# be empty on error (or when ARG is empty)
+func_convert_core_file_wine_to_w32 ()
+{
+  $opt_debug
+  func_convert_core_file_wine_to_w32_result="$1"
+  if test -n "$1"; then
+    # Unfortunately, winepath does not exit with a non-zero error code, so we
+    # are forced to check the contents of stdout. On the other hand, if the
+    # command is not found, the shell will set an exit code of 127 and print
+    # *an error message* to stdout. So we must check for both error code of
+    # zero AND non-empty stdout, which explains the odd construction:
+    func_convert_core_file_wine_to_w32_tmp=`winepath -w "$1" 2>/dev/null`
+    if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then
+      func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" |
+        $SED -e "$lt_sed_naive_backslashify"`
+    else
+      func_convert_core_file_wine_to_w32_result=
+    fi
+  fi
+}
+# end: func_convert_core_file_wine_to_w32
+
+
+# func_convert_core_path_wine_to_w32 ARG
+# Helper function used by path conversion functions when $build is *nix, and
+# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly
+# configured wine environment available, with the winepath program in $build's
+# $PATH. Assumes ARG has no leading or trailing path separator characters.
+#
+# ARG is path to be converted from $build format to win32.
+# Result is available in $func_convert_core_path_wine_to_w32_result.
+# Unconvertible file (directory) names in ARG are skipped; if no directory names
+# are convertible, then the result may be empty.
+func_convert_core_path_wine_to_w32 ()
+{
+  $opt_debug
+  # unfortunately, winepath doesn't convert paths, only file names
+  func_convert_core_path_wine_to_w32_result=""
+  if test -n "$1"; then
+    oldIFS=$IFS
+    IFS=:
+    for func_convert_core_path_wine_to_w32_f in $1; do
+      IFS=$oldIFS
+      func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f"
+      if test -n "$func_convert_core_file_wine_to_w32_result" ; then
+        if test -z "$func_convert_core_path_wine_to_w32_result"; then
+          func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result"
+        else
+          func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result"
+        fi
+      fi
+    done
+    IFS=$oldIFS
+  fi
+}
+# end: func_convert_core_path_wine_to_w32
+
+
+# func_cygpath ARGS...
+# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when
+# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)
+# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or
+# (2), returns the Cygwin file name or path in func_cygpath_result (input
+# file name or path is assumed to be in w32 format, as previously converted
+# from $build's *nix or MSYS format). In case (3), returns the w32 file name
+# or path in func_cygpath_result (input file name or path is assumed to be in
+# Cygwin format). Returns an empty string on error.
+#
+# ARGS are passed to cygpath, with the last one being the file name or path to
+# be converted.
+#
+# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH
+# environment variable; do not put it in $PATH.
+func_cygpath ()
+{
+  $opt_debug
+  if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then
+    func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null`
+    if test "$?" -ne 0; then
+      # on failure, ensure result is empty
+      func_cygpath_result=
+    fi
+  else
+    func_cygpath_result=
+    func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'"
+  fi
+}
+#end: func_cygpath
+
+
+# func_convert_core_msys_to_w32 ARG
+# Convert file name or path ARG from MSYS format to w32 format.  Return
+# result in func_convert_core_msys_to_w32_result.
+func_convert_core_msys_to_w32 ()
+{
+  $opt_debug
+  # awkward: cmd appends spaces to result
+  func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null |
+    $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"`
+}
+#end: func_convert_core_msys_to_w32
+
+
+# func_convert_file_check ARG1 ARG2
+# Verify that ARG1 (a file name in $build format) was converted to $host
+# format in ARG2. Otherwise, emit an error message, but continue (resetting
+# func_to_host_file_result to ARG1).
+func_convert_file_check ()
+{
+  $opt_debug
+  if test -z "$2" && test -n "$1" ; then
+    func_error "Could not determine host file name corresponding to"
+    func_error "  \`$1'"
+    func_error "Continuing, but uninstalled executables may not work."
+    # Fallback:
+    func_to_host_file_result="$1"
+  fi
+}
+# end func_convert_file_check
+
+
+# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH
+# Verify that FROM_PATH (a path in $build format) was converted to $host
+# format in TO_PATH. Otherwise, emit an error message, but continue, resetting
+# func_to_host_file_result to a simplistic fallback value (see below).
+func_convert_path_check ()
+{
+  $opt_debug
+  if test -z "$4" && test -n "$3"; then
+    func_error "Could not determine the host path corresponding to"
+    func_error "  \`$3'"
+    func_error "Continuing, but uninstalled executables may not work."
+    # Fallback.  This is a deliberately simplistic "conversion" and
+    # should not be "improved".  See libtool.info.
+    if test "x$1" != "x$2"; then
+      lt_replace_pathsep_chars="s|$1|$2|g"
+      func_to_host_path_result=`echo "$3" |
+        $SED -e "$lt_replace_pathsep_chars"`
+    else
+      func_to_host_path_result="$3"
+    fi
+  fi
+}
+# end func_convert_path_check
+
+
+# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG
+# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT
+# and appending REPL if ORIG matches BACKPAT.
+func_convert_path_front_back_pathsep ()
+{
+  $opt_debug
+  case $4 in
+  $1 ) func_to_host_path_result="$3$func_to_host_path_result"
+    ;;
+  esac
+  case $4 in
+  $2 ) func_append func_to_host_path_result "$3"
+    ;;
+  esac
+}
+# end func_convert_path_front_back_pathsep
+
+
+##################################################
+# $build to $host FILE NAME CONVERSION FUNCTIONS #
+##################################################
+# invoked via `$to_host_file_cmd ARG'
+#
+# In each case, ARG is the path to be converted from $build to $host format.
+# Result will be available in $func_to_host_file_result.
+
+
+# func_to_host_file ARG
+# Converts the file name ARG from $build format to $host format. Return result
+# in func_to_host_file_result.
+func_to_host_file ()
+{
+  $opt_debug
+  $to_host_file_cmd "$1"
+}
+# end func_to_host_file
+
+
+# func_to_tool_file ARG LAZY
+# converts the file name ARG from $build format to toolchain format. Return
+# result in func_to_tool_file_result.  If the conversion in use is listed
+# in (the comma separated) LAZY, no conversion takes place.
+func_to_tool_file ()
+{
+  $opt_debug
+  case ,$2, in
+    *,"$to_tool_file_cmd",*)
+      func_to_tool_file_result=$1
+      ;;
+    *)
+      $to_tool_file_cmd "$1"
+      func_to_tool_file_result=$func_to_host_file_result
+      ;;
+  esac
+}
+# end func_to_tool_file
+
+
+# func_convert_file_noop ARG
+# Copy ARG to func_to_host_file_result.
+func_convert_file_noop ()
+{
+  func_to_host_file_result="$1"
+}
+# end func_convert_file_noop
+
+
+# func_convert_file_msys_to_w32 ARG
+# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic
+# conversion to w32 is not available inside the cwrapper.  Returns result in
+# func_to_host_file_result.
+func_convert_file_msys_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_msys_to_w32 "$1"
+    func_to_host_file_result="$func_convert_core_msys_to_w32_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_msys_to_w32
+
+
+# func_convert_file_cygwin_to_w32 ARG
+# Convert file name ARG from Cygwin to w32 format.  Returns result in
+# func_to_host_file_result.
+func_convert_file_cygwin_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    # because $build is cygwin, we call "the" cygpath in $PATH; no need to use
+    # LT_CYGPATH in this case.
+    func_to_host_file_result=`cygpath -m "$1"`
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_cygwin_to_w32
+
+
+# func_convert_file_nix_to_w32 ARG
+# Convert file name ARG from *nix to w32 format.  Requires a wine environment
+# and a working winepath. Returns result in func_to_host_file_result.
+func_convert_file_nix_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_file_wine_to_w32 "$1"
+    func_to_host_file_result="$func_convert_core_file_wine_to_w32_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_nix_to_w32
+
+
+# func_convert_file_msys_to_cygwin ARG
+# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
+# Returns result in func_to_host_file_result.
+func_convert_file_msys_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    func_convert_core_msys_to_w32 "$1"
+    func_cygpath -u "$func_convert_core_msys_to_w32_result"
+    func_to_host_file_result="$func_cygpath_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_msys_to_cygwin
+
+
+# func_convert_file_nix_to_cygwin ARG
+# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed
+# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result
+# in func_to_host_file_result.
+func_convert_file_nix_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_file_result="$1"
+  if test -n "$1"; then
+    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.
+    func_convert_core_file_wine_to_w32 "$1"
+    func_cygpath -u "$func_convert_core_file_wine_to_w32_result"
+    func_to_host_file_result="$func_cygpath_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_nix_to_cygwin
+
+
+#############################################
+# $build to $host PATH CONVERSION FUNCTIONS #
+#############################################
+# invoked via `$to_host_path_cmd ARG'
+#
+# In each case, ARG is the path to be converted from $build to $host format.
+# The result will be available in $func_to_host_path_result.
+#
+# Path separators are also converted from $build format to $host format.  If
+# ARG begins or ends with a path separator character, it is preserved (but
+# converted to $host format) on output.
+#
+# All path conversion functions are named using the following convention:
+#   file name conversion function    : func_convert_file_X_to_Y ()
+#   path conversion function         : func_convert_path_X_to_Y ()
+# where, for any given $build/$host combination the 'X_to_Y' value is the
+# same.  If conversion functions are added for new $build/$host combinations,
+# the two new functions must follow this pattern, or func_init_to_host_path_cmd
+# will break.
+
+
+# func_init_to_host_path_cmd
+# Ensures that function "pointer" variable $to_host_path_cmd is set to the
+# appropriate value, based on the value of $to_host_file_cmd.
+to_host_path_cmd=
+func_init_to_host_path_cmd ()
+{
+  $opt_debug
+  if test -z "$to_host_path_cmd"; then
+    func_stripname 'func_convert_file_' '' "$to_host_file_cmd"
+    to_host_path_cmd="func_convert_path_${func_stripname_result}"
+  fi
+}
+
+
+# func_to_host_path ARG
+# Converts the path ARG from $build format to $host format. Return result
+# in func_to_host_path_result.
+func_to_host_path ()
+{
+  $opt_debug
+  func_init_to_host_path_cmd
+  $to_host_path_cmd "$1"
+}
+# end func_to_host_path
+
+
+# func_convert_path_noop ARG
+# Copy ARG to func_to_host_path_result.
+func_convert_path_noop ()
+{
+  func_to_host_path_result="$1"
+}
+# end func_convert_path_noop
+
+
+# func_convert_path_msys_to_w32 ARG
+# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic
+# conversion to w32 is not available inside the cwrapper.  Returns result in
+# func_to_host_path_result.
+func_convert_path_msys_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # Remove leading and trailing path separator characters from ARG.  MSYS
+    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';
+    # and winepath ignores them completely.
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
+    func_to_host_path_result="$func_convert_core_msys_to_w32_result"
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_msys_to_w32
+
+
+# func_convert_path_cygwin_to_w32 ARG
+# Convert path ARG from Cygwin to w32 format.  Returns result in
+# func_to_host_file_result.
+func_convert_path_cygwin_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"`
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_cygwin_to_w32
+
+
+# func_convert_path_nix_to_w32 ARG
+# Convert path ARG from *nix to w32 format.  Requires a wine environment and
+# a working winepath.  Returns result in func_to_host_file_result.
+func_convert_path_nix_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
+    func_to_host_path_result="$func_convert_core_path_wine_to_w32_result"
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_nix_to_w32
+
+
+# func_convert_path_msys_to_cygwin ARG
+# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
+# Returns result in func_to_host_file_result.
+func_convert_path_msys_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
+    func_cygpath -u -p "$func_convert_core_msys_to_w32_result"
+    func_to_host_path_result="$func_cygpath_result"
+    func_convert_path_check : : \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
+  fi
+}
+# end func_convert_path_msys_to_cygwin
+
+
+# func_convert_path_nix_to_cygwin ARG
+# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a
+# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in
+# func_to_host_file_result.
+func_convert_path_nix_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_path_result="$1"
+  if test -n "$1"; then
+    # Remove leading and trailing path separator characters from
+    # ARG. msys behavior is inconsistent here, cygpath turns them
+    # into '.;' and ';.', and winepath ignores them completely.
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=$func_stripname_result
+    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
+    func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result"
+    func_to_host_path_result="$func_cygpath_result"
+    func_convert_path_check : : \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
+  fi
+}
+# end func_convert_path_nix_to_cygwin
+
+
 # func_mode_compile arg...
 func_mode_compile ()
@@ -1138,10 +1987,10 @@
 
 	-pie | -fpie | -fPIE)
-          pie_flag="$pie_flag $arg"
+          func_append pie_flag " $arg"
 	  continue
 	  ;;
 
 	-shared | -static | -prefer-pic | -prefer-non-pic)
-	  later="$later $arg"
+	  func_append later " $arg"
 	  continue
 	  ;;
@@ -1164,6 +2013,5 @@
 	  for arg in $args; do
 	    IFS="$save_ifs"
-	    func_quote_for_eval "$arg"
-	    lastarg="$lastarg $func_quote_for_eval_result"
+	    func_append_quoted lastarg "$arg"
 	  done
 	  IFS="$save_ifs"
@@ -1172,5 +2020,5 @@
 
 	  # Add the arguments to base_compile.
-	  base_compile="$base_compile $lastarg"
+	  func_append base_compile " $lastarg"
 	  continue
 	  ;;
@@ -1188,6 +2036,5 @@
 
       # Aesthetically quote the previous argument.
-      func_quote_for_eval "$lastarg"
-      base_compile="$base_compile $func_quote_for_eval_result"
+      func_append_quoted base_compile "$lastarg"
     done # for arg
 
@@ -1214,5 +2061,5 @@
     *.ada | *.adb | *.ads | *.asm | \
     *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \
-    *.[fF][09]? | *.for | *.java | *.obj | *.sx)
+    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)
       func_xform "$libobj"
       libobj=$func_xform_result
@@ -1289,5 +2136,5 @@
     # not support -o with -c
     if test "$compiler_c_o" = no; then
-      output_obj=`$ECHO "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext}
+      output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext}
       lockfile="$output_obj.lock"
     else
@@ -1320,15 +2167,14 @@
 	exit $EXIT_FAILURE
       fi
-      removelist="$removelist $output_obj"
+      func_append removelist " $output_obj"
       $ECHO "$srcfile" > "$lockfile"
     fi
 
     $opt_dry_run || $RM $removelist
-    removelist="$removelist $lockfile"
+    func_append removelist " $lockfile"
     trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15
 
-    if test -n "$fix_srcfile_path"; then
-      eval srcfile=\"$fix_srcfile_path\"
-    fi
+    func_to_tool_file "$srcfile" func_convert_file_msys_to_w32
+    srcfile=$func_to_tool_file_result
     func_quote_for_eval "$srcfile"
     qsrcfile=$func_quote_for_eval_result
@@ -1350,5 +2196,5 @@
       if test -z "$output_obj"; then
 	# Place PIC objects in $objdir
-	command="$command -o $lobj"
+	func_append command " -o $lobj"
       fi
 
@@ -1397,9 +2243,9 @@
       fi
       if test "$compiler_c_o" = yes; then
-	command="$command -o $obj"
+	func_append command " -o $obj"
       fi
 
       # Suppress compiler output if we already did a PIC compilation.
-      command="$command$suppress_output"
+      func_append command "$suppress_output"
       func_show_eval_locale "$command" \
         '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'
@@ -1446,5 +2292,5 @@
 
 $opt_help || {
-test "$mode" = compile && func_mode_compile ${1+"$@"}
+  test "$opt_mode" = compile && func_mode_compile ${1+"$@"}
 }
 
@@ -1452,5 +2298,5 @@
 {
     # We need to display help for each of the modes.
-    case $mode in
+    case $opt_mode in
       "")
         # Generic help is extracted from the usage comments
@@ -1483,8 +2329,9 @@
   -o OUTPUT-FILE    set the output file name to OUTPUT-FILE
   -no-suppress      do not suppress compiler output for multiple passes
-  -prefer-pic       try to building PIC objects only
-  -prefer-non-pic   try to building non-PIC objects only
+  -prefer-pic       try to build PIC objects only
+  -prefer-non-pic   try to build non-PIC objects only
   -shared           do not build a \`.o' file suitable for static linking
   -static           only build a \`.o' file suitable for static linking
+  -Wc,FLAG          pass FLAG directly to the compiler
 
 COMPILE-COMMAND is a command to be used in creating a \`standard' object file
@@ -1539,5 +2386,5 @@
 The following components of INSTALL-COMMAND are treated specially:
 
-  -inst-prefix PREFIX-DIR  Use PREFIX-DIR as a staging area for installation
+  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation
 
 The rest of the components are interpreted as arguments to that command (only
@@ -1559,4 +2406,6 @@
   -all-static       do not do any dynamic linking at all
   -avoid-version    do not add a version suffix if possible
+  -bindir BINDIR    specify path to binaries directory (for systems where
+                    libraries must be found in the PATH setting at runtime)
   -dlopen FILE      \`-dlpreopen' FILE if it cannot be dlopened at runtime
   -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols
@@ -1587,4 +2436,9 @@
                     specify library version info [each variable defaults to 0]
   -weak LIBNAME     declare that the target provides the LIBNAME interface
+  -Wc,FLAG
+  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler
+  -Wl,FLAG
+  -Xlinker FLAG     pass linker-specific FLAG directly to the linker
+  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)
 
 All other options (arguments beginning with \`-') are ignored.
@@ -1620,16 +2474,42 @@
 
       *)
-        func_fatal_help "invalid operation mode \`$mode'"
+        func_fatal_help "invalid operation mode \`$opt_mode'"
         ;;
     esac
 
-    $ECHO
+    echo
     $ECHO "Try \`$progname --help' for more information about other modes."
-
-    exit $?
-}
-
-  # Now that we've collected a possible --mode arg, show help if necessary
-  $opt_help && func_mode_help
+}
+
+# Now that we've collected a possible --mode arg, show help if necessary
+if $opt_help; then
+  if test "$opt_help" = :; then
+    func_mode_help
+  else
+    {
+      func_help noexit
+      for opt_mode in compile link execute install finish uninstall clean; do
+	func_mode_help
+      done
+    } | sed -n '1p; 2,$s/^Usage:/  or: /p'
+    {
+      func_help noexit
+      for opt_mode in compile link execute install finish uninstall clean; do
+	echo
+	func_mode_help
+      done
+    } |
+    sed '1d
+      /^When reporting/,/^Report/{
+	H
+	d
+      }
+      $x
+      /information about other modes/d
+      /more detailed .*MODE/d
+      s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/'
+  fi
+  exit $?
+fi
 
 
@@ -1644,5 +2524,5 @@
 
     # Handle -dlopen flags immediately.
-    for file in $execute_dlfiles; do
+    for file in $opt_dlopen; do
       test -f "$file" \
 	|| func_fatal_help "\`$file' is not a file"
@@ -1651,4 +2531,7 @@
       case $file in
       *.la)
+	func_resolve_sysroot "$file"
+	file=$func_resolve_sysroot_result
+
 	# Check to see that this really is a libtool archive.
 	func_lalib_unsafe_p "$file" \
@@ -1672,5 +2555,5 @@
 
 	if test -f "$dir/$objdir/$dlname"; then
-	  dir="$dir/$objdir"
+	  func_append dir "/$objdir"
 	else
 	  if test ! -f "$dir/$dlname"; then
@@ -1713,5 +2596,5 @@
     do
       case $file in
-      -*) ;;
+      -* | *.la | *.lo ) ;;
       *)
 	# Do a test to see if this is really a libtool program.
@@ -1729,6 +2612,5 @@
       esac
       # Quote arguments (to preserve shell metacharacters).
-      func_quote_for_eval "$file"
-      args="$args $func_quote_for_eval_result"
+      func_append_quoted args "$file"
     done
 
@@ -1755,5 +2637,5 @@
       if test -n "$shlibpath_var"; then
 	eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\""
-	$ECHO "export $shlibpath_var"
+	echo "export $shlibpath_var"
       fi
       $ECHO "$cmd$args"
@@ -1762,5 +2644,5 @@
 }
 
-test "$mode" = execute && func_mode_execute ${1+"$@"}
+test "$opt_mode" = execute && func_mode_execute ${1+"$@"}
 
 
@@ -1769,13 +2651,50 @@
 {
     $opt_debug
-    libdirs="$nonopt"
+    libs=
+    libdirs=
     admincmds=
 
+    for opt in "$nonopt" ${1+"$@"}
+    do
+      if test -d "$opt"; then
+	func_append libdirs " $opt"
+
+      elif test -f "$opt"; then
+	if func_lalib_unsafe_p "$opt"; then
+	  func_append libs " $opt"
+	else
+	  func_warning "\`$opt' is not a valid libtool archive"
+	fi
+
+      else
+	func_fatal_error "invalid argument \`$opt'"
+      fi
+    done
+
+    if test -n "$libs"; then
+      if test -n "$lt_sysroot"; then
+        sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"`
+        sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;"
+      else
+        sysroot_cmd=
+      fi
+
+      # Remove sysroot references
+      if $opt_dry_run; then
+        for lib in $libs; do
+          echo "removing references to $lt_sysroot and \`=' prefixes from $lib"
+        done
+      else
+        tmpdir=`func_mktempdir`
+        for lib in $libs; do
+	  sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \
+	    > $tmpdir/tmp-la
+	  mv -f $tmpdir/tmp-la $lib
+	done
+        ${RM}r "$tmpdir"
+      fi
+    fi
+
     if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
-      for dir
-      do
-	libdirs="$libdirs $dir"
-      done
-
       for libdir in $libdirs; do
 	if test -n "$finish_cmds"; then
@@ -1787,5 +2706,5 @@
 	  # Do the single finish_eval.
 	  eval cmds=\"$finish_eval\"
-	  $opt_dry_run || eval "$cmds" || admincmds="$admincmds
+	  $opt_dry_run || eval "$cmds" || func_append admincmds "
        $cmds"
 	fi
@@ -1796,51 +2715,53 @@
     $opt_silent && exit $EXIT_SUCCESS
 
-    $ECHO "X----------------------------------------------------------------------" | $Xsed
-    $ECHO "Libraries have been installed in:"
-    for libdir in $libdirs; do
-      $ECHO "   $libdir"
-    done
-    $ECHO
-    $ECHO "If you ever happen to want to link against installed libraries"
-    $ECHO "in a given directory, LIBDIR, you must either use libtool, and"
-    $ECHO "specify the full pathname of the library, or use the \`-LLIBDIR'"
-    $ECHO "flag during linking and do at least one of the following:"
-    if test -n "$shlibpath_var"; then
-      $ECHO "   - add LIBDIR to the \`$shlibpath_var' environment variable"
-      $ECHO "     during execution"
+    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+      echo "----------------------------------------------------------------------"
+      echo "Libraries have been installed in:"
+      for libdir in $libdirs; do
+	$ECHO "   $libdir"
+      done
+      echo
+      echo "If you ever happen to want to link against installed libraries"
+      echo "in a given directory, LIBDIR, you must either use libtool, and"
+      echo "specify the full pathname of the library, or use the \`-LLIBDIR'"
+      echo "flag during linking and do at least one of the following:"
+      if test -n "$shlibpath_var"; then
+	echo "   - add LIBDIR to the \`$shlibpath_var' environment variable"
+	echo "     during execution"
+      fi
+      if test -n "$runpath_var"; then
+	echo "   - add LIBDIR to the \`$runpath_var' environment variable"
+	echo "     during linking"
+      fi
+      if test -n "$hardcode_libdir_flag_spec"; then
+	libdir=LIBDIR
+	eval flag=\"$hardcode_libdir_flag_spec\"
+
+	$ECHO "   - use the \`$flag' linker flag"
+      fi
+      if test -n "$admincmds"; then
+	$ECHO "   - have your system administrator run these commands:$admincmds"
+      fi
+      if test -f /etc/ld.so.conf; then
+	echo "   - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
+      fi
+      echo
+
+      echo "See any operating system documentation about shared libraries for"
+      case $host in
+	solaris2.[6789]|solaris2.1[0-9])
+	  echo "more information, such as the ld(1), crle(1) and ld.so(8) manual"
+	  echo "pages."
+	  ;;
+	*)
+	  echo "more information, such as the ld(1) and ld.so(8) manual pages."
+	  ;;
+      esac
+      echo "----------------------------------------------------------------------"
     fi
-    if test -n "$runpath_var"; then
-      $ECHO "   - add LIBDIR to the \`$runpath_var' environment variable"
-      $ECHO "     during linking"
-    fi
-    if test -n "$hardcode_libdir_flag_spec"; then
-      libdir=LIBDIR
-      eval flag=\"$hardcode_libdir_flag_spec\"
-
-      $ECHO "   - use the \`$flag' linker flag"
-    fi
-    if test -n "$admincmds"; then
-      $ECHO "   - have your system administrator run these commands:$admincmds"
-    fi
-    if test -f /etc/ld.so.conf; then
-      $ECHO "   - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
-    fi
-    $ECHO
-
-    $ECHO "See any operating system documentation about shared libraries for"
-    case $host in
-      solaris2.[6789]|solaris2.1[0-9])
-        $ECHO "more information, such as the ld(1), crle(1) and ld.so(8) manual"
-	$ECHO "pages."
-	;;
-      *)
-        $ECHO "more information, such as the ld(1) and ld.so(8) manual pages."
-        ;;
-    esac
-    $ECHO "X----------------------------------------------------------------------" | $Xsed
     exit $EXIT_SUCCESS
 }
 
-test "$mode" = finish && func_mode_finish ${1+"$@"}
+test "$opt_mode" = finish && func_mode_finish ${1+"$@"}
 
 
@@ -1853,5 +2774,5 @@
     if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
        # Allow the use of GNU shtool's install command.
-       $ECHO "X$nonopt" | $GREP shtool >/dev/null; then
+       case $nonopt in *shtool*) :;; *) false;; esac; then
       # Aesthetically quote it.
       func_quote_for_eval "$nonopt"
@@ -1867,5 +2788,10 @@
     # Aesthetically quote it.
     func_quote_for_eval "$arg"
-    install_prog="$install_prog$func_quote_for_eval_result"
+    func_append install_prog "$func_quote_for_eval_result"
+    install_shared_prog=$install_prog
+    case " $install_prog " in
+      *[\\\ /]cp\ *) install_cp=: ;;
+      *) install_cp=false ;;
+    esac
 
     # We need to accept at least all the BSD install flags.
@@ -1877,8 +2803,10 @@
     isdir=no
     stripme=
+    no_mode=:
     for arg
     do
+      arg2=
       if test -n "$dest"; then
-	files="$files $dest"
+	func_append files " $dest"
 	dest=$arg
 	continue
@@ -1888,8 +2816,7 @@
       -d) isdir=yes ;;
       -f)
-	case " $install_prog " in
-	*[\\\ /]cp\ *) ;;
-	*) prev=$arg ;;
-	esac
+	if $install_cp; then :; else
+	  prev=$arg
+	fi
 	;;
       -g | -m | -o)
@@ -1905,4 +2832,8 @@
 	# If the previous option needed an argument, then skip it.
 	if test -n "$prev"; then
+	  if test "x$prev" = x-m && test -n "$install_override_mode"; then
+	    arg2=$install_override_mode
+	    no_mode=false
+	  fi
 	  prev=
 	else
@@ -1915,5 +2846,9 @@
       # Aesthetically quote the argument.
       func_quote_for_eval "$arg"
-      install_prog="$install_prog $func_quote_for_eval_result"
+      func_append install_prog " $func_quote_for_eval_result"
+      if test -n "$arg2"; then
+	func_quote_for_eval "$arg2"
+      fi
+      func_append install_shared_prog " $func_quote_for_eval_result"
     done
 
@@ -1923,4 +2858,11 @@
     test -n "$prev" && \
       func_fatal_help "the \`$prev' option requires an argument"
+
+    if test -n "$install_override_mode" && $no_mode; then
+      if $install_cp; then :; else
+	func_quote_for_eval "$install_override_mode"
+	func_append install_shared_prog " -m $func_quote_for_eval_result"
+      fi
+    fi
 
     if test -z "$files"; then
@@ -1978,8 +2920,11 @@
       *.$libext)
 	# Do the static libraries later.
-	staticlibs="$staticlibs $file"
+	func_append staticlibs " $file"
 	;;
 
       *.la)
+	func_resolve_sysroot "$file"
+	file=$func_resolve_sysroot_result
+
 	# Check to see that this really is a libtool archive.
 	func_lalib_unsafe_p "$file" \
@@ -1995,5 +2940,5 @@
 	  case "$current_libdirs " in
 	  *" $libdir "*) ;;
-	  *) current_libdirs="$current_libdirs $libdir" ;;
+	  *) func_append current_libdirs " $libdir" ;;
 	  esac
 	else
@@ -2001,5 +2946,5 @@
 	  case "$future_libdirs " in
 	  *" $libdir "*) ;;
-	  *) future_libdirs="$future_libdirs $libdir" ;;
+	  *) func_append future_libdirs " $libdir" ;;
 	  esac
 	fi
@@ -2007,9 +2952,9 @@
 	func_dirname "$file" "/" ""
 	dir="$func_dirname_result"
-	dir="$dir$objdir"
+	func_append dir "$objdir"
 
 	if test -n "$relink_command"; then
 	  # Determine the prefix the user has applied to our future dir.
-	  inst_prefix_dir=`$ECHO "X$destdir" | $Xsed -e "s%$libdir\$%%"`
+	  inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"`
 
 	  # Don't allow the user to place us outside of our expected
@@ -2024,7 +2969,7 @@
 	  if test -n "$inst_prefix_dir"; then
 	    # Stick the inst_prefix_dir data into the link command.
-	    relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"`
+	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"`
 	  else
-	    relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%%"`
+	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"`
 	  fi
 
@@ -2044,5 +2989,5 @@
 
 	  # Install the shared library and build the symlinks.
-	  func_show_eval "$install_prog $dir/$srcname $destdir/$realname" \
+	  func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \
 	      'exit $?'
 	  tstripme="$stripme"
@@ -2084,5 +3029,5 @@
 
 	# Maybe install the static library, too.
-	test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library"
+	test -n "$old_library" && func_append staticlibs " $dir/$old_library"
 	;;
 
@@ -2184,5 +3129,5 @@
 	      func_source "$lib"
 	    fi
-	    libfile="$libdir/"`$ECHO "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test
+	    libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test
 	    if test -n "$libdir" && test ! -f "$libfile"; then
 	      func_warning "\`$lib' has not been installed in \`$libdir'"
@@ -2203,5 +3148,5 @@
 	        outputname="$tmpdir/$file"
 	        # Replace the output file specification.
-	        relink_command=`$ECHO "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'`
+	        relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'`
 
 	        $opt_silent || {
@@ -2222,5 +3167,5 @@
 	  else
 	    # Install the binary that we compiled earlier.
-	    file=`$ECHO "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"`
+	    file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"`
 	  fi
 	fi
@@ -2258,9 +3203,11 @@
       # Set up the ranlib parameters.
       oldlib="$destdir/$name"
+      func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
+      tool_oldlib=$func_to_tool_file_result
 
       func_show_eval "$install_prog \$file \$oldlib" 'exit $?'
 
       if test -n "$stripme" && test -n "$old_striplib"; then
-	func_show_eval "$old_striplib $oldlib" 'exit $?'
+	func_show_eval "$old_striplib $tool_oldlib" 'exit $?'
       fi
 
@@ -2281,5 +3228,5 @@
 }
 
-test "$mode" = install && func_mode_install ${1+"$@"}
+test "$opt_mode" = install && func_mode_install ${1+"$@"}
 
 
@@ -2324,4 +3271,20 @@
 #endif
 
+#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))
+#pragma GCC diagnostic ignored \"-Wstrict-prototypes\"
+#endif
+
+/* 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_DLSYM_CONST
+#elif defined(__osf__)
+/* This system does not cope well with relocations in const data.  */
+# define LT_DLSYM_CONST
+#else
+# define LT_DLSYM_CONST const
+#endif
+
 /* External symbol declarations for the compiler. */\
 "
@@ -2333,8 +3296,9 @@
 
 	  # Add our own program objects to the symbol list.
-	  progfiles=`$ECHO "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+	  progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP`
 	  for progfile in $progfiles; do
-	    func_verbose "extracting global C symbols from \`$progfile'"
-	    $opt_dry_run || eval "$NM $progfile | $global_symbol_pipe >> '$nlist'"
+	    func_to_tool_file "$progfile" func_convert_file_msys_to_w32
+	    func_verbose "extracting global C symbols from \`$func_to_tool_file_result'"
+	    $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'"
 	  done
 
@@ -2372,5 +3336,5 @@
 	      eval '$MV "$nlist"T "$nlist"'
 	      case $host in
-	        *cygwin | *mingw* | *cegcc* )
+	        *cygwin* | *mingw* | *cegcc* )
 	          eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
 	          eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
@@ -2385,8 +3349,50 @@
 	  func_basename "$dlprefile"
 	  name="$func_basename_result"
-	  $opt_dry_run || {
-	    eval '$ECHO ": $name " >> "$nlist"'
-	    eval "$NM $dlprefile 2>/dev/null | $global_symbol_pipe >> '$nlist'"
-	  }
+          case $host in
+	    *cygwin* | *mingw* | *cegcc* )
+	      # if an import library, we need to obtain dlname
+	      if func_win32_import_lib_p "$dlprefile"; then
+	        func_tr_sh "$dlprefile"
+	        eval "curr_lafile=\$libfile_$func_tr_sh_result"
+	        dlprefile_dlbasename=""
+	        if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then
+	          # Use subshell, to avoid clobbering current variable values
+	          dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"`
+	          if test -n "$dlprefile_dlname" ; then
+	            func_basename "$dlprefile_dlname"
+	            dlprefile_dlbasename="$func_basename_result"
+	          else
+	            # no lafile. user explicitly requested -dlpreopen <import library>.
+	            $sharedlib_from_linklib_cmd "$dlprefile"
+	            dlprefile_dlbasename=$sharedlib_from_linklib_result
+	          fi
+	        fi
+	        $opt_dry_run || {
+	          if test -n "$dlprefile_dlbasename" ; then
+	            eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"'
+	          else
+	            func_warning "Could not compute DLL name from $name"
+	            eval '$ECHO ": $name " >> "$nlist"'
+	          fi
+	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe |
+	            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'"
+	        }
+	      else # not an import lib
+	        $opt_dry_run || {
+	          eval '$ECHO ": $name " >> "$nlist"'
+	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'"
+	        }
+	      fi
+	    ;;
+	    *)
+	      $opt_dry_run || {
+	        eval '$ECHO ": $name " >> "$nlist"'
+	        func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	        eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'"
+	      }
+	    ;;
+          esac
 	done
 
@@ -2416,8 +3422,8 @@
 	    eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"'
 	  else
-	    $ECHO '/* NONE */' >> "$output_objdir/$my_dlsyms"
+	    echo '/* NONE */' >> "$output_objdir/$my_dlsyms"
 	  fi
 
-	  $ECHO >> "$output_objdir/$my_dlsyms" "\
+	  echo >> "$output_objdir/$my_dlsyms" "\
 
 /* The mapping between symbol names and symbols.  */
@@ -2426,24 +3432,7 @@
   void *address;
 } lt_dlsymlist;
-"
-	  case $host in
-	  *cygwin* | *mingw* | *cegcc* )
-	    $ECHO >> "$output_objdir/$my_dlsyms" "\
-/* DATA imports from DLLs on WIN32 con't be const, because
-   runtime relocations are performed -- see ld's documentation
-   on pseudo-relocs.  */"
-	    lt_dlsym_const= ;;
-	  *osf5*)
-	    echo >> "$output_objdir/$my_dlsyms" "\
-/* This system does not cope well with relocations in const data */"
-	    lt_dlsym_const= ;;
-	  *)
-	    lt_dlsym_const=const ;;
-	  esac
-
-	  $ECHO >> "$output_objdir/$my_dlsyms" "\
-extern $lt_dlsym_const lt_dlsymlist
+extern LT_DLSYM_CONST lt_dlsymlist
 lt_${my_prefix}_LTX_preloaded_symbols[];
-$lt_dlsym_const lt_dlsymlist
+LT_DLSYM_CONST lt_dlsymlist
 lt_${my_prefix}_LTX_preloaded_symbols[] =
 {\
@@ -2458,5 +3447,5 @@
 	    ;;
 	  esac
-	  $ECHO >> "$output_objdir/$my_dlsyms" "\
+	  echo >> "$output_objdir/$my_dlsyms" "\
   {0, (void *) 0}
 };
@@ -2485,5 +3474,5 @@
 	  # pic_flag when linking with -static.  The problem exists in
 	  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
-	  *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
+	  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
 	    pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;;
 	  *-*-hpux*)
@@ -2501,5 +3490,5 @@
 	  case $arg in
 	  -pie | -fpie | -fPIE) ;;
-	  *) symtab_cflags="$symtab_cflags $arg" ;;
+	  *) func_append symtab_cflags " $arg" ;;
 	  esac
 	done
@@ -2516,14 +3505,14 @@
 	*cygwin* | *mingw* | *cegcc* )
 	  if test -f "$output_objdir/$my_outputname.def"; then
-	    compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
-	    finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
 	  else
-	    compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
-	    finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
+	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"`
 	  fi
 	  ;;
 	*)
-	  compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
-	  finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"`
+	  compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"`
+	  finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"`
 	  ;;
 	esac
@@ -2539,6 +3528,6 @@
 
       # Nullify the symbol file.
-      compile_command=`$ECHO "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"`
-      finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"`
+      compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"`
+      finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"`
     fi
 }
@@ -2550,4 +3539,5 @@
 # Has to be a shell function in order to 'eat' the argument
 # that is supplied when $file_magic_command is called.
+# Despite the name, also deal with 64 bit binaries.
 func_win32_libid ()
 {
@@ -2560,7 +3550,9 @@
     ;;
   *ar\ archive*) # could be an import, or static
+    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.
     if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |
-       $EGREP 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then
-      win32_nmres=`eval $NM -f posix -A $1 |
+       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then
+      func_to_tool_file "$1" func_convert_file_msys_to_w32
+      win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" |
 	$SED -n -e '
 	    1,100{
@@ -2591,4 +3583,129 @@
 }
 
+# func_cygming_dll_for_implib ARG
+#
+# Platform-specific function to extract the
+# name of the DLL associated with the specified
+# import library ARG.
+# Invoked by eval'ing the libtool variable
+#    $sharedlib_from_linklib_cmd
+# Result is available in the variable
+#    $sharedlib_from_linklib_result
+func_cygming_dll_for_implib ()
+{
+  $opt_debug
+  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"`
+}
+
+# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs
+#
+# The is the core of a fallback implementation of a
+# platform-specific function to extract the name of the
+# DLL associated with the specified import library LIBNAME.
+#
+# SECTION_NAME is either .idata$6 or .idata$7, depending
+# on the platform and compiler that created the implib.
+#
+# Echos the name of the DLL associated with the
+# specified import library.
+func_cygming_dll_for_implib_fallback_core ()
+{
+  $opt_debug
+  match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"`
+  $OBJDUMP -s --section "$1" "$2" 2>/dev/null |
+    $SED '/^Contents of section '"$match_literal"':/{
+      # Place marker at beginning of archive member dllname section
+      s/.*/====MARK====/
+      p
+      d
+    }
+    # These lines can sometimes be longer than 43 characters, but
+    # are always uninteresting
+    /:[	 ]*file format pe[i]\{,1\}-/d
+    /^In archive [^:]*:/d
+    # Ensure marker is printed
+    /^====MARK====/p
+    # Remove all lines with less than 43 characters
+    /^.\{43\}/!d
+    # From remaining lines, remove first 43 characters
+    s/^.\{43\}//' |
+    $SED -n '
+      # Join marker and all lines until next marker into a single line
+      /^====MARK====/ b para
+      H
+      $ b para
+      b
+      :para
+      x
+      s/\n//g
+      # Remove the marker
+      s/^====MARK====//
+      # Remove trailing dots and whitespace
+      s/[\. \t]*$//
+      # Print
+      /./p' |
+    # we now have a list, one entry per line, of the stringified
+    # contents of the appropriate section of all members of the
+    # archive which possess that section. Heuristic: eliminate
+    # all those which have a first or second character that is
+    # a '.' (that is, objdump's representation of an unprintable
+    # character.) This should work for all archives with less than
+    # 0x302f exports -- but will fail for DLLs whose name actually
+    # begins with a literal '.' or a single character followed by
+    # a '.'.
+    #
+    # Of those that remain, print the first one.
+    $SED -e '/^\./d;/^.\./d;q'
+}
+
+# func_cygming_gnu_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is a GNU/binutils-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_gnu_implib_p ()
+{
+  $opt_debug
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`
+  test -n "$func_cygming_gnu_implib_tmp"
+}
+
+# func_cygming_ms_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is an MS-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_ms_implib_p ()
+{
+  $opt_debug
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'`
+  test -n "$func_cygming_ms_implib_tmp"
+}
+
+# func_cygming_dll_for_implib_fallback ARG
+# Platform-specific function to extract the
+# name of the DLL associated with the specified
+# import library ARG.
+#
+# This fallback implementation is for use when $DLLTOOL
+# does not support the --identify-strict option.
+# Invoked by eval'ing the libtool variable
+#    $sharedlib_from_linklib_cmd
+# Result is available in the variable
+#    $sharedlib_from_linklib_result
+func_cygming_dll_for_implib_fallback ()
+{
+  $opt_debug
+  if func_cygming_gnu_implib_p "$1" ; then
+    # binutils import library
+    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"`
+  elif func_cygming_ms_implib_p "$1" ; then
+    # ms-generated import library
+    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"`
+  else
+    # unknown
+    sharedlib_from_linklib_result=""
+  fi
+}
 
 
@@ -2599,5 +3716,16 @@
     f_ex_an_ar_dir="$1"; shift
     f_ex_an_ar_oldlib="$1"
-    func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" 'exit $?'
+    if test "$lock_old_archive_extraction" = yes; then
+      lockfile=$f_ex_an_ar_oldlib.lock
+      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
+	func_echo "Waiting for $lockfile to be removed"
+	sleep 2
+      done
+    fi
+    func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \
+		   'stat=$?; rm -f "$lockfile"; exit $stat'
+    if test "$lock_old_archive_extraction" = yes; then
+      $opt_dry_run || rm -f "$lockfile"
+    fi
     if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
      :
@@ -2670,5 +3798,5 @@
 	    darwin_files=
 	    for darwin_file in $darwin_filelist; do
-	      darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP`
+	      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`
 	      $LIPO -create -output "$darwin_file" $darwin_files
 	    done # $darwin_filelist
@@ -2685,244 +3813,9 @@
 	;;
       esac
-      my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP`
+      my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP`
     done
 
     func_extract_archives_result="$my_oldobjs"
 }
-
-
-
-# func_emit_wrapper_part1 [arg=no]
-#
-# Emit the first part of a libtool wrapper script on stdout.
-# For more information, see the description associated with
-# func_emit_wrapper(), below.
-func_emit_wrapper_part1 ()
-{
-	func_emit_wrapper_part1_arg1=no
-	if test -n "$1" ; then
-	  func_emit_wrapper_part1_arg1=$1
-	fi
-
-	$ECHO "\
-#! $SHELL
-
-# $output - temporary wrapper script for $objdir/$outputname
-# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
-#
-# The $output program cannot be directly executed until all the libtool
-# libraries that it depends on are installed.
-#
-# This wrapper script should never be moved out of the build directory.
-# If it is, it will not operate correctly.
-
-# Sed substitution that helps us do robust quoting.  It backslashifies
-# metacharacters that are still active within double-quoted strings.
-Xsed='${SED} -e 1s/^X//'
-sed_quote_subst='$sed_quote_subst'
-
-# Be Bourne compatible
-if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '\${1+\"\$@\"}'='\"\$@\"'
-  setopt NO_GLOB_SUBST
-else
-  case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
-fi
-BIN_SH=xpg4; export BIN_SH # for Tru64
-DUALCASE=1; export DUALCASE # for MKS sh
-
-# 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
-
-relink_command=\"$relink_command\"
-
-# This environment variable determines our operation mode.
-if test \"\$libtool_install_magic\" = \"$magic\"; then
-  # install mode needs the following variables:
-  generated_by_libtool_version='$macro_version'
-  notinst_deplibs='$notinst_deplibs'
-else
-  # When we are sourced in execute mode, \$file and \$ECHO are already set.
-  if test \"\$libtool_execute_magic\" != \"$magic\"; then
-    ECHO=\"$qecho\"
-    file=\"\$0\"
-    # Make sure echo works.
-    if test \"X\$1\" = X--no-reexec; then
-      # Discard the --no-reexec flag, and continue.
-      shift
-    elif test \"X\`{ \$ECHO '\t'; } 2>/dev/null\`\" = 'X\t'; then
-      # Yippee, \$ECHO works!
-      :
-    else
-      # Restart under the correct shell, and then maybe \$ECHO will work.
-      exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"}
-    fi
-  fi\
-"
-	$ECHO "\
-
-  # Find the directory that this script lives in.
-  thisdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\`
-  test \"x\$thisdir\" = \"x\$file\" && thisdir=.
-
-  # Follow symbolic links until we get to the real thisdir.
-  file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\`
-  while test -n \"\$file\"; do
-    destdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\`
-
-    # If there was a directory component, then change thisdir.
-    if test \"x\$destdir\" != \"x\$file\"; then
-      case \"\$destdir\" in
-      [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
-      *) thisdir=\"\$thisdir/\$destdir\" ;;
-      esac
-    fi
-
-    file=\`\$ECHO \"X\$file\" | \$Xsed -e 's%^.*/%%'\`
-    file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\`
-  done
-"
-}
-# end: func_emit_wrapper_part1
-
-# func_emit_wrapper_part2 [arg=no]
-#
-# Emit the second part of a libtool wrapper script on stdout.
-# For more information, see the description associated with
-# func_emit_wrapper(), below.
-func_emit_wrapper_part2 ()
-{
-	func_emit_wrapper_part2_arg1=no
-	if test -n "$1" ; then
-	  func_emit_wrapper_part2_arg1=$1
-	fi
-
-	$ECHO "\
-
-  # Usually 'no', except on cygwin/mingw when embedded into
-  # the cwrapper.
-  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_part2_arg1
-  if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then
-    # special case for '.'
-    if test \"\$thisdir\" = \".\"; then
-      thisdir=\`pwd\`
-    fi
-    # remove .libs from thisdir
-    case \"\$thisdir\" in
-    *[\\\\/]$objdir ) thisdir=\`\$ECHO \"X\$thisdir\" | \$Xsed -e 's%[\\\\/][^\\\\/]*$%%'\` ;;
-    $objdir )   thisdir=. ;;
-    esac
-  fi
-
-  # Try to get the absolute directory name.
-  absdir=\`cd \"\$thisdir\" && pwd\`
-  test -n \"\$absdir\" && thisdir=\"\$absdir\"
-"
-
-	if test "$fast_install" = yes; then
-	  $ECHO "\
-  program=lt-'$outputname'$exeext
-  progdir=\"\$thisdir/$objdir\"
-
-  if test ! -f \"\$progdir/\$program\" ||
-     { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
-       test \"X\$file\" != \"X\$progdir/\$program\"; }; then
-
-    file=\"\$\$-\$program\"
-
-    if test ! -d \"\$progdir\"; then
-      $MKDIR \"\$progdir\"
-    else
-      $RM \"\$progdir/\$file\"
-    fi"
-
-	  $ECHO "\
-
-    # relink executable if necessary
-    if test -n \"\$relink_command\"; then
-      if relink_command_output=\`eval \$relink_command 2>&1\`; then :
-      else
-	$ECHO \"\$relink_command_output\" >&2
-	$RM \"\$progdir/\$file\"
-	exit 1
-      fi
-    fi
-
-    $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
-    { $RM \"\$progdir/\$program\";
-      $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; }
-    $RM \"\$progdir/\$file\"
-  fi"
-	else
-	  $ECHO "\
-  program='$outputname'
-  progdir=\"\$thisdir/$objdir\"
-"
-	fi
-
-	$ECHO "\
-
-  if test -f \"\$progdir/\$program\"; then"
-
-	# Export our shlibpath_var if we have one.
-	if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
-	  $ECHO "\
-    # Add our own library path to $shlibpath_var
-    $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
-
-    # Some systems cannot cope with colon-terminated $shlibpath_var
-    # The second colon is a workaround for a bug in BeOS R4 sed
-    $shlibpath_var=\`\$ECHO \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\`
-
-    export $shlibpath_var
-"
-	fi
-
-	# fixup the dll searchpath if we need to.
-	if test -n "$dllsearchpath"; then
-	  $ECHO "\
-    # Add the dll search path components to the executable PATH
-    PATH=$dllsearchpath:\$PATH
-"
-	fi
-
-	$ECHO "\
-    if test \"\$libtool_execute_magic\" != \"$magic\"; then
-      # Run the actual program with our arguments.
-"
-	case $host in
-	# Backslashes separate directories on plain windows
-	*-*-mingw | *-*-os2* | *-cegcc*)
-	  $ECHO "\
-      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
-"
-	  ;;
-
-	*)
-	  $ECHO "\
-      exec \"\$progdir/\$program\" \${1+\"\$@\"}
-"
-	  ;;
-	esac
-	$ECHO "\
-      \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2
-      exit 1
-    fi
-  else
-    # The program doesn't exist.
-    \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
-    \$ECHO \"This script is just a wrapper for \$program.\" 1>&2
-    $ECHO \"See the $PACKAGE documentation for more information.\" 1>&2
-    exit 1
-  fi
-fi\
-"
-}
-# end: func_emit_wrapper_part2
 
 
@@ -2943,186 +3836,299 @@
 func_emit_wrapper ()
 {
-	func_emit_wrapper_arg1=no
-	if test -n "$1" ; then
-	  func_emit_wrapper_arg1=$1
-	fi
-
-	# split this up so that func_emit_cwrapperexe_src
-	# can call each part independently.
-	func_emit_wrapper_part1 "${func_emit_wrapper_arg1}"
-	func_emit_wrapper_part2 "${func_emit_wrapper_arg1}"
-}
-
-
-# func_to_host_path arg
+	func_emit_wrapper_arg1=${1-no}
+
+	$ECHO "\
+#! $SHELL
+
+# $output - temporary wrapper script for $objdir/$outputname
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
 #
-# Convert paths to host format when used with build tools.
-# Intended for use with "native" mingw (where libtool itself
-# is running under the msys shell), or in the following cross-
-# build environments:
-#    $build          $host
-#    mingw (msys)    mingw  [e.g. native]
-#    cygwin          mingw
-#    *nix + wine     mingw
-# where wine is equipped with the `winepath' executable.
-# In the native mingw case, the (msys) shell automatically
-# converts paths for any non-msys applications it launches,
-# but that facility isn't available from inside the cwrapper.
-# Similar accommodations are necessary for $host mingw and
-# $build cygwin.  Calling this function does no harm for other
-# $host/$build combinations not listed above.
+# The $output program cannot be directly executed until all the libtool
+# libraries that it depends on are installed.
 #
-# ARG is the path (on $build) that should be converted to
-# the proper representation for $host. The result is stored
-# in $func_to_host_path_result.
-func_to_host_path ()
-{
-  func_to_host_path_result="$1"
-  if test -n "$1" ; then
-    case $host in
-      *mingw* )
-        lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
-        case $build in
-          *mingw* ) # actually, msys
-            # awkward: cmd appends spaces to result
-            lt_sed_strip_trailing_spaces="s/[ ]*\$//"
-            func_to_host_path_tmp1=`( cmd //c echo "$1" |\
-              $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""`
-            func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\
-              $SED -e "$lt_sed_naive_backslashify"`
-            ;;
-          *cygwin* )
-            func_to_host_path_tmp1=`cygpath -w "$1"`
-            func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\
-              $SED -e "$lt_sed_naive_backslashify"`
-            ;;
-          * )
-            # Unfortunately, winepath does not exit with a non-zero
-            # error code, so we are forced to check the contents of
-            # stdout. On the other hand, if the command is not
-            # found, the shell will set an exit code of 127 and print
-            # *an error message* to stdout. So we must check for both
-            # error code of zero AND non-empty stdout, which explains
-            # the odd construction:
-            func_to_host_path_tmp1=`winepath -w "$1" 2>/dev/null`
-            if test "$?" -eq 0 && test -n "${func_to_host_path_tmp1}"; then
-              func_to_host_path_result=`echo "$func_to_host_path_tmp1" |\
-                $SED -e "$lt_sed_naive_backslashify"`
-            else
-              # Allow warning below.
-              func_to_host_path_result=""
-            fi
-            ;;
-        esac
-        if test -z "$func_to_host_path_result" ; then
-          func_error "Could not determine host path corresponding to"
-          func_error "  '$1'"
-          func_error "Continuing, but uninstalled executables may not work."
-          # Fallback:
-          func_to_host_path_result="$1"
-        fi
-        ;;
+# This wrapper script should never be moved out of the build directory.
+# If it is, it will not operate correctly.
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+sed_quote_subst='$sed_quote_subst'
+
+# Be Bourne compatible
+if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'='\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
+fi
+BIN_SH=xpg4; export BIN_SH # for Tru64
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# 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
+
+relink_command=\"$relink_command\"
+
+# This environment variable determines our operation mode.
+if test \"\$libtool_install_magic\" = \"$magic\"; then
+  # install mode needs the following variables:
+  generated_by_libtool_version='$macro_version'
+  notinst_deplibs='$notinst_deplibs'
+else
+  # When we are sourced in execute mode, \$file and \$ECHO are already set.
+  if test \"\$libtool_execute_magic\" != \"$magic\"; then
+    file=\"\$0\""
+
+    qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"`
+    $ECHO "\
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+\$1
+_LTECHO_EOF'
+}
+    ECHO=\"$qECHO\"
+  fi
+
+# Very basic option parsing. These options are (a) specific to
+# the libtool wrapper, (b) are identical between the wrapper
+# /script/ and the wrapper /executable/ which is used only on
+# windows platforms, and (c) all begin with the string "--lt-"
+# (application programs are unlikely to have options which match
+# this pattern).
+#
+# There are only two supported options: --lt-debug and
+# --lt-dump-script. There is, deliberately, no --lt-help.
+#
+# The first argument to this parsing function should be the
+# script's $0 value, followed by "$@".
+lt_option_debug=
+func_parse_lt_options ()
+{
+  lt_script_arg0=\$0
+  shift
+  for lt_opt
+  do
+    case \"\$lt_opt\" in
+    --lt-debug) lt_option_debug=1 ;;
+    --lt-dump-script)
+        lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\`
+        test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=.
+        lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\`
+        cat \"\$lt_dump_D/\$lt_dump_F\"
+        exit 0
+      ;;
+    --lt-*)
+        \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2
+        exit 1
+      ;;
+    esac
+  done
+
+  # Print the debug banner immediately:
+  if test -n \"\$lt_option_debug\"; then
+    echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2
+  fi
+}
+
+# Used when --lt-debug. Prints its arguments to stdout
+# (redirection is the responsibility of the caller)
+func_lt_dump_args ()
+{
+  lt_dump_args_N=1;
+  for lt_arg
+  do
+    \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\"
+    lt_dump_args_N=\`expr \$lt_dump_args_N + 1\`
+  done
+}
+
+# Core function for launching the target application
+func_exec_program_core ()
+{
+"
+  case $host in
+  # Backslashes separate directories on plain windows
+  *-*-mingw | *-*-os2* | *-cegcc*)
+    $ECHO "\
+      if test -n \"\$lt_option_debug\"; then
+        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2
+        func_lt_dump_args \${1+\"\$@\"} 1>&2
+      fi
+      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
+"
+    ;;
+
+  *)
+    $ECHO "\
+      if test -n \"\$lt_option_debug\"; then
+        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2
+        func_lt_dump_args \${1+\"\$@\"} 1>&2
+      fi
+      exec \"\$progdir/\$program\" \${1+\"\$@\"}
+"
+    ;;
+  esac
+  $ECHO "\
+      \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2
+      exit 1
+}
+
+# A function to encapsulate launching the target application
+# Strips options in the --lt-* namespace from \$@ and
+# launches target application with the remaining arguments.
+func_exec_program ()
+{
+  case \" \$* \" in
+  *\\ --lt-*)
+    for lt_wr_arg
+    do
+      case \$lt_wr_arg in
+      --lt-*) ;;
+      *) set x \"\$@\" \"\$lt_wr_arg\"; shift;;
+      esac
+      shift
+    done ;;
+  esac
+  func_exec_program_core \${1+\"\$@\"}
+}
+
+  # Parse options
+  func_parse_lt_options \"\$0\" \${1+\"\$@\"}
+
+  # Find the directory that this script lives in.
+  thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\`
+  test \"x\$thisdir\" = \"x\$file\" && thisdir=.
+
+  # Follow symbolic links until we get to the real thisdir.
+  file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\`
+  while test -n \"\$file\"; do
+    destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\`
+
+    # If there was a directory component, then change thisdir.
+    if test \"x\$destdir\" != \"x\$file\"; then
+      case \"\$destdir\" in
+      [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
+      *) thisdir=\"\$thisdir/\$destdir\" ;;
+      esac
+    fi
+
+    file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\`
+    file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\`
+  done
+
+  # Usually 'no', except on cygwin/mingw when embedded into
+  # the cwrapper.
+  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1
+  if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then
+    # special case for '.'
+    if test \"\$thisdir\" = \".\"; then
+      thisdir=\`pwd\`
+    fi
+    # remove .libs from thisdir
+    case \"\$thisdir\" in
+    *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;;
+    $objdir )   thisdir=. ;;
     esac
   fi
-}
-# end: func_to_host_path
-
-# func_to_host_pathlist arg
-#
-# Convert pathlists to host format when used with build tools.
-# See func_to_host_path(), above. This function supports the
-# following $build/$host combinations (but does no harm for
-# combinations not listed here):
-#    $build          $host
-#    mingw (msys)    mingw  [e.g. native]
-#    cygwin          mingw
-#    *nix + wine     mingw
-#
-# Path separators are also converted from $build format to
-# $host format. If ARG begins or ends with a path separator
-# character, it is preserved (but converted to $host format)
-# on output.
-#
-# ARG is a pathlist (on $build) that should be converted to
-# the proper representation on $host. The result is stored
-# in $func_to_host_pathlist_result.
-func_to_host_pathlist ()
-{
-  func_to_host_pathlist_result="$1"
-  if test -n "$1" ; then
-    case $host in
-      *mingw* )
-        lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
-        # Remove leading and trailing path separator characters from
-        # ARG. msys behavior is inconsistent here, cygpath turns them
-        # into '.;' and ';.', and winepath ignores them completely.
-        func_to_host_pathlist_tmp2="$1"
-        # Once set for this call, this variable should not be
-        # reassigned. It is used in tha fallback case.
-        func_to_host_pathlist_tmp1=`echo "$func_to_host_pathlist_tmp2" |\
-          $SED -e 's|^:*||' -e 's|:*$||'`
-        case $build in
-          *mingw* ) # Actually, msys.
-            # Awkward: cmd appends spaces to result.
-            lt_sed_strip_trailing_spaces="s/[ ]*\$//"
-            func_to_host_pathlist_tmp2=`( cmd //c echo "$func_to_host_pathlist_tmp1" |\
-              $SED -e "$lt_sed_strip_trailing_spaces" ) 2>/dev/null || echo ""`
-            func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\
-              $SED -e "$lt_sed_naive_backslashify"`
-            ;;
-          *cygwin* )
-            func_to_host_pathlist_tmp2=`cygpath -w -p "$func_to_host_pathlist_tmp1"`
-            func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp2" |\
-              $SED -e "$lt_sed_naive_backslashify"`
-            ;;
-          * )
-            # unfortunately, winepath doesn't convert pathlists
-            func_to_host_pathlist_result=""
-            func_to_host_pathlist_oldIFS=$IFS
-            IFS=:
-            for func_to_host_pathlist_f in $func_to_host_pathlist_tmp1 ; do
-              IFS=$func_to_host_pathlist_oldIFS
-              if test -n "$func_to_host_pathlist_f" ; then
-                func_to_host_path "$func_to_host_pathlist_f"
-                if test -n "$func_to_host_path_result" ; then
-                  if test -z "$func_to_host_pathlist_result" ; then
-                    func_to_host_pathlist_result="$func_to_host_path_result"
-                  else
-                    func_to_host_pathlist_result="$func_to_host_pathlist_result;$func_to_host_path_result"
-                  fi
-                fi
-              fi
-              IFS=:
-            done
-            IFS=$func_to_host_pathlist_oldIFS
-            ;;
-        esac
-        if test -z "$func_to_host_pathlist_result" ; then
-          func_error "Could not determine the host path(s) corresponding to"
-          func_error "  '$1'"
-          func_error "Continuing, but uninstalled executables may not work."
-          # Fallback. This may break if $1 contains DOS-style drive
-          # specifications. The fix is not to complicate the expression
-          # below, but for the user to provide a working wine installation
-          # with winepath so that path translation in the cross-to-mingw
-          # case works properly.
-          lt_replace_pathsep_nix_to_dos="s|:|;|g"
-          func_to_host_pathlist_result=`echo "$func_to_host_pathlist_tmp1" |\
-            $SED -e "$lt_replace_pathsep_nix_to_dos"`
-        fi
-        # Now, add the leading and trailing path separators back
-        case "$1" in
-          :* ) func_to_host_pathlist_result=";$func_to_host_pathlist_result"
-            ;;
-        esac
-        case "$1" in
-          *: ) func_to_host_pathlist_result="$func_to_host_pathlist_result;"
-            ;;
-        esac
-        ;;
-    esac
+
+  # Try to get the absolute directory name.
+  absdir=\`cd \"\$thisdir\" && pwd\`
+  test -n \"\$absdir\" && thisdir=\"\$absdir\"
+"
+
+	if test "$fast_install" = yes; then
+	  $ECHO "\
+  program=lt-'$outputname'$exeext
+  progdir=\"\$thisdir/$objdir\"
+
+  if test ! -f \"\$progdir/\$program\" ||
+     { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
+       test \"X\$file\" != \"X\$progdir/\$program\"; }; then
+
+    file=\"\$\$-\$program\"
+
+    if test ! -d \"\$progdir\"; then
+      $MKDIR \"\$progdir\"
+    else
+      $RM \"\$progdir/\$file\"
+    fi"
+
+	  $ECHO "\
+
+    # relink executable if necessary
+    if test -n \"\$relink_command\"; then
+      if relink_command_output=\`eval \$relink_command 2>&1\`; then :
+      else
+	$ECHO \"\$relink_command_output\" >&2
+	$RM \"\$progdir/\$file\"
+	exit 1
+      fi
+    fi
+
+    $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
+    { $RM \"\$progdir/\$program\";
+      $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; }
+    $RM \"\$progdir/\$file\"
+  fi"
+	else
+	  $ECHO "\
+  program='$outputname'
+  progdir=\"\$thisdir/$objdir\"
+"
+	fi
+
+	$ECHO "\
+
+  if test -f \"\$progdir/\$program\"; then"
+
+	# fixup the dll searchpath if we need to.
+	#
+	# Fix the DLL searchpath if we need to.  Do this before prepending
+	# to shlibpath, because on Windows, both are PATH and uninstalled
+	# libraries must come first.
+	if test -n "$dllsearchpath"; then
+	  $ECHO "\
+    # Add the dll search path components to the executable PATH
+    PATH=$dllsearchpath:\$PATH
+"
+	fi
+
+	# Export our shlibpath_var if we have one.
+	if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+	  $ECHO "\
+    # Add our own library path to $shlibpath_var
+    $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
+
+    # Some systems cannot cope with colon-terminated $shlibpath_var
+    # The second colon is a workaround for a bug in BeOS R4 sed
+    $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\`
+
+    export $shlibpath_var
+"
+	fi
+
+	$ECHO "\
+    if test \"\$libtool_execute_magic\" != \"$magic\"; then
+      # Run the actual program with our arguments.
+      func_exec_program \${1+\"\$@\"}
+    fi
+  else
+    # The program doesn't exist.
+    \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
+    \$ECHO \"This script is just a wrapper for \$program.\" 1>&2
+    \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2
+    exit 1
   fi
-}
-# end: func_to_host_pathlist
+fi\
+"
+}
+
 
 # func_emit_cwrapperexe_src
@@ -3142,11 +4148,10 @@
    This wrapper executable should never be moved out of the build directory.
    If it is, it will not operate correctly.
-
-   Currently, it simply execs the wrapper *script* "$SHELL $output",
-   but could eventually absorb all of the scripts functionality and
-   exec $objdir/$outputname directly.
 */
 EOF
 	    cat <<"EOF"
+#ifdef _MSC_VER
+# define _CRT_SECURE_NO_DEPRECATE 1
+#endif
 #include <stdio.h>
 #include <stdlib.h>
@@ -3155,5 +4160,4 @@
 # include <process.h>
 # include <io.h>
-# define setmode _setmode
 #else
 # include <unistd.h>
@@ -3161,10 +4165,4 @@
 # ifdef __CYGWIN__
 #  include <io.h>
-#  define HAVE_SETENV
-#  ifdef __STRICT_ANSI__
-char *realpath (const char *, char *);
-int putenv (char *);
-int setenv (const char *, const char *, int);
-#  endif
 # endif
 #endif
@@ -3178,4 +4176,42 @@
 #include <sys/stat.h>
 
+/* declarations of non-ANSI functions */
+#if defined(__MINGW32__)
+# ifdef __STRICT_ANSI__
+int _putenv (const char *);
+# endif
+#elif defined(__CYGWIN__)
+# ifdef __STRICT_ANSI__
+char *realpath (const char *, char *);
+int putenv (char *);
+int setenv (const char *, const char *, int);
+# endif
+/* #elif defined (other platforms) ... */
+#endif
+
+/* portability defines, excluding path handling macros */
+#if defined(_MSC_VER)
+# define setmode _setmode
+# define stat    _stat
+# define chmod   _chmod
+# define getcwd  _getcwd
+# define putenv  _putenv
+# define S_IXUSR _S_IEXEC
+# ifndef _INTPTR_T_DEFINED
+#  define _INTPTR_T_DEFINED
+#  define intptr_t int
+# endif
+#elif defined(__MINGW32__)
+# define setmode _setmode
+# define stat    _stat
+# define chmod   _chmod
+# define getcwd  _getcwd
+# define putenv  _putenv
+#elif defined(__CYGWIN__)
+# define HAVE_SETENV
+# define FOPEN_WB "wb"
+/* #elif defined (other platforms) ... */
+#endif
+
 #if defined(PATH_MAX)
 # define LT_PATHMAX PATH_MAX
@@ -3193,12 +4229,5 @@
 #endif
 
-#ifdef _MSC_VER
-# define S_IXUSR _S_IEXEC
-# define stat _stat
-# ifndef _INTPTR_T_DEFINED
-#  define intptr_t int
-# endif
-#endif
-
+/* path handling portability macros */
 #ifndef DIR_SEPARATOR
 # define DIR_SEPARATOR '/'
@@ -3231,8 +4260,4 @@
 #endif /* PATH_SEPARATOR_2 */
 
-#ifdef __CYGWIN__
-# define FOPEN_WB "wb"
-#endif
-
 #ifndef FOPEN_WB
 # define FOPEN_WB "w"
@@ -3247,20 +4272,11 @@
 } while (0)
 
-#undef LTWRAPPER_DEBUGPRINTF
-#if defined DEBUGWRAPPER
-# define LTWRAPPER_DEBUGPRINTF(args) ltwrapper_debugprintf args
-static void
-ltwrapper_debugprintf (const char *fmt, ...)
-{
-    va_list args;
-    va_start (args, fmt);
-    (void) vfprintf (stderr, fmt, args);
-    va_end (args);
-}
+#if defined(LT_DEBUGWRAPPER)
+static int lt_debug = 1;
 #else
-# define LTWRAPPER_DEBUGPRINTF(args)
+static int lt_debug = 0;
 #endif
 
-const char *program_name = NULL;
+const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */
 
 void *xmalloc (size_t num);
@@ -3272,39 +4288,25 @@
 int check_executable (const char *path);
 char *strendzap (char *str, const char *pat);
-void lt_fatal (const char *message, ...);
+void lt_debugprintf (const char *file, int line, const char *fmt, ...);
+void lt_fatal (const char *file, int line, const char *message, ...);
+static const char *nonnull (const char *s);
+static const char *nonempty (const char *s);
 void lt_setenv (const char *name, const char *value);
 char *lt_extend_str (const char *orig_value, const char *add, int to_end);
-void lt_opt_process_env_set (const char *arg);
-void lt_opt_process_env_prepend (const char *arg);
-void lt_opt_process_env_append (const char *arg);
-int lt_split_name_value (const char *arg, char** name, char** value);
 void lt_update_exe_path (const char *name, const char *value);
 void lt_update_lib_path (const char *name, const char *value);
-
-static const char *script_text_part1 =
+char **prepare_spawn (char **argv);
+void lt_dump_script (FILE *f);
 EOF
 
-	    func_emit_wrapper_part1 yes |
-	        $SED -e 's/\([\\"]\)/\\\1/g' \
-	             -e 's/^/  "/' -e 's/$/\\n"/'
-	    echo ";"
 	    cat <<EOF
-
-static const char *script_text_part2 =
-EOF
-	    func_emit_wrapper_part2 yes |
-	        $SED -e 's/\([\\"]\)/\\\1/g' \
-	             -e 's/^/  "/' -e 's/$/\\n"/'
-	    echo ";"
-
-	    cat <<EOF
-const char * MAGIC_EXE = "$magic_exe";
+volatile const char * MAGIC_EXE = "$magic_exe";
 const char * LIB_PATH_VARNAME = "$shlibpath_var";
 EOF
 
 	    if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
-              func_to_host_pathlist "$temp_rpath"
+              func_to_host_path "$temp_rpath"
 	      cat <<EOF
-const char * LIB_PATH_VALUE   = "$func_to_host_pathlist_result";
+const char * LIB_PATH_VALUE   = "$func_to_host_path_result";
 EOF
 	    else
@@ -3315,8 +4317,8 @@
 
 	    if test -n "$dllsearchpath"; then
-              func_to_host_pathlist "$dllsearchpath:"
+              func_to_host_path "$dllsearchpath:"
 	      cat <<EOF
 const char * EXE_PATH_VARNAME = "PATH";
-const char * EXE_PATH_VALUE   = "$func_to_host_pathlist_result";
+const char * EXE_PATH_VALUE   = "$func_to_host_path_result";
 EOF
 	    else
@@ -3341,22 +4343,8 @@
 
 #define LTWRAPPER_OPTION_PREFIX         "--lt-"
-#define LTWRAPPER_OPTION_PREFIX_LENGTH  5
-
-static const size_t opt_prefix_len         = LTWRAPPER_OPTION_PREFIX_LENGTH;
+
 static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;
-
 static const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX "dump-script";
-
-static const size_t env_set_opt_len     = LTWRAPPER_OPTION_PREFIX_LENGTH + 7;
-static const char *env_set_opt          = LTWRAPPER_OPTION_PREFIX "env-set";
-  /* argument is putenv-style "foo=bar", value of foo is set to bar */
-
-static const size_t env_prepend_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 11;
-static const char *env_prepend_opt      = LTWRAPPER_OPTION_PREFIX "env-prepend";
-  /* argument is putenv-style "foo=bar", new value of foo is bar${foo} */
-
-static const size_t env_append_opt_len  = LTWRAPPER_OPTION_PREFIX_LENGTH + 10;
-static const char *env_append_opt       = LTWRAPPER_OPTION_PREFIX "env-append";
-  /* argument is putenv-style "foo=bar", new value of foo is ${foo}bar */
+static const char *debug_opt            = LTWRAPPER_OPTION_PREFIX "debug";
 
 int
@@ -3375,8 +4363,11 @@
 
   program_name = (char *) xstrdup (base_name (argv[0]));
-  LTWRAPPER_DEBUGPRINTF (("(main) argv[0]      : %s\n", argv[0]));
-  LTWRAPPER_DEBUGPRINTF (("(main) program_name : %s\n", program_name));
-
-  /* very simple arg parsing; don't want to rely on getopt */
+  newargz = XMALLOC (char *, argc + 1);
+
+  /* very simple arg parsing; don't want to rely on getopt
+   * also, copy all non cwrapper options to newargz, except
+   * argz[0], which is handled differently
+   */
+  newargc=0;
   for (i = 1; i < argc; i++)
     {
@@ -3392,23 +4383,55 @@
 
 	    cat <<"EOF"
-	  printf ("%s", script_text_part1);
-	  printf ("%s", script_text_part2);
+	  lt_dump_script (stdout);
 	  return 0;
 	}
+      if (strcmp (argv[i], debug_opt) == 0)
+	{
+          lt_debug = 1;
+          continue;
+	}
+      if (strcmp (argv[i], ltwrapper_option_prefix) == 0)
+        {
+          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX
+             namespace, but it is not one of the ones we know about and
+             have already dealt with, above (inluding dump-script), then
+             report an error. Otherwise, targets might begin to believe
+             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX
+             namespace. The first time any user complains about this, we'll
+             need to make LTWRAPPER_OPTION_PREFIX a configure-time option
+             or a configure.ac-settable value.
+           */
+          lt_fatal (__FILE__, __LINE__,
+		    "unrecognized %s option: '%s'",
+                    ltwrapper_option_prefix, argv[i]);
+        }
+      /* otherwise ... */
+      newargz[++newargc] = xstrdup (argv[i]);
     }
-
-  newargz = XMALLOC (char *, argc + 1);
+  newargz[++newargc] = NULL;
+
+EOF
+	    cat <<EOF
+  /* The GNU banner must be the first non-error debug message */
+  lt_debugprintf (__FILE__, __LINE__, "libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\n");
+EOF
+	    cat <<"EOF"
+  lt_debugprintf (__FILE__, __LINE__, "(main) argv[0]: %s\n", argv[0]);
+  lt_debugprintf (__FILE__, __LINE__, "(main) program_name: %s\n", program_name);
+
   tmp_pathspec = find_executable (argv[0]);
   if (tmp_pathspec == NULL)
-    lt_fatal ("Couldn't find %s", argv[0]);
-  LTWRAPPER_DEBUGPRINTF (("(main) found exe (before symlink chase) at : %s\n",
-			  tmp_pathspec));
+    lt_fatal (__FILE__, __LINE__, "couldn't find %s", argv[0]);
+  lt_debugprintf (__FILE__, __LINE__,
+                  "(main) found exe (before symlink chase) at: %s\n",
+		  tmp_pathspec);
 
   actual_cwrapper_path = chase_symlinks (tmp_pathspec);
-  LTWRAPPER_DEBUGPRINTF (("(main) found exe (after symlink chase) at : %s\n",
-			  actual_cwrapper_path));
+  lt_debugprintf (__FILE__, __LINE__,
+                  "(main) found exe (after symlink chase) at: %s\n",
+		  actual_cwrapper_path);
   XFREE (tmp_pathspec);
 
-  actual_cwrapper_name = xstrdup( base_name (actual_cwrapper_path));
+  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));
   strendzap (actual_cwrapper_path, actual_cwrapper_name);
 
@@ -3428,6 +4451,7 @@
   tmp_pathspec = 0;
 
-  LTWRAPPER_DEBUGPRINTF (("(main) libtool target name: %s\n",
-			  target_name));
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(main) libtool target name: %s\n",
+		  target_name);
 EOF
 
@@ -3479,78 +4503,17 @@
   lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */
   lt_setenv ("DUALCASE", "1");  /* for MSK sh */
+  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must
+     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)
+     because on Windows, both *_VARNAMEs are PATH but uninstalled
+     libraries must come first. */
+  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);
   lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);
-  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);
-
-  newargc=0;
-  for (i = 1; i < argc; i++)
-    {
-      if (strncmp (argv[i], env_set_opt, env_set_opt_len) == 0)
-        {
-          if (argv[i][env_set_opt_len] == '=')
-            {
-              const char *p = argv[i] + env_set_opt_len + 1;
-              lt_opt_process_env_set (p);
-            }
-          else if (argv[i][env_set_opt_len] == '\0' && i + 1 < argc)
-            {
-              lt_opt_process_env_set (argv[++i]); /* don't copy */
-            }
-          else
-            lt_fatal ("%s missing required argument", env_set_opt);
-          continue;
-        }
-      if (strncmp (argv[i], env_prepend_opt, env_prepend_opt_len) == 0)
-        {
-          if (argv[i][env_prepend_opt_len] == '=')
-            {
-              const char *p = argv[i] + env_prepend_opt_len + 1;
-              lt_opt_process_env_prepend (p);
-            }
-          else if (argv[i][env_prepend_opt_len] == '\0' && i + 1 < argc)
-            {
-              lt_opt_process_env_prepend (argv[++i]); /* don't copy */
-            }
-          else
-            lt_fatal ("%s missing required argument", env_prepend_opt);
-          continue;
-        }
-      if (strncmp (argv[i], env_append_opt, env_append_opt_len) == 0)
-        {
-          if (argv[i][env_append_opt_len] == '=')
-            {
-              const char *p = argv[i] + env_append_opt_len + 1;
-              lt_opt_process_env_append (p);
-            }
-          else if (argv[i][env_append_opt_len] == '\0' && i + 1 < argc)
-            {
-              lt_opt_process_env_append (argv[++i]); /* don't copy */
-            }
-          else
-            lt_fatal ("%s missing required argument", env_append_opt);
-          continue;
-        }
-      if (strncmp (argv[i], ltwrapper_option_prefix, opt_prefix_len) == 0)
-        {
-          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX
-             namespace, but it is not one of the ones we know about and
-             have already dealt with, above (inluding dump-script), then
-             report an error. Otherwise, targets might begin to believe
-             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX
-             namespace. The first time any user complains about this, we'll
-             need to make LTWRAPPER_OPTION_PREFIX a configure-time option
-             or a configure.ac-settable value.
-           */
-          lt_fatal ("Unrecognized option in %s namespace: '%s'",
-                    ltwrapper_option_prefix, argv[i]);
-        }
-      /* otherwise ... */
-      newargz[++newargc] = xstrdup (argv[i]);
-    }
-  newargz[++newargc] = NULL;
-
-  LTWRAPPER_DEBUGPRINTF     (("(main) lt_argv_zero : %s\n", (lt_argv_zero ? lt_argv_zero : "<NULL>")));
+
+  lt_debugprintf (__FILE__, __LINE__, "(main) lt_argv_zero: %s\n",
+		  nonnull (lt_argv_zero));
   for (i = 0; i < newargc; i++)
     {
-      LTWRAPPER_DEBUGPRINTF (("(main) newargz[%d]   : %s\n", i, (newargz[i] ? newargz[i] : "<NULL>")));
+      lt_debugprintf (__FILE__, __LINE__, "(main) newargz[%d]: %s\n",
+		      i, nonnull (newargz[i]));
     }
 
@@ -3561,9 +4524,12 @@
 		cat <<"EOF"
   /* execv doesn't actually work on mingw as expected on unix */
+  newargz = prepare_spawn (newargz);
   rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);
   if (rval == -1)
     {
       /* failed to start process */
-      LTWRAPPER_DEBUGPRINTF (("(main) failed to launch target \"%s\": errno = %d\n", lt_argv_zero, errno));
+      lt_debugprintf (__FILE__, __LINE__,
+		      "(main) failed to launch target \"%s\": %s\n",
+		      lt_argv_zero, nonnull (strerror (errno)));
       return 127;
     }
@@ -3587,5 +4553,5 @@
   void *p = (void *) malloc (num);
   if (!p)
-    lt_fatal ("Memory exhausted");
+    lt_fatal (__FILE__, __LINE__, "memory exhausted");
 
   return p;
@@ -3621,6 +4587,6 @@
   struct stat st;
 
-  LTWRAPPER_DEBUGPRINTF (("(check_executable)  : %s\n",
-			  path ? (*path ? path : "EMPTY!") : "NULL!"));
+  lt_debugprintf (__FILE__, __LINE__, "(check_executable): %s\n",
+                  nonempty (path));
   if ((!path) || (!*path))
     return 0;
@@ -3639,6 +4605,6 @@
   struct stat st;
 
-  LTWRAPPER_DEBUGPRINTF (("(make_executable)   : %s\n",
-			  path ? (*path ? path : "EMPTY!") : "NULL!"));
+  lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n",
+                  nonempty (path));
   if ((!path) || (!*path))
     return 0;
@@ -3666,6 +4632,6 @@
   char *concat_name;
 
-  LTWRAPPER_DEBUGPRINTF (("(find_executable)   : %s\n",
-			  wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!"));
+  lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n",
+                  nonempty (wrapper));
 
   if ((wrapper == NULL) || (*wrapper == '\0'))
@@ -3720,5 +4686,6 @@
 		  /* empty path: current directory */
 		  if (getcwd (tmp, LT_PATHMAX) == NULL)
-		    lt_fatal ("getcwd failed");
+		    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
+                              nonnull (strerror (errno)));
 		  tmp_len = strlen (tmp);
 		  concat_name =
@@ -3745,5 +4712,6 @@
   /* Relative path | not found in path: prepend cwd */
   if (getcwd (tmp, LT_PATHMAX) == NULL)
-    lt_fatal ("getcwd failed");
+    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
+              nonnull (strerror (errno)));
   tmp_len = strlen (tmp);
   concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
@@ -3771,6 +4739,7 @@
   while (strlen (tmp_pathspec) && !has_symlinks)
     {
-      LTWRAPPER_DEBUGPRINTF (("checking path component for symlinks: %s\n",
-			      tmp_pathspec));
+      lt_debugprintf (__FILE__, __LINE__,
+		      "checking path component for symlinks: %s\n",
+		      tmp_pathspec);
       if (lstat (tmp_pathspec, &s) == 0)
 	{
@@ -3794,6 +4763,7 @@
       else
 	{
-	  char *errstr = strerror (errno);
-	  lt_fatal ("Error accessing file %s (%s)", tmp_pathspec, errstr);
+	  lt_fatal (__FILE__, __LINE__,
+		    "error accessing file \"%s\": %s",
+		    tmp_pathspec, nonnull (strerror (errno)));
 	}
     }
@@ -3808,5 +4778,6 @@
   if (tmp_pathspec == 0)
     {
-      lt_fatal ("Could not follow symlinks for %s", pathspec);
+      lt_fatal (__FILE__, __LINE__,
+		"could not follow symlinks for %s", pathspec);
     }
   return xstrdup (tmp_pathspec);
@@ -3834,9 +4805,23 @@
 }
 
+void
+lt_debugprintf (const char *file, int line, const char *fmt, ...)
+{
+  va_list args;
+  if (lt_debug)
+    {
+      (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line);
+      va_start (args, fmt);
+      (void) vfprintf (stderr, fmt, args);
+      va_end (args);
+    }
+}
+
 static void
-lt_error_core (int exit_status, const char *mode,
+lt_error_core (int exit_status, const char *file,
+	       int line, const char *mode,
 	       const char *message, va_list ap)
 {
-  fprintf (stderr, "%s: %s: ", program_name, mode);
+  fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode);
   vfprintf (stderr, message, ap);
   fprintf (stderr, ".\n");
@@ -3847,10 +4832,22 @@
 
 void
-lt_fatal (const char *message, ...)
+lt_fatal (const char *file, int line, const char *message, ...)
 {
   va_list ap;
   va_start (ap, message);
-  lt_error_core (EXIT_FAILURE, "FATAL", message, ap);
+  lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap);
   va_end (ap);
+}
+
+static const char *
+nonnull (const char *s)
+{
+  return s ? s : "(null)";
+}
+
+static const char *
+nonempty (const char *s)
+{
+  return (s && !*s) ? "(empty)" : nonnull (s);
 }
 
@@ -3858,7 +4855,7 @@
 lt_setenv (const char *name, const char *value)
 {
-  LTWRAPPER_DEBUGPRINTF (("(lt_setenv) setting '%s' to '%s'\n",
-                          (name ? name : "<NULL>"),
-                          (value ? value : "<NULL>")));
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_setenv) setting '%s' to '%s'\n",
+                  nonnull (name), nonnull (value));
   {
 #ifdef HAVE_SETENV
@@ -3905,93 +4902,10 @@
 }
 
-int
-lt_split_name_value (const char *arg, char** name, char** value)
-{
-  const char *p;
-  int len;
-  if (!arg || !*arg)
-    return 1;
-
-  p = strchr (arg, (int)'=');
-
-  if (!p)
-    return 1;
-
-  *value = xstrdup (++p);
-
-  len = strlen (arg) - strlen (*value);
-  *name = XMALLOC (char, len);
-  strncpy (*name, arg, len-1);
-  (*name)[len - 1] = '\0';
-
-  return 0;
-}
-
-void
-lt_opt_process_env_set (const char *arg)
-{
-  char *name = NULL;
-  char *value = NULL;
-
-  if (lt_split_name_value (arg, &name, &value) != 0)
-    {
-      XFREE (name);
-      XFREE (value);
-      lt_fatal ("bad argument for %s: '%s'", env_set_opt, arg);
-    }
-
-  lt_setenv (name, value);
-  XFREE (name);
-  XFREE (value);
-}
-
-void
-lt_opt_process_env_prepend (const char *arg)
-{
-  char *name = NULL;
-  char *value = NULL;
-  char *new_value = NULL;
-
-  if (lt_split_name_value (arg, &name, &value) != 0)
-    {
-      XFREE (name);
-      XFREE (value);
-      lt_fatal ("bad argument for %s: '%s'", env_prepend_opt, arg);
-    }
-
-  new_value = lt_extend_str (getenv (name), value, 0);
-  lt_setenv (name, new_value);
-  XFREE (new_value);
-  XFREE (name);
-  XFREE (value);
-}
-
-void
-lt_opt_process_env_append (const char *arg)
-{
-  char *name = NULL;
-  char *value = NULL;
-  char *new_value = NULL;
-
-  if (lt_split_name_value (arg, &name, &value) != 0)
-    {
-      XFREE (name);
-      XFREE (value);
-      lt_fatal ("bad argument for %s: '%s'", env_append_opt, arg);
-    }
-
-  new_value = lt_extend_str (getenv (name), value, 1);
-  lt_setenv (name, new_value);
-  XFREE (new_value);
-  XFREE (name);
-  XFREE (value);
-}
-
 void
 lt_update_exe_path (const char *name, const char *value)
 {
-  LTWRAPPER_DEBUGPRINTF (("(lt_update_exe_path) modifying '%s' by prepending '%s'\n",
-                          (name ? name : "<NULL>"),
-                          (value ? value : "<NULL>")));
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_update_exe_path) modifying '%s' by prepending '%s'\n",
+                  nonnull (name), nonnull (value));
 
   if (name && *name && value && *value)
@@ -4012,7 +4926,7 @@
 lt_update_lib_path (const char *name, const char *value)
 {
-  LTWRAPPER_DEBUGPRINTF (("(lt_update_lib_path) modifying '%s' by prepending '%s'\n",
-                          (name ? name : "<NULL>"),
-                          (value ? value : "<NULL>")));
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_update_lib_path) modifying '%s' by prepending '%s'\n",
+                  nonnull (name), nonnull (value));
 
   if (name && *name && value && *value)
@@ -4024,8 +4938,155 @@
 }
 
-
 EOF
+	    case $host_os in
+	      mingw*)
+		cat <<"EOF"
+
+/* Prepares an argument vector before calling spawn().
+   Note that spawn() does not by itself call the command interpreter
+     (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") :
+      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+         GetVersionEx(&v);
+         v.dwPlatformId == VER_PLATFORM_WIN32_NT;
+      }) ? "cmd.exe" : "command.com").
+   Instead it simply concatenates the arguments, separated by ' ', and calls
+   CreateProcess().  We must quote the arguments since Win32 CreateProcess()
+   interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a
+   special way:
+   - Space and tab are interpreted as delimiters. They are not treated as
+     delimiters if they are surrounded by double quotes: "...".
+   - Unescaped double quotes are removed from the input. Their only effect is
+     that within double quotes, space and tab are treated like normal
+     characters.
+   - Backslashes not followed by double quotes are not special.
+   - But 2*n+1 backslashes followed by a double quote become
+     n backslashes followed by a double quote (n >= 0):
+       \" -> "
+       \\\" -> \"
+       \\\\\" -> \\"
+ */
+#define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
+#define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
+char **
+prepare_spawn (char **argv)
+{
+  size_t argc;
+  char **new_argv;
+  size_t i;
+
+  /* Count number of arguments.  */
+  for (argc = 0; argv[argc] != NULL; argc++)
+    ;
+
+  /* Allocate new argument vector.  */
+  new_argv = XMALLOC (char *, argc + 1);
+
+  /* Put quoted arguments into the new argument vector.  */
+  for (i = 0; i < argc; i++)
+    {
+      const char *string = argv[i];
+
+      if (string[0] == '\0')
+	new_argv[i] = xstrdup ("\"\"");
+      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)
+	{
+	  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);
+	  size_t length;
+	  unsigned int backslashes;
+	  const char *s;
+	  char *quoted_string;
+	  char *p;
+
+	  length = 0;
+	  backslashes = 0;
+	  if (quote_around)
+	    length++;
+	  for (s = string; *s != '\0'; s++)
+	    {
+	      char c = *s;
+	      if (c == '"')
+		length += backslashes + 1;
+	      length++;
+	      if (c == '\\')
+		backslashes++;
+	      else
+		backslashes = 0;
+	    }
+	  if (quote_around)
+	    length += backslashes + 1;
+
+	  quoted_string = XMALLOC (char, length + 1);
+
+	  p = quoted_string;
+	  backslashes = 0;
+	  if (quote_around)
+	    *p++ = '"';
+	  for (s = string; *s != '\0'; s++)
+	    {
+	      char c = *s;
+	      if (c == '"')
+		{
+		  unsigned int j;
+		  for (j = backslashes + 1; j > 0; j--)
+		    *p++ = '\\';
+		}
+	      *p++ = c;
+	      if (c == '\\')
+		backslashes++;
+	      else
+		backslashes = 0;
+	    }
+	  if (quote_around)
+	    {
+	      unsigned int j;
+	      for (j = backslashes; j > 0; j--)
+		*p++ = '\\';
+	      *p++ = '"';
+	    }
+	  *p = '\0';
+
+	  new_argv[i] = quoted_string;
+	}
+      else
+	new_argv[i] = (char *) string;
+    }
+  new_argv[argc] = NULL;
+
+  return new_argv;
+}
+EOF
+		;;
+	    esac
+
+            cat <<"EOF"
+void lt_dump_script (FILE* f)
+{
+EOF
+	    func_emit_wrapper yes |
+	      $SED -n -e '
+s/^\(.\{79\}\)\(..*\)/\1\
+\2/
+h
+s/\([\\"]\)/\\\1/g
+s/$/\\n/
+s/\([^\n]*\).*/  fputs ("\1", f);/p
+g
+D'
+            cat <<"EOF"
+}
+EOF
 }
 # end: func_emit_cwrapperexe_src
+
+# func_win32_import_lib_p ARG
+# True if ARG is an import lib, as indicated by $file_magic_cmd
+func_win32_import_lib_p ()
+{
+    $opt_debug
+    case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in
+    *import*) : ;;
+    *) false ;;
+    esac
+}
 
 # func_mode_link arg...
@@ -4073,4 +5134,5 @@
 
     avoid_version=no
+    bindir=
     dlfiles=
     dlprefiles=
@@ -4165,4 +5227,9 @@
 
 	case $prev in
+	bindir)
+	  bindir="$arg"
+	  prev=
+	  continue
+	  ;;
 	dlfiles|dlprefiles)
 	  if test "$preload" = no; then
@@ -4196,7 +5263,7 @@
 	  *)
 	    if test "$prev" = dlfiles; then
-	      dlfiles="$dlfiles $arg"
+	      func_append dlfiles " $arg"
 	    else
-	      dlprefiles="$dlprefiles $arg"
+	      func_append dlprefiles " $arg"
 	    fi
 	    prev=
@@ -4222,5 +5289,5 @@
 	      case "$deplibs " in
 		*" $qarg.ltframework "*) ;;
-		*) deplibs="$deplibs $qarg.ltframework" # this is fixed later
+		*) func_append deplibs " $qarg.ltframework" # this is fixed later
 		   ;;
 	      esac
@@ -4241,5 +5308,5 @@
 	    for fil in `cat "$save_arg"`
 	    do
-#	      moreargs="$moreargs $fil"
+#	      func_append moreargs " $fil"
 	      arg=$fil
 	      # A libtool-controlled object.
@@ -4270,5 +5337,5 @@
 		  if test "$prev" = dlfiles; then
 		    if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
-		      dlfiles="$dlfiles $pic_object"
+		      func_append dlfiles " $pic_object"
 		      prev=
 		      continue
@@ -4282,5 +5349,5 @@
 		  if test "$prev" = dlprefiles; then
 		    # Preload the old-style object.
-		    dlprefiles="$dlprefiles $pic_object"
+		    func_append dlprefiles " $pic_object"
 		    prev=
 		  fi
@@ -4352,10 +5419,10 @@
 	    case "$rpath " in
 	    *" $arg "*) ;;
-	    *) rpath="$rpath $arg" ;;
+	    *) func_append rpath " $arg" ;;
 	    esac
 	  else
 	    case "$xrpath " in
 	    *" $arg "*) ;;
-	    *) xrpath="$xrpath $arg" ;;
+	    *) func_append xrpath " $arg" ;;
 	    esac
 	  fi
@@ -4369,11 +5436,11 @@
 	  ;;
 	weak)
-	  weak_libs="$weak_libs $arg"
+	  func_append weak_libs " $arg"
 	  prev=
 	  continue
 	  ;;
 	xcclinker)
-	  linker_flags="$linker_flags $qarg"
-	  compiler_flags="$compiler_flags $qarg"
+	  func_append linker_flags " $qarg"
+	  func_append compiler_flags " $qarg"
 	  prev=
 	  func_append compile_command " $qarg"
@@ -4382,5 +5449,5 @@
 	  ;;
 	xcompiler)
-	  compiler_flags="$compiler_flags $qarg"
+	  func_append compiler_flags " $qarg"
 	  prev=
 	  func_append compile_command " $qarg"
@@ -4389,6 +5456,6 @@
 	  ;;
 	xlinker)
-	  linker_flags="$linker_flags $qarg"
-	  compiler_flags="$compiler_flags $wl$qarg"
+	  func_append linker_flags " $qarg"
+	  func_append compiler_flags " $wl$qarg"
 	  prev=
 	  func_append compile_command " $wl$qarg"
@@ -4426,4 +5493,9 @@
 	;;
 
+      -bindir)
+	prev=bindir
+	continue
+	;;
+
       -dlopen)
 	prev=dlfiles
@@ -4476,7 +5548,6 @@
 
       -L*)
-	func_stripname '-L' '' "$arg"
-	dir=$func_stripname_result
-	if test -z "$dir"; then
+	func_stripname "-L" '' "$arg"
+	if test -z "$func_stripname_result"; then
 	  if test "$#" -gt 0; then
 	    func_fatal_error "require no space between \`-L' and \`$1'"
@@ -4485,4 +5556,6 @@
 	  fi
 	fi
+	func_resolve_sysroot "$func_stripname_result"
+	dir=$func_resolve_sysroot_result
 	# We need an absolute path.
 	case $dir in
@@ -4496,22 +5569,28 @@
 	esac
 	case "$deplibs " in
-	*" -L$dir "*) ;;
+	*" -L$dir "* | *" $arg "*)
+	  # Will only happen for absolute or sysroot arguments
+	  ;;
 	*)
-	  deplibs="$deplibs -L$dir"
-	  lib_search_path="$lib_search_path $dir"
+	  # Preserve sysroot, but never include relative directories
+	  case $dir in
+	    [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;;
+	    *) func_append deplibs " -L$dir" ;;
+	  esac
+	  func_append lib_search_path " $dir"
 	  ;;
 	esac
 	case $host in
 	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
-	  testbindir=`$ECHO "X$dir" | $Xsed -e 's*/lib$*/bin*'`
+	  testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'`
 	  case :$dllsearchpath: in
 	  *":$dir:"*) ;;
 	  ::) dllsearchpath=$dir;;
-	  *) dllsearchpath="$dllsearchpath:$dir";;
+	  *) func_append dllsearchpath ":$dir";;
 	  esac
 	  case :$dllsearchpath: in
 	  *":$testbindir:"*) ;;
 	  ::) dllsearchpath=$testbindir;;
-	  *) dllsearchpath="$dllsearchpath:$testbindir";;
+	  *) func_append dllsearchpath ":$testbindir";;
 	  esac
 	  ;;
@@ -4523,5 +5602,5 @@
 	if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
 	  case $host in
-	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc*)
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)
 	    # These systems don't actually have a C or math library (as such)
 	    continue
@@ -4537,5 +5616,5 @@
 	  *-*-rhapsody* | *-*-darwin1.[012])
 	    # Rhapsody C and math libraries are in the System framework
-	    deplibs="$deplibs System.ltframework"
+	    func_append deplibs " System.ltframework"
 	    continue
 	    ;;
@@ -4557,5 +5636,5 @@
 	 esac
 	fi
-	deplibs="$deplibs $arg"
+	func_append deplibs " $arg"
 	continue
 	;;
@@ -4569,6 +5648,6 @@
       # classes, name mangling, and exception handling.
       # Darwin uses the -arch flag to determine output architecture.
-      -model|-arch|-isysroot)
-	compiler_flags="$compiler_flags $arg"
+      -model|-arch|-isysroot|--sysroot)
+	func_append compiler_flags " $arg"
 	func_append compile_command " $arg"
 	func_append finalize_command " $arg"
@@ -4577,11 +5656,12 @@
 	;;
 
-      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads)
-	compiler_flags="$compiler_flags $arg"
+      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
+      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
+	func_append compiler_flags " $arg"
 	func_append compile_command " $arg"
 	func_append finalize_command " $arg"
 	case "$new_inherited_linker_flags " in
 	    *" $arg "*) ;;
-	    * ) new_inherited_linker_flags="$new_inherited_linker_flags $arg" ;;
+	    * ) func_append new_inherited_linker_flags " $arg" ;;
 	esac
 	continue
@@ -4650,4 +5730,8 @@
 	case $dir in
 	[\\/]* | [A-Za-z]:[\\/]*) ;;
+	=*)
+	  func_stripname '=' '' "$dir"
+	  dir=$lt_sysroot$func_stripname_result
+	  ;;
 	*)
 	  func_fatal_error "only absolute run-paths are allowed"
@@ -4656,5 +5740,5 @@
 	case "$xrpath " in
 	*" $dir "*) ;;
-	*) xrpath="$xrpath $dir" ;;
+	*) func_append xrpath " $dir" ;;
 	esac
 	continue
@@ -4709,6 +5793,6 @@
 	  IFS="$save_ifs"
           func_quote_for_eval "$flag"
-	  arg="$arg $wl$func_quote_for_eval_result"
-	  compiler_flags="$compiler_flags $func_quote_for_eval_result"
+	  func_append arg " $func_quote_for_eval_result"
+	  func_append compiler_flags " $func_quote_for_eval_result"
 	done
 	IFS="$save_ifs"
@@ -4725,7 +5809,7 @@
 	  IFS="$save_ifs"
           func_quote_for_eval "$flag"
-	  arg="$arg $wl$func_quote_for_eval_result"
-	  compiler_flags="$compiler_flags $wl$func_quote_for_eval_result"
-	  linker_flags="$linker_flags $func_quote_for_eval_result"
+	  func_append arg " $wl$func_quote_for_eval_result"
+	  func_append compiler_flags " $wl$func_quote_for_eval_result"
+	  func_append linker_flags " $func_quote_for_eval_result"
 	done
 	IFS="$save_ifs"
@@ -4755,21 +5839,25 @@
 	;;
 
-      # -64, -mips[0-9] enable 64-bit mode on the SGI compiler
-      # -r[0-9][0-9]* specifies the processor on the SGI compiler
-      # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler
-      # +DA*, +DD* enable 64-bit mode on the HP compiler
-      # -q* pass through compiler args for the IBM compiler
-      # -m*, -t[45]*, -txscale* pass through architecture-specific
-      # compiler args for GCC
-      # -F/path gives path to uninstalled frameworks, gcc on darwin
-      # -p, -pg, --coverage, -fprofile-* pass through profiling flag for GCC
-      # @file GCC response files
+      # Flags to be passed through unchanged, with rationale:
+      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler
+      # -r[0-9][0-9]*        specify processor for the SGI compiler
+      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler
+      # +DA*, +DD*           enable 64-bit mode for the HP compiler
+      # -q*                  compiler args for the IBM compiler
+      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC
+      # -F/path              path to uninstalled frameworks, gcc on darwin
+      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC
+      # @file                GCC response files
+      # -tp=*                Portland pgcc target processor selection
+      # --sysroot=*          for sysroot support
+      # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization
       -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \
-      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*)
+      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \
+      -O*|-flto*|-fwhopr*|-fuse-linker-plugin)
         func_quote_for_eval "$arg"
 	arg="$func_quote_for_eval_result"
         func_append compile_command " $arg"
         func_append finalize_command " $arg"
-        compiler_flags="$compiler_flags $arg"
+        func_append compiler_flags " $arg"
         continue
         ;;
@@ -4783,5 +5871,5 @@
       *.$objext)
 	# A standard object.
-	objs="$objs $arg"
+	func_append objs " $arg"
 	;;
 
@@ -4814,5 +5902,5 @@
 	    if test "$prev" = dlfiles; then
 	      if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
-		dlfiles="$dlfiles $pic_object"
+		func_append dlfiles " $pic_object"
 		prev=
 		continue
@@ -4826,5 +5914,5 @@
 	    if test "$prev" = dlprefiles; then
 	      # Preload the old-style object.
-	      dlprefiles="$dlprefiles $pic_object"
+	      func_append dlprefiles " $pic_object"
 	      prev=
 	    fi
@@ -4871,6 +5959,6 @@
       *.$libext)
 	# An archive.
-	deplibs="$deplibs $arg"
-	old_deplibs="$old_deplibs $arg"
+	func_append deplibs " $arg"
+	func_append old_deplibs " $arg"
 	continue
 	;;
@@ -4879,14 +5967,15 @@
 	# A libtool-controlled library.
 
+	func_resolve_sysroot "$arg"
 	if test "$prev" = dlfiles; then
 	  # This library was specified with -dlopen.
-	  dlfiles="$dlfiles $arg"
+	  func_append dlfiles " $func_resolve_sysroot_result"
 	  prev=
 	elif test "$prev" = dlprefiles; then
 	  # The library was specified with -dlpreopen.
-	  dlprefiles="$dlprefiles $arg"
+	  func_append dlprefiles " $func_resolve_sysroot_result"
 	  prev=
 	else
-	  deplibs="$deplibs $arg"
+	  func_append deplibs " $func_resolve_sysroot_result"
 	fi
 	continue
@@ -4926,5 +6015,5 @@
     if test -n "$shlibpath_var"; then
       # get the directories listed in $shlibpath_var
-      eval shlib_search_path=\`\$ECHO \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\`
+      eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\`
     else
       shlib_search_path=
@@ -4935,4 +6024,6 @@
     func_dirname "$output" "/" ""
     output_objdir="$func_dirname_result$objdir"
+    func_to_tool_file "$output_objdir/"
+    tool_output_objdir=$func_to_tool_file_result
     # Create the object directory.
     func_mkdir_p "$output_objdir"
@@ -4955,10 +6046,10 @@
     # that are linked more than once (e.g. -la -lb -la)
     for deplib in $deplibs; do
-      if $opt_duplicate_deps ; then
+      if $opt_preserve_dup_deps ; then
 	case "$libs " in
-	*" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+	*" $deplib "*) func_append specialdeplibs " $deplib" ;;
 	esac
       fi
-      libs="$libs $deplib"
+      func_append libs " $deplib"
     done
 
@@ -4973,7 +6064,7 @@
 	for pre_post_dep in $predeps $postdeps; do
 	  case "$pre_post_deps " in
-	  *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;;
+	  *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;;
 	  esac
-	  pre_post_deps="$pre_post_deps $pre_post_dep"
+	  func_append pre_post_deps " $pre_post_dep"
 	done
       fi
@@ -5042,6 +6133,7 @@
 	  # Ignore non-libtool-libs
 	  dependency_libs=
+	  func_resolve_sysroot "$lib"
 	  case $lib in
-	  *.la)	func_source "$lib" ;;
+	  *.la)	func_source "$func_resolve_sysroot_result" ;;
 	  esac
 
@@ -5049,8 +6141,9 @@
 	  # has declared as weak libs
 	  for deplib in $dependency_libs; do
-            deplib_base=`$ECHO "X$deplib" | $Xsed -e "$basename"`
+	    func_basename "$deplib"
+            deplib_base=$func_basename_result
 	    case " $weak_libs " in
 	    *" $deplib_base "*) ;;
-	    *) deplibs="$deplibs $deplib" ;;
+	    *) func_append deplibs " $deplib" ;;
 	    esac
 	  done
@@ -5068,14 +6161,15 @@
 	found=no
 	case $deplib in
-	-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads)
+	-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
+        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
 	  if test "$linkmode,$pass" = "prog,link"; then
 	    compile_deplibs="$deplib $compile_deplibs"
 	    finalize_deplibs="$deplib $finalize_deplibs"
 	  else
-	    compiler_flags="$compiler_flags $deplib"
+	    func_append compiler_flags " $deplib"
 	    if test "$linkmode" = lib ; then
 		case "$new_inherited_linker_flags " in
 		    *" $deplib "*) ;;
-		    * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;;
+		    * ) func_append new_inherited_linker_flags " $deplib" ;;
 		esac
 	    fi
@@ -5162,5 +6256,5 @@
 		case "$new_inherited_linker_flags " in
 		    *" $deplib "*) ;;
-		    * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;;
+		    * ) func_append new_inherited_linker_flags " $deplib" ;;
 		esac
 	    fi
@@ -5175,5 +6269,6 @@
 	    newdependency_libs="$deplib $newdependency_libs"
 	    func_stripname '-L' '' "$deplib"
-	    newlib_search_path="$newlib_search_path $func_stripname_result"
+	    func_resolve_sysroot "$func_stripname_result"
+	    func_append newlib_search_path " $func_resolve_sysroot_result"
 	    ;;
 	  prog)
@@ -5189,5 +6284,6 @@
 	    fi
 	    func_stripname '-L' '' "$deplib"
-	    newlib_search_path="$newlib_search_path $func_stripname_result"
+	    func_resolve_sysroot "$func_stripname_result"
+	    func_append newlib_search_path " $func_resolve_sysroot_result"
 	    ;;
 	  *)
@@ -5200,9 +6296,10 @@
 	  if test "$pass" = link; then
 	    func_stripname '-R' '' "$deplib"
-	    dir=$func_stripname_result
+	    func_resolve_sysroot "$func_stripname_result"
+	    dir=$func_resolve_sysroot_result
 	    # Make sure the xrpath contains only unique directories.
 	    case "$xrpath " in
 	    *" $dir "*) ;;
-	    *) xrpath="$xrpath $dir" ;;
+	    *) func_append xrpath " $dir" ;;
 	    esac
 	  fi
@@ -5210,5 +6307,8 @@
 	  continue
 	  ;;
-	*.la) lib="$deplib" ;;
+	*.la)
+	  func_resolve_sysroot "$deplib"
+	  lib=$func_resolve_sysroot_result
+	  ;;
 	*.$libext)
 	  if test "$pass" = conv; then
@@ -5228,5 +6328,5 @@
 		  set dummy $deplibs_check_method; shift
 		  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
-		  if eval "\$ECHO \"X$deplib\"" 2>/dev/null | $Xsed -e 10q \
+		  if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \
 		    | $EGREP "$match_pattern_regex" > /dev/null; then
 		    valid_a_lib=yes
@@ -5238,13 +6338,13 @@
 	      esac
 	      if test "$valid_a_lib" != yes; then
-		$ECHO
+		echo
 		$ECHO "*** Warning: Trying to link with static lib archive $deplib."
-		$ECHO "*** I have the capability to make that library automatically link in when"
-		$ECHO "*** you link to this library.  But I can only do this if you have a"
-		$ECHO "*** shared version of the library, which you do not appear to have"
-		$ECHO "*** because the file extensions .$libext of this argument makes me believe"
-		$ECHO "*** that it is just a static archive that I should not use here."
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because the file extensions .$libext of this argument makes me believe"
+		echo "*** that it is just a static archive that I should not use here."
 	      else
-		$ECHO
+		echo
 		$ECHO "*** Warning: Linking the shared library $output against the"
 		$ECHO "*** static library $deplib is not portable!"
@@ -5273,9 +6373,9 @@
 	      # If there is no dlopen support or we're linking statically,
 	      # we need to preload.
-	      newdlprefiles="$newdlprefiles $deplib"
+	      func_append newdlprefiles " $deplib"
 	      compile_deplibs="$deplib $compile_deplibs"
 	      finalize_deplibs="$deplib $finalize_deplibs"
 	    else
-	      newdlfiles="$newdlfiles $deplib"
+	      func_append newdlfiles " $deplib"
 	    fi
 	  fi
@@ -5319,18 +6419,18 @@
 	# Convert "-framework foo" to "foo.ltframework"
 	if test -n "$inherited_linker_flags"; then
-	  tmp_inherited_linker_flags=`$ECHO "X$inherited_linker_flags" | $Xsed -e 's/-framework \([^ $]*\)/\1.ltframework/g'`
+	  tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'`
 	  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do
 	    case " $new_inherited_linker_flags " in
 	      *" $tmp_inherited_linker_flag "*) ;;
-	      *) new_inherited_linker_flags="$new_inherited_linker_flags $tmp_inherited_linker_flag";;
+	      *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";;
 	    esac
 	  done
 	fi
-	dependency_libs=`$ECHO "X $dependency_libs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
 	if test "$linkmode,$pass" = "lib,link" ||
 	   test "$linkmode,$pass" = "prog,scan" ||
 	   { test "$linkmode" != prog && test "$linkmode" != lib; }; then
-	  test -n "$dlopen" && dlfiles="$dlfiles $dlopen"
-	  test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen"
+	  test -n "$dlopen" && func_append dlfiles " $dlopen"
+	  test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen"
 	fi
 
@@ -5343,6 +6443,6 @@
 	    fi
 	    # It is a libtool convenience library, so add in its objects.
-	    convenience="$convenience $ladir/$objdir/$old_library"
-	    old_convenience="$old_convenience $ladir/$objdir/$old_library"
+	    func_append convenience " $ladir/$objdir/$old_library"
+	    func_append old_convenience " $ladir/$objdir/$old_library"
 	  elif test "$linkmode" != prog && test "$linkmode" != lib; then
 	    func_fatal_error "\`$lib' is not a convenience library"
@@ -5351,10 +6451,10 @@
 	  for deplib in $dependency_libs; do
 	    deplibs="$deplib $deplibs"
-	    if $opt_duplicate_deps ; then
+	    if $opt_preserve_dup_deps ; then
 	      case "$tmp_libs " in
-	      *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
 	      esac
 	    fi
-	    tmp_libs="$tmp_libs $deplib"
+	    func_append tmp_libs " $deplib"
 	  done
 	  continue
@@ -5364,7 +6464,13 @@
 	# Get the name of the library we link against.
 	linklib=
-	for l in $old_library $library_names; do
-	  linklib="$l"
-	done
+	if test -n "$old_library" &&
+	   { test "$prefer_static_libs" = yes ||
+	     test "$prefer_static_libs,$installed" = "built,no"; }; then
+	  linklib=$old_library
+	else
+	  for l in $old_library $library_names; do
+	    linklib="$l"
+	  done
+	fi
 	if test -z "$linklib"; then
 	  func_fatal_error "cannot find name of link library for \`$lib'"
@@ -5383,7 +6489,7 @@
 	    # dependent libraries so libltdl's deplib preloader doesn't
 	    # bomb out in the load deplibs phase.
-	    dlprefiles="$dlprefiles $lib $dependency_libs"
+	    func_append dlprefiles " $lib $dependency_libs"
 	  else
-	    newdlfiles="$newdlfiles $lib"
+	    func_append newdlfiles " $lib"
 	  fi
 	  continue
@@ -5407,5 +6513,5 @@
 	# Find the relevant object directory and library name.
 	if test "X$installed" = Xyes; then
-	  if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+	  if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
 	    func_warning "library \`$lib' was moved."
 	    dir="$ladir"
@@ -5413,6 +6519,6 @@
 	    libdir="$abs_ladir"
 	  else
-	    dir="$libdir"
-	    absdir="$libdir"
+	    dir="$lt_sysroot$libdir"
+	    absdir="$lt_sysroot$libdir"
 	  fi
 	  test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
@@ -5422,10 +6528,10 @@
 	    absdir="$abs_ladir"
 	    # Remove this search path later
-	    notinst_path="$notinst_path $abs_ladir"
+	    func_append notinst_path " $abs_ladir"
 	  else
 	    dir="$ladir/$objdir"
 	    absdir="$abs_ladir/$objdir"
 	    # Remove this search path later
-	    notinst_path="$notinst_path $abs_ladir"
+	    func_append notinst_path " $abs_ladir"
 	  fi
 	fi # $installed = yes
@@ -5438,18 +6544,44 @@
 	    func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'"
 	  fi
-	  # Prefer using a static library (so that no silly _DYNAMIC symbols
-	  # are required to link).
-	  if test -n "$old_library"; then
-	    newdlprefiles="$newdlprefiles $dir/$old_library"
-	    # Keep a list of preopened convenience libraries to check
-	    # that they are being used correctly in the link pass.
-	    test -z "$libdir" && \
-		dlpreconveniencelibs="$dlpreconveniencelibs $dir/$old_library"
-	  # Otherwise, use the dlname, so that lt_dlopen finds it.
-	  elif test -n "$dlname"; then
-	    newdlprefiles="$newdlprefiles $dir/$dlname"
-	  else
-	    newdlprefiles="$newdlprefiles $dir/$linklib"
-	  fi
+	  case "$host" in
+	    # special handling for platforms with PE-DLLs.
+	    *cygwin* | *mingw* | *cegcc* )
+	      # Linker will automatically link against shared library if both
+	      # static and shared are present.  Therefore, ensure we extract
+	      # symbols from the import library if a shared library is present
+	      # (otherwise, the dlopen module name will be incorrect).  We do
+	      # this by putting the import library name into $newdlprefiles.
+	      # We recover the dlopen module name by 'saving' the la file
+	      # name in a special purpose variable, and (later) extracting the
+	      # dlname from the la file.
+	      if test -n "$dlname"; then
+	        func_tr_sh "$dir/$linklib"
+	        eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname"
+	        func_append newdlprefiles " $dir/$linklib"
+	      else
+	        func_append newdlprefiles " $dir/$old_library"
+	        # Keep a list of preopened convenience libraries to check
+	        # that they are being used correctly in the link pass.
+	        test -z "$libdir" && \
+	          func_append dlpreconveniencelibs " $dir/$old_library"
+	      fi
+	    ;;
+	    * )
+	      # Prefer using a static library (so that no silly _DYNAMIC symbols
+	      # are required to link).
+	      if test -n "$old_library"; then
+	        func_append newdlprefiles " $dir/$old_library"
+	        # Keep a list of preopened convenience libraries to check
+	        # that they are being used correctly in the link pass.
+	        test -z "$libdir" && \
+	          func_append dlpreconveniencelibs " $dir/$old_library"
+	      # Otherwise, use the dlname, so that lt_dlopen finds it.
+	      elif test -n "$dlname"; then
+	        func_append newdlprefiles " $dir/$dlname"
+	      else
+	        func_append newdlprefiles " $dir/$linklib"
+	      fi
+	    ;;
+	  esac
 	fi # $pass = dlpreopen
 
@@ -5469,5 +6601,5 @@
 
 	if test "$linkmode" = prog && test "$pass" != link; then
-	  newlib_search_path="$newlib_search_path $ladir"
+	  func_append newlib_search_path " $ladir"
 	  deplibs="$lib $deplibs"
 
@@ -5482,5 +6614,6 @@
 	    case $deplib in
 	    -L*) func_stripname '-L' '' "$deplib"
-	         newlib_search_path="$newlib_search_path $func_stripname_result"
+	         func_resolve_sysroot "$func_stripname_result"
+	         func_append newlib_search_path " $func_resolve_sysroot_result"
 		 ;;
 	    esac
@@ -5493,10 +6626,10 @@
 	      newdependency_libs="$deplib $newdependency_libs"
 	    fi
-	    if $opt_duplicate_deps ; then
+	    if $opt_preserve_dup_deps ; then
 	      case "$tmp_libs " in
-	      *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
 	      esac
 	    fi
-	    tmp_libs="$tmp_libs $deplib"
+	    func_append tmp_libs " $deplib"
 	  done # for deplib
 	  continue
@@ -5513,5 +6646,5 @@
 	      case "$temp_rpath:" in
 	      *"$absdir:"*) ;;
-	      *) temp_rpath="$temp_rpath$absdir:" ;;
+	      *) func_append temp_rpath "$absdir:" ;;
 	      esac
 	    fi
@@ -5525,5 +6658,5 @@
 	      case "$compile_rpath " in
 	      *" $absdir "*) ;;
-	      *) compile_rpath="$compile_rpath $absdir"
+	      *) func_append compile_rpath " $absdir" ;;
 	      esac
 	      ;;
@@ -5534,5 +6667,5 @@
 	      case "$finalize_rpath " in
 	      *" $libdir "*) ;;
-	      *) finalize_rpath="$finalize_rpath $libdir"
+	      *) func_append finalize_rpath " $libdir" ;;
 	      esac
 	      ;;
@@ -5559,10 +6692,10 @@
 	  *cygwin* | *mingw* | *cegcc*)
 	      # No point in relinking DLLs because paths are not encoded
-	      notinst_deplibs="$notinst_deplibs $lib"
+	      func_append notinst_deplibs " $lib"
 	      need_relink=no
 	    ;;
 	  *)
 	    if test "$installed" = no; then
-	      notinst_deplibs="$notinst_deplibs $lib"
+	      func_append notinst_deplibs " $lib"
 	      need_relink=yes
 	    fi
@@ -5581,5 +6714,5 @@
 	  done
 	  if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then
-	    $ECHO
+	    echo
 	    if test "$linkmode" = prog; then
 	      $ECHO "*** Warning: Linking the executable $output against the loadable module"
@@ -5599,5 +6732,5 @@
 	      case "$compile_rpath " in
 	      *" $absdir "*) ;;
-	      *) compile_rpath="$compile_rpath $absdir"
+	      *) func_append compile_rpath " $absdir" ;;
 	      esac
 	      ;;
@@ -5608,5 +6741,5 @@
 	      case "$finalize_rpath " in
 	      *" $libdir "*) ;;
-	      *) finalize_rpath="$finalize_rpath $libdir"
+	      *) func_append finalize_rpath " $libdir" ;;
 	      esac
 	      ;;
@@ -5662,5 +6795,5 @@
 	  fi # test -n "$old_archive_from_expsyms_cmds"
 
-	  if test "$linkmode" = prog || test "$mode" != relink; then
+	  if test "$linkmode" = prog || test "$opt_mode" != relink; then
 	    add_shlibpath=
 	    add_dir=
@@ -5684,7 +6817,7 @@
 			$ECHO "*** Warning: lib $linklib is a module, not a shared library"
 			if test -z "$old_library" ; then
-			  $ECHO
-			  $ECHO "*** And there doesn't seem to be a static archive available"
-			  $ECHO "*** The link will probably fail, sorry"
+			  echo
+			  echo "*** And there doesn't seem to be a static archive available"
+			  echo "*** The link will probably fail, sorry"
 			else
 			  add="$dir/$old_library"
@@ -5713,10 +6846,10 @@
 		add="$dir/$linklib"
 	      elif test "$hardcode_minus_L" = yes; then
-		add_dir="-L$dir"
+		add_dir="-L$absdir"
 		# Try looking first in the location we're being installed to.
 		if test -n "$inst_prefix_dir"; then
 		  case $libdir in
 		    [\\/]*)
-		      add_dir="$add_dir -L$inst_prefix_dir$libdir"
+		      func_append add_dir " -L$inst_prefix_dir$libdir"
 		      ;;
 		  esac
@@ -5740,5 +6873,5 @@
 	      case :$compile_shlibpath: in
 	      *":$add_shlibpath:"*) ;;
-	      *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;;
+	      *) func_append compile_shlibpath "$add_shlibpath:" ;;
 	      esac
 	    fi
@@ -5754,5 +6887,5 @@
 		case :$finalize_shlibpath: in
 		*":$libdir:"*) ;;
-		*) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
+		*) func_append finalize_shlibpath "$libdir:" ;;
 		esac
 	      fi
@@ -5760,5 +6893,5 @@
 	  fi
 
-	  if test "$linkmode" = prog || test "$mode" = relink; then
+	  if test "$linkmode" = prog || test "$opt_mode" = relink; then
 	    add_shlibpath=
 	    add_dir=
@@ -5774,5 +6907,5 @@
 	      case :$finalize_shlibpath: in
 	      *":$libdir:"*) ;;
-	      *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
+	      *) func_append finalize_shlibpath "$libdir:" ;;
 	      esac
 	      add="-l$name"
@@ -5791,5 +6924,5 @@
 		case $libdir in
 		  [\\/]*)
-		    add_dir="$add_dir -L$inst_prefix_dir$libdir"
+		    func_append add_dir " -L$inst_prefix_dir$libdir"
 		    ;;
 		esac
@@ -5826,19 +6959,19 @@
 	    # Just print a warning and add the library to dependency_libs so
 	    # that the program can be linked against the static library.
-	    $ECHO
+	    echo
 	    $ECHO "*** Warning: This system can not link to static lib archive $lib."
-	    $ECHO "*** I have the capability to make that library automatically link in when"
-	    $ECHO "*** you link to this library.  But I can only do this if you have a"
-	    $ECHO "*** shared version of the library, which you do not appear to have."
+	    echo "*** I have the capability to make that library automatically link in when"
+	    echo "*** you link to this library.  But I can only do this if you have a"
+	    echo "*** shared version of the library, which you do not appear to have."
 	    if test "$module" = yes; then
-	      $ECHO "*** But as you try to build a module library, libtool will still create "
-	      $ECHO "*** a static module, that should work as long as the dlopening application"
-	      $ECHO "*** is linked with the -dlopen flag to resolve symbols at runtime."
+	      echo "*** But as you try to build a module library, libtool will still create "
+	      echo "*** a static module, that should work as long as the dlopening application"
+	      echo "*** is linked with the -dlopen flag to resolve symbols at runtime."
 	      if test -z "$global_symbol_pipe"; then
-		$ECHO
-		$ECHO "*** However, this would only work if libtool was able to extract symbol"
-		$ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could"
-		$ECHO "*** not find such a program.  So, this module is probably useless."
-		$ECHO "*** \`nm' from GNU binutils and a full rebuild may help."
+		echo
+		echo "*** However, this would only work if libtool was able to extract symbol"
+		echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+		echo "*** not find such a program.  So, this module is probably useless."
+		echo "*** \`nm' from GNU binutils and a full rebuild may help."
 	      fi
 	      if test "$build_old_libs" = no; then
@@ -5868,7 +7001,7 @@
 		   case " $xrpath " in
 		   *" $temp_xrpath "*) ;;
-		   *) xrpath="$xrpath $temp_xrpath";;
+		   *) func_append xrpath " $temp_xrpath";;
 		   esac;;
-	      *) temp_deplibs="$temp_deplibs $libdir";;
+	      *) func_append temp_deplibs " $libdir";;
 	      esac
 	    done
@@ -5876,5 +7009,5 @@
 	  fi
 
-	  newlib_search_path="$newlib_search_path $absdir"
+	  func_append newlib_search_path " $absdir"
 	  # Link against this library
 	  test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
@@ -5883,10 +7016,16 @@
 	  for deplib in $dependency_libs; do
 	    newdependency_libs="$deplib $newdependency_libs"
-	    if $opt_duplicate_deps ; then
+	    case $deplib in
+              -L*) func_stripname '-L' '' "$deplib"
+                   func_resolve_sysroot "$func_stripname_result";;
+              *) func_resolve_sysroot "$deplib" ;;
+            esac
+	    if $opt_preserve_dup_deps ; then
 	      case "$tmp_libs " in
-	      *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+	      *" $func_resolve_sysroot_result "*)
+                func_append specialdeplibs " $func_resolve_sysroot_result" ;;
 	      esac
 	    fi
-	    tmp_libs="$tmp_libs $deplib"
+	    func_append tmp_libs " $func_resolve_sysroot_result"
 	  done
 
@@ -5894,9 +7033,12 @@
 	    # Add the search paths of all dependency libraries
 	    for deplib in $dependency_libs; do
+	      path=
 	      case $deplib in
 	      -L*) path="$deplib" ;;
 	      *.la)
+	        func_resolve_sysroot "$deplib"
+	        deplib=$func_resolve_sysroot_result
 	        func_dirname "$deplib" "" "."
-		dir="$func_dirname_result"
+		dir=$func_dirname_result
 		# We need an absolute path.
 		case $dir in
@@ -5925,6 +7067,6 @@
                           darwin_install_name=`${OTOOL64} -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`
                       fi
-		      compiler_flags="$compiler_flags ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}"
-		      linker_flags="$linker_flags -dylib_file ${darwin_install_name}:${depdepl}"
+		      func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}"
+		      func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}"
 		      path=
 		    fi
@@ -5959,5 +7101,5 @@
 	  finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs"
 	else
-	  compiler_flags="$compiler_flags "`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
 	fi
       fi
@@ -5976,5 +7118,5 @@
 	    case "$lib_search_path " in
 	    *" $dir "*) ;;
-	    *) lib_search_path="$lib_search_path $dir" ;;
+	    *) func_append lib_search_path " $dir" ;;
 	    esac
 	  done
@@ -6034,8 +7176,8 @@
 	      case " $tmp_libs " in
 	      *" $deplib "*) ;;
-	      *) tmp_libs="$tmp_libs $deplib" ;;
+	      *) func_append tmp_libs " $deplib" ;;
 	      esac
 	      ;;
-	    *) tmp_libs="$tmp_libs $deplib" ;;
+	    *) func_append tmp_libs " $deplib" ;;
 	    esac
 	  done
@@ -6053,5 +7195,5 @@
 	esac
 	if test -n "$i" ; then
-	  tmp_libs="$tmp_libs $i"
+	  func_append tmp_libs " $i"
 	fi
       done
@@ -6094,5 +7236,5 @@
       build_libtool_libs=no
       oldlibs="$output"
-      objs="$objs$old_deplibs"
+      func_append objs "$old_deplibs"
       ;;
 
@@ -6127,8 +7269,8 @@
 	  func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs"
 	else
-	  $ECHO
+	  echo
 	  $ECHO "*** Warning: Linking the shared library $output against the non-libtool"
 	  $ECHO "*** objects $objs is not portable!"
-	  libobjs="$libobjs $objs"
+	  func_append libobjs " $objs"
 	fi
       fi
@@ -6189,4 +7331,5 @@
 	  #
 	  case $version_type in
+	  # correct linux to gnu/linux during the next big refactor
 	  darwin|linux|osf|windows|none)
 	    func_arith $number_major + $number_minor
@@ -6195,5 +7338,5 @@
 	    revision="$number_revision"
 	    ;;
-	  freebsd-aout|freebsd-elf|sunos)
+	  freebsd-aout|freebsd-elf|qnx|sunos)
 	    current="$number_major"
 	    revision="$number_minor"
@@ -6305,5 +7448,5 @@
 	  ;;
 
-	linux)
+	linux) # correct to gnu/linux during the next big refactor
 	  func_arith $current - $age
 	  major=.$func_arith_result
@@ -6328,5 +7471,5 @@
 
 	  # Make executables depend on our current version.
-	  verstring="$verstring:${current}.0"
+	  func_append verstring ":${current}.0"
 	  ;;
 
@@ -6396,8 +7539,8 @@
 
       func_generate_dlsyms "$libname" "$libname" "yes"
-      libobjs="$libobjs $symfileobj"
+      func_append libobjs " $symfileobj"
       test "X$libobjs" = "X " && libobjs=
 
-      if test "$mode" != relink; then
+      if test "$opt_mode" != relink; then
 	# Remove our outputs, but don't remove object files since they
 	# may have been created when compiling PIC objects.
@@ -6415,5 +7558,5 @@
 		 fi
 	       fi
-	       removelist="$removelist $p"
+	       func_append removelist " $p"
 	       ;;
 	    *) ;;
@@ -6426,15 +7569,15 @@
       # Now set the variables for building old libraries.
       if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then
-	oldlibs="$oldlibs $output_objdir/$libname.$libext"
+	func_append oldlibs " $output_objdir/$libname.$libext"
 
 	# Transform .lo files to .o files.
-	oldobjs="$objs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP`
+	oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP`
       fi
 
       # Eliminate all temporary directories.
       #for path in $notinst_path; do
-      #	lib_search_path=`$ECHO "X$lib_search_path " | $Xsed -e "s% $path % %g"`
-      #	deplibs=`$ECHO "X$deplibs " | $Xsed -e "s% -L$path % %g"`
-      #	dependency_libs=`$ECHO "X$dependency_libs " | $Xsed -e "s% -L$path % %g"`
+      #	lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"`
+      #	deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"`
+      #	dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"`
       #done
 
@@ -6443,8 +7586,9 @@
 	temp_xrpath=
 	for libdir in $xrpath; do
-	  temp_xrpath="$temp_xrpath -R$libdir"
+	  func_replace_sysroot "$libdir"
+	  func_append temp_xrpath " -R$func_replace_sysroot_result"
 	  case "$finalize_rpath " in
 	  *" $libdir "*) ;;
-	  *) finalize_rpath="$finalize_rpath $libdir" ;;
+	  *) func_append finalize_rpath " $libdir" ;;
 	  esac
 	done
@@ -6460,5 +7604,5 @@
 	case " $dlprefiles $dlfiles " in
 	*" $lib "*) ;;
-	*) dlfiles="$dlfiles $lib" ;;
+	*) func_append dlfiles " $lib" ;;
 	esac
       done
@@ -6470,5 +7614,5 @@
 	case "$dlprefiles " in
 	*" $lib "*) ;;
-	*) dlprefiles="$dlprefiles $lib" ;;
+	*) func_append dlprefiles " $lib" ;;
 	esac
       done
@@ -6477,10 +7621,10 @@
 	if test -n "$rpath"; then
 	  case $host in
-	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc*)
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)
 	    # these systems don't actually have a c library (as such)!
 	    ;;
 	  *-*-rhapsody* | *-*-darwin1.[012])
 	    # Rhapsody C library is in the System framework
-	    deplibs="$deplibs System.ltframework"
+	    func_append deplibs " System.ltframework"
 	    ;;
 	  *-*-netbsd*)
@@ -6499,5 +7643,5 @@
 	    # Add libc to deplibs on all other systems if necessary.
 	    if test "$build_libtool_need_lc" = "yes"; then
-	      deplibs="$deplibs -lc"
+	      func_append deplibs " -lc"
 	    fi
 	    ;;
@@ -6548,5 +7692,5 @@
 		  case " $predeps $postdeps " in
 		  *" $i "*)
-		    newdeplibs="$newdeplibs $i"
+		    func_append newdeplibs " $i"
 		    i=""
 		    ;;
@@ -6559,19 +7703,19 @@
 		  deplib_match=$1
 		  if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
-		    newdeplibs="$newdeplibs $i"
+		    func_append newdeplibs " $i"
 		  else
 		    droppeddeps=yes
-		    $ECHO
+		    echo
 		    $ECHO "*** Warning: dynamic linker does not accept needed library $i."
-		    $ECHO "*** I have the capability to make that library automatically link in when"
-		    $ECHO "*** you link to this library.  But I can only do this if you have a"
-		    $ECHO "*** shared version of the library, which I believe you do not have"
-		    $ECHO "*** because a test_compile did reveal that the linker did not use it for"
-		    $ECHO "*** its dynamic dependency list that programs get resolved with at runtime."
+		    echo "*** I have the capability to make that library automatically link in when"
+		    echo "*** you link to this library.  But I can only do this if you have a"
+		    echo "*** shared version of the library, which I believe you do not have"
+		    echo "*** because a test_compile did reveal that the linker did not use it for"
+		    echo "*** its dynamic dependency list that programs get resolved with at runtime."
 		  fi
 		fi
 		;;
 	      *)
-		newdeplibs="$newdeplibs $i"
+		func_append newdeplibs " $i"
 		;;
 	      esac
@@ -6591,5 +7735,5 @@
 		    case " $predeps $postdeps " in
 		    *" $i "*)
-		      newdeplibs="$newdeplibs $i"
+		      func_append newdeplibs " $i"
 		      i=""
 		      ;;
@@ -6602,27 +7746,27 @@
 		    deplib_match=$1
 		    if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
-		      newdeplibs="$newdeplibs $i"
+		      func_append newdeplibs " $i"
 		    else
 		      droppeddeps=yes
-		      $ECHO
+		      echo
 		      $ECHO "*** Warning: dynamic linker does not accept needed library $i."
-		      $ECHO "*** I have the capability to make that library automatically link in when"
-		      $ECHO "*** you link to this library.  But I can only do this if you have a"
-		      $ECHO "*** shared version of the library, which you do not appear to have"
-		      $ECHO "*** because a test_compile did reveal that the linker did not use this one"
-		      $ECHO "*** as a dynamic dependency that programs can get resolved with at runtime."
+		      echo "*** I have the capability to make that library automatically link in when"
+		      echo "*** you link to this library.  But I can only do this if you have a"
+		      echo "*** shared version of the library, which you do not appear to have"
+		      echo "*** because a test_compile did reveal that the linker did not use this one"
+		      echo "*** as a dynamic dependency that programs can get resolved with at runtime."
 		    fi
 		  fi
 		else
 		  droppeddeps=yes
-		  $ECHO
+		  echo
 		  $ECHO "*** Warning!  Library $i is needed by this library but I was not able to"
-		  $ECHO "*** make it link in!  You will probably need to install it or some"
-		  $ECHO "*** library that it depends on before this library will be fully"
-		  $ECHO "*** functional.  Installing it before continuing would be even better."
+		  echo "*** make it link in!  You will probably need to install it or some"
+		  echo "*** library that it depends on before this library will be fully"
+		  echo "*** functional.  Installing it before continuing would be even better."
 		fi
 		;;
 	      *)
-		newdeplibs="$newdeplibs $i"
+		func_append newdeplibs " $i"
 		;;
 	      esac
@@ -6641,5 +7785,5 @@
 		case " $predeps $postdeps " in
 		*" $a_deplib "*)
-		  newdeplibs="$newdeplibs $a_deplib"
+		  func_append newdeplibs " $a_deplib"
 		  a_deplib=""
 		  ;;
@@ -6648,6 +7792,18 @@
 	      if test -n "$a_deplib" ; then
 		libname=`eval "\\$ECHO \"$libname_spec\""`
+		if test -n "$file_magic_glob"; then
+		  libnameglob=`func_echo_all "$libname" | $SED -e $file_magic_glob`
+		else
+		  libnameglob=$libname
+		fi
+		test "$want_nocaseglob" = yes && nocaseglob=`shopt -p nocaseglob`
 		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
-		  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
+		  if test "$want_nocaseglob" = yes; then
+		    shopt -s nocaseglob
+		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
+		    $nocaseglob
+		  else
+		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
+		  fi
 		  for potent_lib in $potential_libs; do
 		      # Follow soft links.
@@ -6666,5 +7822,5 @@
 			case $potliblink in
 			[\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";;
-			*) potlib=`$ECHO "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";;
+			*) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";;
 			esac
 		      done
@@ -6672,5 +7828,5 @@
 			 $SED -e 10q |
 			 $EGREP "$file_magic_regex" > /dev/null; then
-			newdeplibs="$newdeplibs $a_deplib"
+			func_append newdeplibs " $a_deplib"
 			a_deplib=""
 			break 2
@@ -6681,10 +7837,10 @@
 	      if test -n "$a_deplib" ; then
 		droppeddeps=yes
-		$ECHO
+		echo
 		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
-		$ECHO "*** I have the capability to make that library automatically link in when"
-		$ECHO "*** you link to this library.  But I can only do this if you have a"
-		$ECHO "*** shared version of the library, which you do not appear to have"
-		$ECHO "*** because I did check the linker path looking for a file starting"
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because I did check the linker path looking for a file starting"
 		if test -z "$potlib" ; then
 		  $ECHO "*** with $libname but no candidates were found. (...for file magic test)"
@@ -6697,5 +7853,5 @@
 	    *)
 	      # Add a -L argument.
-	      newdeplibs="$newdeplibs $a_deplib"
+	      func_append newdeplibs " $a_deplib"
 	      ;;
 	    esac
@@ -6713,5 +7869,5 @@
 		case " $predeps $postdeps " in
 		*" $a_deplib "*)
-		  newdeplibs="$newdeplibs $a_deplib"
+		  func_append newdeplibs " $a_deplib"
 		  a_deplib=""
 		  ;;
@@ -6724,7 +7880,7 @@
 		  for potent_lib in $potential_libs; do
 		    potlib="$potent_lib" # see symlink-check above in file_magic test
-		    if eval "\$ECHO \"X$potent_lib\"" 2>/dev/null | $Xsed -e 10q | \
+		    if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \
 		       $EGREP "$match_pattern_regex" > /dev/null; then
-		      newdeplibs="$newdeplibs $a_deplib"
+		      func_append newdeplibs " $a_deplib"
 		      a_deplib=""
 		      break 2
@@ -6735,10 +7891,10 @@
 	      if test -n "$a_deplib" ; then
 		droppeddeps=yes
-		$ECHO
+		echo
 		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
-		$ECHO "*** I have the capability to make that library automatically link in when"
-		$ECHO "*** you link to this library.  But I can only do this if you have a"
-		$ECHO "*** shared version of the library, which you do not appear to have"
-		$ECHO "*** because I did check the linker path looking for a file starting"
+		echo "*** I have the capability to make that library automatically link in when"
+		echo "*** you link to this library.  But I can only do this if you have a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because I did check the linker path looking for a file starting"
 		if test -z "$potlib" ; then
 		  $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)"
@@ -6751,5 +7907,5 @@
 	    *)
 	      # Add a -L argument.
-	      newdeplibs="$newdeplibs $a_deplib"
+	      func_append newdeplibs " $a_deplib"
 	      ;;
 	    esac
@@ -6758,23 +7914,23 @@
 	none | unknown | *)
 	  newdeplibs=""
-	  tmp_deplibs=`$ECHO "X $deplibs" | $Xsed \
-	      -e 's/ -lc$//' -e 's/ -[LR][^ ]*//g'`
+	  tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`
 	  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
 	    for i in $predeps $postdeps ; do
 	      # can't use Xsed below, because $i might contain '/'
-	      tmp_deplibs=`$ECHO "X $tmp_deplibs" | $Xsed -e "s,$i,,"`
+	      tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"`
 	    done
 	  fi
-	  if $ECHO "X $tmp_deplibs" | $Xsed -e 's/[	 ]//g' |
-	     $GREP . >/dev/null; then
-	    $ECHO
+	  case $tmp_deplibs in
+	  *[!\	\ ]*)
+	    echo
 	    if test "X$deplibs_check_method" = "Xnone"; then
-	      $ECHO "*** Warning: inter-library dependencies are not supported in this platform."
+	      echo "*** Warning: inter-library dependencies are not supported in this platform."
 	    else
-	      $ECHO "*** Warning: inter-library dependencies are not known to be supported."
+	      echo "*** Warning: inter-library dependencies are not known to be supported."
 	    fi
-	    $ECHO "*** All declared inter-library dependencies are being dropped."
+	    echo "*** All declared inter-library dependencies are being dropped."
 	    droppeddeps=yes
-	  fi
+	    ;;
+	  esac
 	  ;;
 	esac
@@ -6788,5 +7944,5 @@
 	*-*-rhapsody* | *-*-darwin1.[012])
 	  # On Rhapsody replace the C library with the System framework
-	  newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's/ -lc / System.ltframework /'`
+	  newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'`
 	  ;;
 	esac
@@ -6794,15 +7950,15 @@
 	if test "$droppeddeps" = yes; then
 	  if test "$module" = yes; then
-	    $ECHO
-	    $ECHO "*** Warning: libtool could not satisfy all declared inter-library"
+	    echo
+	    echo "*** Warning: libtool could not satisfy all declared inter-library"
 	    $ECHO "*** dependencies of module $libname.  Therefore, libtool will create"
-	    $ECHO "*** a static module, that should work as long as the dlopening"
-	    $ECHO "*** application is linked with the -dlopen flag."
+	    echo "*** a static module, that should work as long as the dlopening"
+	    echo "*** application is linked with the -dlopen flag."
 	    if test -z "$global_symbol_pipe"; then
-	      $ECHO
-	      $ECHO "*** However, this would only work if libtool was able to extract symbol"
-	      $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could"
-	      $ECHO "*** not find such a program.  So, this module is probably useless."
-	      $ECHO "*** \`nm' from GNU binutils and a full rebuild may help."
+	      echo
+	      echo "*** However, this would only work if libtool was able to extract symbol"
+	      echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+	      echo "*** not find such a program.  So, this module is probably useless."
+	      echo "*** \`nm' from GNU binutils and a full rebuild may help."
 	    fi
 	    if test "$build_old_libs" = no; then
@@ -6814,14 +7970,14 @@
 	    fi
 	  else
-	    $ECHO "*** The inter-library dependencies that have been dropped here will be"
-	    $ECHO "*** automatically added whenever a program is linked with this library"
-	    $ECHO "*** or is declared to -dlopen it."
+	    echo "*** The inter-library dependencies that have been dropped here will be"
+	    echo "*** automatically added whenever a program is linked with this library"
+	    echo "*** or is declared to -dlopen it."
 
 	    if test "$allow_undefined" = no; then
-	      $ECHO
-	      $ECHO "*** Since this library must not contain undefined symbols,"
-	      $ECHO "*** because either the platform does not support them or"
-	      $ECHO "*** it was explicitly requested with -no-undefined,"
-	      $ECHO "*** libtool will only create a static version of it."
+	      echo
+	      echo "*** Since this library must not contain undefined symbols,"
+	      echo "*** because either the platform does not support them or"
+	      echo "*** it was explicitly requested with -no-undefined,"
+	      echo "*** libtool will only create a static version of it."
 	      if test "$build_old_libs" = no; then
 		oldlibs="$output_objdir/$libname.$libext"
@@ -6840,7 +7996,7 @@
       case $host in
 	*-*-darwin*)
-	  newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
-	  new_inherited_linker_flags=`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
-	  deplibs=`$ECHO "X $deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
 	  ;;
       esac
@@ -6855,5 +8011,5 @@
 	  case " $deplibs " in
 	  *" -L$path/$objdir "*)
-	    new_libs="$new_libs -L$path/$objdir" ;;
+	    func_append new_libs " -L$path/$objdir" ;;
 	  esac
 	  ;;
@@ -6865,8 +8021,8 @@
 	  case " $new_libs " in
 	  *" $deplib "*) ;;
-	  *) new_libs="$new_libs $deplib" ;;
+	  *) func_append new_libs " $deplib" ;;
 	  esac
 	  ;;
-	*) new_libs="$new_libs $deplib" ;;
+	*) func_append new_libs " $deplib" ;;
 	esac
       done
@@ -6880,4 +8036,9 @@
       # Test again, we may have decided not to build it any more
       if test "$build_libtool_libs" = yes; then
+	# Remove ${wl} instances when linking with ld.
+	# FIXME: should test the right _cmds variable.
+	case $archive_cmds in
+	  *\$LD\ *) wl= ;;
+        esac
 	if test "$hardcode_into_libs" = yes; then
 	  # Hardcode the library paths
@@ -6885,8 +8046,10 @@
 	  dep_rpath=
 	  rpath="$finalize_rpath"
-	  test "$mode" != relink && rpath="$compile_rpath$rpath"
+	  test "$opt_mode" != relink && rpath="$compile_rpath$rpath"
 	  for libdir in $rpath; do
 	    if test -n "$hardcode_libdir_flag_spec"; then
 	      if test -n "$hardcode_libdir_separator"; then
+		func_replace_sysroot "$libdir"
+		libdir=$func_replace_sysroot_result
 		if test -z "$hardcode_libdirs"; then
 		  hardcode_libdirs="$libdir"
@@ -6897,5 +8060,5 @@
 		    ;;
 		  *)
-		    hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+		    func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
 		    ;;
 		  esac
@@ -6903,10 +8066,10 @@
 	      else
 		eval flag=\"$hardcode_libdir_flag_spec\"
-		dep_rpath="$dep_rpath $flag"
+		func_append dep_rpath " $flag"
 	      fi
 	    elif test -n "$runpath_var"; then
 	      case "$perm_rpath " in
 	      *" $libdir "*) ;;
-	      *) perm_rpath="$perm_rpath $libdir" ;;
+	      *) func_append perm_rpath " $libdir" ;;
 	      esac
 	    fi
@@ -6916,9 +8079,5 @@
 	     test -n "$hardcode_libdirs"; then
 	    libdir="$hardcode_libdirs"
-	    if test -n "$hardcode_libdir_flag_spec_ld"; then
-	      eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\"
-	    else
-	      eval dep_rpath=\"$hardcode_libdir_flag_spec\"
-	    fi
+	    eval "dep_rpath=\"$hardcode_libdir_flag_spec\""
 	  fi
 	  if test -n "$runpath_var" && test -n "$perm_rpath"; then
@@ -6926,5 +8085,5 @@
 	    rpath=
 	    for dir in $perm_rpath; do
-	      rpath="$rpath$dir:"
+	      func_append rpath "$dir:"
 	    done
 	    eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var"
@@ -6934,5 +8093,5 @@
 
 	shlibpath="$finalize_shlibpath"
-	test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
+	test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
 	if test -n "$shlibpath"; then
 	  eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var"
@@ -6960,9 +8119,9 @@
 	for link
 	do
-	  linknames="$linknames $link"
+	  func_append linknames " $link"
 	done
 
 	# Use standard objects if they are pic
-	test -z "$pic_flag" && libobjs=`$ECHO "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+	test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP`
 	test "X$libobjs" = "X " && libobjs=
 
@@ -6971,5 +8130,5 @@
 	  $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp"
 	  export_symbols="$output_objdir/$libname.uexp"
-	  delfiles="$delfiles $export_symbols"
+	  func_append delfiles " $export_symbols"
 	fi
 
@@ -7002,11 +8161,43 @@
 	    cmds=$export_symbols_cmds
 	    save_ifs="$IFS"; IFS='~'
-	    for cmd in $cmds; do
+	    for cmd1 in $cmds; do
 	      IFS="$save_ifs"
-	      eval cmd=\"$cmd\"
-	      func_len " $cmd"
-	      len=$func_len_result
-	      if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	      # Take the normal branch if the nm_file_list_spec branch
+	      # doesn't work or if tool conversion is not needed.
+	      case $nm_file_list_spec~$to_tool_file_cmd in
+		*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)
+		  try_normal_branch=yes
+		  eval cmd=\"$cmd1\"
+		  func_len " $cmd"
+		  len=$func_len_result
+		  ;;
+		*)
+		  try_normal_branch=no
+		  ;;
+	      esac
+	      if test "$try_normal_branch" = yes \
+		 && { test "$len" -lt "$max_cmd_len" \
+		      || test "$max_cmd_len" -le -1; }
+	      then
 		func_show_eval "$cmd" 'exit $?'
+		skipped_export=false
+	      elif test -n "$nm_file_list_spec"; then
+		func_basename "$output"
+		output_la=$func_basename_result
+		save_libobjs=$libobjs
+		save_output=$output
+		output=${output_objdir}/${output_la}.nm
+		func_to_tool_file "$output"
+		libobjs=$nm_file_list_spec$func_to_tool_file_result
+		func_append delfiles " $output"
+		func_verbose "creating $NM input file list: $output"
+		for obj in $save_libobjs; do
+		  func_to_tool_file "$obj"
+		  $ECHO "$func_to_tool_file_result"
+		done > "$output"
+		eval cmd=\"$cmd1\"
+		func_show_eval "$cmd" 'exit $?'
+		output=$save_output
+		libobjs=$save_libobjs
 		skipped_export=false
 	      else
@@ -7030,5 +8221,5 @@
 	  tmp_export_symbols="$export_symbols"
 	  test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
-	  $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"'
+	  $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
 	fi
 
@@ -7042,5 +8233,5 @@
 	  # isn't a blessed tool.
 	  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
-	  delfiles="$delfiles $export_symbols $output_objdir/$libname.filter"
+	  func_append delfiles " $export_symbols $output_objdir/$libname.filter"
 	  export_symbols=$output_objdir/$libname.def
 	  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
@@ -7052,5 +8243,5 @@
 	  *" $test_deplib "*) ;;
 	  *)
-	    tmp_deplibs="$tmp_deplibs $test_deplib"
+	    func_append tmp_deplibs " $test_deplib"
 	    ;;
 	  esac
@@ -7072,8 +8263,8 @@
 	  else
 	    gentop="$output_objdir/${outputname}x"
-	    generated="$generated $gentop"
+	    func_append generated " $gentop"
 
 	    func_extract_archives $gentop $convenience
-	    libobjs="$libobjs $func_extract_archives_result"
+	    func_append libobjs " $func_extract_archives_result"
 	    test "X$libobjs" = "X " && libobjs=
 	  fi
@@ -7082,9 +8273,9 @@
 	if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
 	  eval flag=\"$thread_safe_flag_spec\"
-	  linker_flags="$linker_flags $flag"
+	  func_append linker_flags " $flag"
 	fi
 
 	# Make a backup of the uninstalled library when relinking
-	if test "$mode" = relink; then
+	if test "$opt_mode" = relink; then
 	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?
 	fi
@@ -7131,5 +8322,6 @@
 	  fi
 	  save_output=$output
-	  output_la=`$ECHO "X$output" | $Xsed -e "$basename"`
+	  func_basename "$output"
+	  output_la=$func_basename_result
 
 	  # Clear the reloadable object creation command queue and
@@ -7144,11 +8336,14 @@
 	    output=${output_objdir}/${output_la}.lnkscript
 	    func_verbose "creating GNU ld script: $output"
-	    $ECHO 'INPUT (' > $output
+	    echo 'INPUT (' > $output
 	    for obj in $save_libobjs
 	    do
-	      $ECHO "$obj" >> $output
+	      func_to_tool_file "$obj"
+	      $ECHO "$func_to_tool_file_result" >> $output
 	    done
-	    $ECHO ')' >> $output
-	    delfiles="$delfiles $output"
+	    echo ')' >> $output
+	    func_append delfiles " $output"
+	    func_to_tool_file "$output"
+	    output=$func_to_tool_file_result
 	  elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then
 	    output=${output_objdir}/${output_la}.lnk
@@ -7164,8 +8359,10 @@
 	    for obj
 	    do
-	      $ECHO "$obj" >> $output
+	      func_to_tool_file "$obj"
+	      $ECHO "$func_to_tool_file_result" >> $output
 	    done
-	    delfiles="$delfiles $output"
-	    output=$firstobj\"$file_list_spec$output\"
+	    func_append delfiles " $output"
+	    func_to_tool_file "$output"
+	    output=$firstobj\"$file_list_spec$func_to_tool_file_result\"
 	  else
 	    if test -n "$save_libobjs"; then
@@ -7191,9 +8388,11 @@
 		  if test "$k" -eq 1 ; then
 		    # The first file doesn't have a previous command to add.
-		    eval concat_cmds=\"$reload_cmds $objlist $last_robj\"
+		    reload_objs=$objlist
+		    eval concat_cmds=\"$reload_cmds\"
 		  else
 		    # All subsequent reloadable object files will link in
 		    # the last one created.
-		    eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj~\$RM $last_robj\"
+		    reload_objs="$objlist $last_robj"
+		    eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\"
 		  fi
 		  last_robj=$output_objdir/$output_la-${k}.$objext
@@ -7201,5 +8400,5 @@
 		  k=$func_arith_result
 		  output=$output_objdir/$output_la-${k}.$objext
-		  objlist=$obj
+		  objlist=" $obj"
 		  func_len " $last_robj"
 		  func_arith $len0 + $func_len_result
@@ -7211,9 +8410,10 @@
 	      # files will link in the last one created.
 	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
-	      eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\"
+	      reload_objs="$objlist $last_robj"
+	      eval concat_cmds=\"\${concat_cmds}$reload_cmds\"
 	      if test -n "$last_robj"; then
 	        eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\"
 	      fi
-	      delfiles="$delfiles $output"
+	      func_append delfiles " $output"
 
 	    else
@@ -7249,5 +8449,5 @@
 
 		# Restore the uninstalled library and exit
-		if test "$mode" = relink; then
+		if test "$opt_mode" = relink; then
 		  ( cd "$output_objdir" && \
 		    $RM "${realname}T" && \
@@ -7270,5 +8470,5 @@
 	      tmp_export_symbols="$export_symbols"
 	      test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
-	      $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"'
+	      $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
 	    fi
 
@@ -7282,5 +8482,5 @@
 	      # isn't a blessed tool.
 	      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
-	      delfiles="$delfiles $export_symbols $output_objdir/$libname.filter"
+	      func_append delfiles " $export_symbols $output_objdir/$libname.filter"
 	      export_symbols=$output_objdir/$libname.def
 	      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
@@ -7323,8 +8523,8 @@
 	if test -n "$dlprefiles"; then
 	  gentop="$output_objdir/${outputname}x"
-	  generated="$generated $gentop"
+	  func_append generated " $gentop"
 
 	  func_extract_archives $gentop $dlprefiles
-	  libobjs="$libobjs $func_extract_archives_result"
+	  func_append libobjs " $func_extract_archives_result"
 	  test "X$libobjs" = "X " && libobjs=
 	fi
@@ -7342,5 +8542,5 @@
 
 	    # Restore the uninstalled library and exit
-	    if test "$mode" = relink; then
+	    if test "$opt_mode" = relink; then
 	      ( cd "$output_objdir" && \
 	        $RM "${realname}T" && \
@@ -7354,5 +8554,5 @@
 
 	# Restore the uninstalled library and exit
-	if test "$mode" = relink; then
+	if test "$opt_mode" = relink; then
 	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?
 
@@ -7435,8 +8635,8 @@
 	if test -n "$whole_archive_flag_spec"; then
 	  eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\"
-	  reload_conv_objs=$reload_objs\ `$ECHO "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'`
+	  reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'`
 	else
 	  gentop="$output_objdir/${obj}x"
-	  generated="$generated $gentop"
+	  func_append generated " $gentop"
 
 	  func_extract_archives $gentop $convenience
@@ -7445,6 +8645,9 @@
       fi
 
+      # If we're not building shared, we need to use non_pic_objs
+      test "$build_libtool_libs" != yes && libobjs="$non_pic_objects"
+
       # Create the old-style object.
-      reload_objs="$objs$old_deplibs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
+      reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
 
       output="$obj"
@@ -7506,6 +8709,6 @@
       *-*-rhapsody* | *-*-darwin1.[012])
 	# On Rhapsody replace the C library is the System framework
-	compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'`
-	finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'`
+	compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'`
+	finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'`
 	;;
       esac
@@ -7518,12 +8721,12 @@
 	  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in
 	    10.[0123])
-	      compile_command="$compile_command ${wl}-bind_at_load"
-	      finalize_command="$finalize_command ${wl}-bind_at_load"
+	      func_append compile_command " ${wl}-bind_at_load"
+	      func_append finalize_command " ${wl}-bind_at_load"
 	    ;;
 	  esac
 	fi
 	# Time to change all our "foo.ltframework" stuff back to "-framework foo"
-	compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
-	finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'`
+	compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
 	;;
       esac
@@ -7539,5 +8742,5 @@
 	  case " $compile_deplibs " in
 	  *" -L$path/$objdir "*)
-	    new_libs="$new_libs -L$path/$objdir" ;;
+	    func_append new_libs " -L$path/$objdir" ;;
 	  esac
 	  ;;
@@ -7549,8 +8752,8 @@
 	  case " $new_libs " in
 	  *" $deplib "*) ;;
-	  *) new_libs="$new_libs $deplib" ;;
+	  *) func_append new_libs " $deplib" ;;
 	  esac
 	  ;;
-	*) new_libs="$new_libs $deplib" ;;
+	*) func_append new_libs " $deplib" ;;
 	esac
       done
@@ -7558,6 +8761,6 @@
 
 
-      compile_command="$compile_command $compile_deplibs"
-      finalize_command="$finalize_command $finalize_deplibs"
+      func_append compile_command " $compile_deplibs"
+      func_append finalize_command " $finalize_deplibs"
 
       if test -n "$rpath$xrpath"; then
@@ -7567,5 +8770,5 @@
 	  case "$finalize_rpath " in
 	  *" $libdir "*) ;;
-	  *) finalize_rpath="$finalize_rpath $libdir" ;;
+	  *) func_append finalize_rpath " $libdir" ;;
 	  esac
 	done
@@ -7586,5 +8789,5 @@
 		;;
 	      *)
-		hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
 		;;
 	      esac
@@ -7592,10 +8795,10 @@
 	  else
 	    eval flag=\"$hardcode_libdir_flag_spec\"
-	    rpath="$rpath $flag"
+	    func_append rpath " $flag"
 	  fi
 	elif test -n "$runpath_var"; then
 	  case "$perm_rpath " in
 	  *" $libdir "*) ;;
-	  *) perm_rpath="$perm_rpath $libdir" ;;
+	  *) func_append perm_rpath " $libdir" ;;
 	  esac
 	fi
@@ -7606,10 +8809,10 @@
 	  *":$libdir:"*) ;;
 	  ::) dllsearchpath=$libdir;;
-	  *) dllsearchpath="$dllsearchpath:$libdir";;
+	  *) func_append dllsearchpath ":$libdir";;
 	  esac
 	  case :$dllsearchpath: in
 	  *":$testbindir:"*) ;;
 	  ::) dllsearchpath=$testbindir;;
-	  *) dllsearchpath="$dllsearchpath:$testbindir";;
+	  *) func_append dllsearchpath ":$testbindir";;
 	  esac
 	  ;;
@@ -7637,5 +8840,5 @@
 		;;
 	      *)
-		hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
 		;;
 	      esac
@@ -7643,10 +8846,10 @@
 	  else
 	    eval flag=\"$hardcode_libdir_flag_spec\"
-	    rpath="$rpath $flag"
+	    func_append rpath " $flag"
 	  fi
 	elif test -n "$runpath_var"; then
 	  case "$finalize_perm_rpath " in
 	  *" $libdir "*) ;;
-	  *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;;
+	  *) func_append finalize_perm_rpath " $libdir" ;;
 	  esac
 	fi
@@ -7662,6 +8865,6 @@
       if test -n "$libobjs" && test "$build_old_libs" = yes; then
 	# Transform all the library objects into standard objects.
-	compile_command=`$ECHO "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
-	finalize_command=`$ECHO "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+	compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
+	finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
       fi
 
@@ -7675,12 +8878,12 @@
       wrappers_required=yes
       case $host in
+      *cegcc* | *mingw32ce*)
+        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.
+        wrappers_required=no
+        ;;
       *cygwin* | *mingw* )
         if test "$build_libtool_libs" != yes; then
           wrappers_required=no
         fi
-        ;;
-      *cegcc)
-        # Disable wrappers for cegcc, we are cross compiling anyway.
-        wrappers_required=no
         ;;
       *)
@@ -7692,5 +8895,5 @@
       if test "$wrappers_required" = no; then
 	# Replace the output file specification.
-	compile_command=`$ECHO "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
+	compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
 	link_command="$compile_command$compile_rpath"
 
@@ -7698,4 +8901,10 @@
 	exit_status=0
 	func_show_eval "$link_command" 'exit_status=$?'
+
+	if test -n "$postlink_cmds"; then
+	  func_to_tool_file "$output"
+	  postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	  func_execute_cmds "$postlink_cmds" 'exit $?'
+	fi
 
 	# Delete the generated files.
@@ -7721,5 +8930,5 @@
 	  rpath=
 	  for dir in $perm_rpath; do
-	    rpath="$rpath$dir:"
+	    func_append rpath "$dir:"
 	  done
 	  compile_var="$runpath_var=\"$rpath\$$runpath_var\" "
@@ -7729,5 +8938,5 @@
 	  rpath=
 	  for dir in $finalize_perm_rpath; do
-	    rpath="$rpath$dir:"
+	    func_append rpath "$dir:"
 	  done
 	  finalize_var="$runpath_var=\"$rpath\$$runpath_var\" "
@@ -7739,9 +8948,16 @@
 	link_command="$compile_var$compile_command$compile_rpath"
 	# Replace the output file specification.
-	link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
+	link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
 	# Delete the old output file.
 	$opt_dry_run || $RM $output
 	# Link the executable and exit
 	func_show_eval "$link_command" 'exit $?'
+
+	if test -n "$postlink_cmds"; then
+	  func_to_tool_file "$output"
+	  postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	  func_execute_cmds "$postlink_cmds" 'exit $?'
+	fi
+
 	exit $EXIT_SUCCESS
       fi
@@ -7758,5 +8974,5 @@
 	  link_command="$finalize_var$compile_command$finalize_rpath"
 	  if test "$fast_install" = yes; then
-	    relink_command=`$ECHO "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'`
+	    relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'`
 	  else
 	    # fast_install is set to needless
@@ -7770,5 +8986,5 @@
 
       # Replace the output file specification.
-      link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
+      link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
 
       # Delete the old output files.
@@ -7776,4 +8992,10 @@
 
       func_show_eval "$link_command" 'exit $?'
+
+      if test -n "$postlink_cmds"; then
+	func_to_tool_file "$output_objdir/$outputname"
+	postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	func_execute_cmds "$postlink_cmds" 'exit $?'
+      fi
 
       # Now create the wrapper script.
@@ -7794,16 +9016,5 @@
 	done
 	relink_command="(cd `pwd`; $relink_command)"
-	relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"`
-      fi
-
-      # Quote $ECHO for shipping.
-      if test "X$ECHO" = "X$SHELL $progpath --fallback-echo"; then
-	case $progpath in
-	[\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";;
-	*) qecho="$SHELL `pwd`/$progpath --fallback-echo";;
-	esac
-	qecho=`$ECHO "X$qecho" | $Xsed -e "$sed_quote_subst"`
-      else
-	qecho=`$ECHO "X$ECHO" | $Xsed -e "$sed_quote_subst"`
+	relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
       fi
 
@@ -7885,5 +9096,5 @@
 	  oldobjs="$old_deplibs $non_pic_objects"
 	  if test "$preload" = yes && test -f "$symfileobj"; then
-	    oldobjs="$oldobjs $symfileobj"
+	    func_append oldobjs " $symfileobj"
 	  fi
 	fi
@@ -7893,8 +9104,8 @@
       if test -n "$addlibs"; then
 	gentop="$output_objdir/${outputname}x"
-	generated="$generated $gentop"
+	func_append generated " $gentop"
 
 	func_extract_archives $gentop $addlibs
-	oldobjs="$oldobjs $func_extract_archives_result"
+	func_append oldobjs " $func_extract_archives_result"
       fi
 
@@ -7907,8 +9118,8 @@
 	if test -n "$dlprefiles"; then
 	  gentop="$output_objdir/${outputname}x"
-	  generated="$generated $gentop"
+	  func_append generated " $gentop"
 
 	  func_extract_archives $gentop $dlprefiles
-	  oldobjs="$oldobjs $func_extract_archives_result"
+	  func_append oldobjs " $func_extract_archives_result"
 	fi
 
@@ -7926,7 +9137,7 @@
 	  :
 	else
-	  $ECHO "copying selected object files to avoid basename conflicts..."
+	  echo "copying selected object files to avoid basename conflicts..."
 	  gentop="$output_objdir/${outputname}x"
-	  generated="$generated $gentop"
+	  func_append generated " $gentop"
 	  func_mkdir_p "$gentop"
 	  save_oldobjs=$oldobjs
@@ -7952,10 +9163,12 @@
 	      done
 	      func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
-	      oldobjs="$oldobjs $gentop/$newobj"
+	      func_append oldobjs " $gentop/$newobj"
 	      ;;
-	    *) oldobjs="$oldobjs $obj" ;;
+	    *) func_append oldobjs " $obj" ;;
 	    esac
 	  done
 	fi
+	func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
+	tool_oldlib=$func_to_tool_file_result
 	eval cmds=\"$old_archive_cmds\"
 
@@ -7963,4 +9176,14 @@
 	len=$func_len_result
 	if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	  cmds=$old_archive_cmds
+	elif test -n "$archiver_list_spec"; then
+	  func_verbose "using command file archive linking..."
+	  for obj in $oldobjs
+	  do
+	    func_to_tool_file "$obj"
+	    $ECHO "$func_to_tool_file_result"
+	  done > $output_objdir/$libname.libcmd
+	  func_to_tool_file "$output_objdir/$libname.libcmd"
+	  oldobjs=" $archiver_list_spec$func_to_tool_file_result"
 	  cmds=$old_archive_cmds
 	else
@@ -8037,5 +9260,5 @@
       # Quote the link command for shipping.
       relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
-      relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"`
+      relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
       if test "$hardcode_automatic" = yes ; then
 	relink_command=
@@ -8057,10 +9280,21 @@
 		func_basename "$deplib"
 		name="$func_basename_result"
-		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+		func_resolve_sysroot "$deplib"
+		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result`
 		test -z "$libdir" && \
 		  func_fatal_error "\`$deplib' is not a valid libtool archive"
-		newdependency_libs="$newdependency_libs $libdir/$name"
+		func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name"
 		;;
-	      *) newdependency_libs="$newdependency_libs $deplib" ;;
+	      -L*)
+		func_stripname -L '' "$deplib"
+		func_replace_sysroot "$func_stripname_result"
+		func_append newdependency_libs " -L$func_replace_sysroot_result"
+		;;
+	      -R*)
+		func_stripname -R '' "$deplib"
+		func_replace_sysroot "$func_stripname_result"
+		func_append newdependency_libs " -R$func_replace_sysroot_result"
+		;;
+	      *) func_append newdependency_libs " $deplib" ;;
 	      esac
 	    done
@@ -8076,7 +9310,7 @@
 		test -z "$libdir" && \
 		  func_fatal_error "\`$lib' is not a valid libtool archive"
-		newdlfiles="$newdlfiles $libdir/$name"
+		func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name"
 		;;
-	      *) newdlfiles="$newdlfiles $lib" ;;
+	      *) func_append newdlfiles " $lib" ;;
 	      esac
 	    done
@@ -8095,5 +9329,5 @@
 		test -z "$libdir" && \
 		  func_fatal_error "\`$lib' is not a valid libtool archive"
-		newdlprefiles="$newdlprefiles $libdir/$name"
+		func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name"
 		;;
 	      esac
@@ -8107,5 +9341,5 @@
 		*) abs=`pwd`"/$lib" ;;
 	      esac
-	      newdlfiles="$newdlfiles $abs"
+	      func_append newdlfiles " $abs"
 	    done
 	    dlfiles="$newdlfiles"
@@ -8116,5 +9350,5 @@
 		*) abs=`pwd`"/$lib" ;;
 	      esac
-	      newdlprefiles="$newdlprefiles $abs"
+	      func_append newdlprefiles " $abs"
 	    done
 	    dlprefiles="$newdlprefiles"
@@ -8122,7 +9356,25 @@
 	  $RM $output
 	  # place dlname in correct position for cygwin
+	  # In fact, it would be nice if we could use this code for all target
+	  # systems that can't hard-code library paths into their executables
+	  # and that have no shared library path variable independent of PATH,
+	  # but it turns out we can't easily determine that from inspecting
+	  # libtool variables, so we have to hard-code the OSs to which it
+	  # applies here; at the moment, that means platforms that use the PE
+	  # object format with DLL files.  See the long comment at the top of
+	  # tests/bindir.at for full details.
 	  tdlname=$dlname
 	  case $host,$output,$installed,$module,$dlname in
-	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;;
+	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)
+	      # If a -bindir argument was supplied, place the dll there.
+	      if test "x$bindir" != x ;
+	      then
+		func_relative_path "$install_libdir" "$bindir"
+		tdlname=$func_relative_path_result$dlname
+	      else
+		# Otherwise fall back on heuristic.
+		tdlname=../bin/$dlname
+	      fi
+	      ;;
 	  esac
 	  $ECHO > $output "\
@@ -8183,5 +9435,5 @@
 }
 
-{ test "$mode" = link || test "$mode" = relink; } &&
+{ test "$opt_mode" = link || test "$opt_mode" = relink; } &&
     func_mode_link ${1+"$@"}
 
@@ -8203,7 +9455,7 @@
     do
       case $arg in
-      -f) RM="$RM $arg"; rmforce=yes ;;
-      -*) RM="$RM $arg" ;;
-      *) files="$files $arg" ;;
+      -f) func_append RM " $arg"; rmforce=yes ;;
+      -*) func_append RM " $arg" ;;
+      *) func_append files " $arg" ;;
       esac
     done
@@ -8214,22 +9466,21 @@
     rmdirs=
 
-    origobjdir="$objdir"
     for file in $files; do
       func_dirname "$file" "" "."
       dir="$func_dirname_result"
       if test "X$dir" = X.; then
-	objdir="$origobjdir"
+	odir="$objdir"
       else
-	objdir="$dir/$origobjdir"
+	odir="$dir/$objdir"
       fi
       func_basename "$file"
       name="$func_basename_result"
-      test "$mode" = uninstall && objdir="$dir"
-
-      # Remember objdir for removal later, being careful to avoid duplicates
-      if test "$mode" = clean; then
+      test "$opt_mode" = uninstall && odir="$dir"
+
+      # Remember odir for removal later, being careful to avoid duplicates
+      if test "$opt_mode" = clean; then
 	case " $rmdirs " in
-	  *" $objdir "*) ;;
-	  *) rmdirs="$rmdirs $objdir" ;;
+	  *" $odir "*) ;;
+	  *) func_append rmdirs " $odir" ;;
 	esac
       fi
@@ -8257,16 +9508,15 @@
 	  # Delete the libtool libraries and symlinks.
 	  for n in $library_names; do
-	    rmfiles="$rmfiles $objdir/$n"
+	    func_append rmfiles " $odir/$n"
 	  done
-	  test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library"
-
-	  case "$mode" in
+	  test -n "$old_library" && func_append rmfiles " $odir/$old_library"
+
+	  case "$opt_mode" in
 	  clean)
-	    case "  $library_names " in
-	    # "  " in the beginning catches empty $dlname
+	    case " $library_names " in
 	    *" $dlname "*) ;;
-	    *) rmfiles="$rmfiles $objdir/$dlname" ;;
+	    *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;;
 	    esac
-	    test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i"
+	    test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i"
 	    ;;
 	  uninstall)
@@ -8296,5 +9546,5 @@
 	  if test -n "$pic_object" &&
 	     test "$pic_object" != none; then
-	    rmfiles="$rmfiles $dir/$pic_object"
+	    func_append rmfiles " $dir/$pic_object"
 	  fi
 
@@ -8302,5 +9552,5 @@
 	  if test -n "$non_pic_object" &&
 	     test "$non_pic_object" != none; then
-	    rmfiles="$rmfiles $dir/$non_pic_object"
+	    func_append rmfiles " $dir/$non_pic_object"
 	  fi
 	fi
@@ -8308,5 +9558,5 @@
 
       *)
-	if test "$mode" = clean ; then
+	if test "$opt_mode" = clean ; then
 	  noexename=$name
 	  case $file in
@@ -8318,5 +9568,5 @@
 	    # $file with .exe has already been added to rmfiles,
 	    # add $file without .exe
-	    rmfiles="$rmfiles $file"
+	    func_append rmfiles " $file"
 	    ;;
 	  esac
@@ -8327,5 +9577,5 @@
 	      relink_command=
 	      func_source $func_ltwrapper_scriptname_result
-	      rmfiles="$rmfiles $func_ltwrapper_scriptname_result"
+	      func_append rmfiles " $func_ltwrapper_scriptname_result"
 	    else
 	      relink_command=
@@ -8335,10 +9585,10 @@
 	    # note $name still contains .exe if it was in $file originally
 	    # as does the version of $file that was added into $rmfiles
-	    rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}"
+	    func_append rmfiles " $odir/$name $odir/${name}S.${objext}"
 	    if test "$fast_install" = yes && test -n "$relink_command"; then
-	      rmfiles="$rmfiles $objdir/lt-$name"
+	      func_append rmfiles " $odir/lt-$name"
 	    fi
 	    if test "X$noexename" != "X$name" ; then
-	      rmfiles="$rmfiles $objdir/lt-${noexename}.c"
+	      func_append rmfiles " $odir/lt-${noexename}.c"
 	    fi
 	  fi
@@ -8348,5 +9598,4 @@
       func_show_eval "$RM $rmfiles" 'exit_status=1'
     done
-    objdir="$origobjdir"
 
     # Try to remove the ${objdir}s in the directories where we deleted files
@@ -8360,8 +9609,8 @@
 }
 
-{ test "$mode" = uninstall || test "$mode" = clean; } &&
+{ test "$opt_mode" = uninstall || test "$opt_mode" = clean; } &&
     func_mode_uninstall ${1+"$@"}
 
-test -z "$mode" && {
+test -z "$opt_mode" && {
   help="$generic_help"
   func_fatal_help "you must specify a MODE"
@@ -8369,5 +9618,5 @@
 
 test -z "$exec_cmd" && \
-  func_fatal_help "invalid operation mode \`$mode'"
+  func_fatal_help "invalid operation mode \`$opt_mode'"
 
 if test -n "$exec_cmd"; then
Index: sm/trunk/m4/ar-lib.m4
===================================================================
--- /issm/trunk/m4/ar-lib.m4	(revision 13394)
+++ 	(revision )
@@ -1,61 +1,0 @@
-##                                                          -*- Autoconf -*-
-# Copyright (C) 2011 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# serial 1
-
-# AM_PROG_AR([ACT-IF-FAIL])
-# -------------------------
-# Try to determine the archiver interface, and trigger the ar-lib wrapper
-# if it is needed.  If the detection of archiver interface fails, run
-# ACT-IF-FAIL (default is to abort configure with a proper error message).
-AC_DEFUN([AM_PROG_AR],
-[AC_BEFORE([$0], [LT_INIT])dnl
-AC_BEFORE([$0], [AC_PROG_LIBTOOL])dnl
-AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
-AC_REQUIRE_AUX_FILE([ar-lib])dnl
-AC_CHECK_TOOLS([AR], [ar lib "link -lib"], [false])
-: ${AR=ar}
-
-AC_CACHE_CHECK([the archiver ($AR) interface], [am_cv_ar_interface],
-  [am_cv_ar_interface=ar
-   AC_COMPILE_IFELSE([AC_LANG_SOURCE([[int some_variable = 0;]])],
-     [am_ar_try='$AR cru libconftest.a conftest.$ac_objext >&AS_MESSAGE_LOG_FD'
-      AC_TRY_EVAL([am_ar_try])
-      if test "$ac_status" -eq 0; then
-        am_cv_ar_interface=ar
-      else
-        am_ar_try='$AR -NOLOGO -OUT:conftest.lib conftest.$ac_objext >&AS_MESSAGE_LOG_FD'
-        AC_TRY_EVAL([am_ar_try])
-        if test "$ac_status" -eq 0; then
-          am_cv_ar_interface=lib
-        else
-          am_cv_ar_interface=unknown
-        fi
-      fi
-      rm -f conftest.lib libconftest.a
-     ])
-   ])
-
-case $am_cv_ar_interface in
-ar)
-  ;;
-lib)
-  # Microsoft lib, so override with the ar-lib wrapper script.
-  # FIXME: It is wrong to rewrite AR.
-  # But if we don't then we get into trouble of one sort or another.
-  # A longer-term fix would be to have automake use am__AR in this case,
-  # and then we could set am__AR="$am_aux_dir/ar-lib \$(AR)" or something
-  # similar.
-  AR="$am_aux_dir/ar-lib $AR"
-  ;;
-unknown)
-  m4_default([$1],
-             [AC_MSG_ERROR([could not determine $AR interface])])
-  ;;
-esac
-AC_SUBST([AR])dnl
-])
Index: /issm/trunk/m4/issm_options.m4
===================================================================
--- /issm/trunk/m4/issm_options.m4	(revision 13394)
+++ /issm/trunk/m4/issm_options.m4	(revision 13395)
@@ -12,5 +12,22 @@
 		AC_DEFINE([_ISSM_DEBUG_],[1],[Macro to enable debugging in ISSM])
 	fi
-	dnl }}}
+
+	dnl }}}
+    dnl shared build {{{
+    AC_ARG_ENABLE([sharedlibs],                                                dnl feature
+        AS_HELP_STRING([--enable-sharedlibs], [produce libISSM.so.0]),         dnl help string
+        [enable_sharedlibs=$enableval],                                        dnl action if given
+        [enable_sharedlibs=no])                                                dnl action if not given
+    AM_CONDITIONAL([SHAREDLIBS], [test x$enable_sharedlibs = xyes])
+    dnl }}}
+
+    dnl shared build {{{
+    AC_ARG_ENABLE([version],                                                dnl feature
+        AS_HELP_STRING([--enable-version], [produce libISSM.so.0]),         dnl help string
+        [enable_version=$enableval],                                        dnl action if given
+        [enable_version=no])                                                dnl action if not given
+    AM_CONDITIONAL([VERSION], [test x$enable_VERSION = xyes])
+    dnl }}}
+
 	dnl Modules build {{{
 	AC_ARG_WITH([modules],
@@ -164,42 +181,46 @@
 		MATLABINCL=-I"$MATLAB_ROOT/extern/include";
 		
-		dnl OS-dependent variables and checks
-		case "${host_os}" in
-			*linux*)
-				if test "${host_cpu}" = "x86_64";
-				then
-					MEXLIB=-L"$MATLAB_ROOT/bin/glnxa64/ -lmex"
-					MEXLINK="-pthread -shared -W2,--version-script,${MATLAB_ROOT}/extern/lib/glnxa64/mexFunction.map";
-				else
-					MEXLIB=-L"$MATLAB_ROOT/bin/glnx86/ -lmex"
-					MEXLINK="-pthread -shared -W2,--version-script,${MATLAB_ROOT}/extern/lib/glnx86/mexFunction.map";
-				fi
-				MEXEXT=`$MATLAB_ROOT/bin/mexext`
-				MEXEXT=".$MEXEXT"
-			;;
-			*darwin*)
-				dnl mex -v gives all the flags for compilation of mex files
-				dnl if matlab version is 7.9 or more, we must use mexmaci64 (64 bits)
-				MEXLINK="-O -Wl,-flat_namespace -undefined suppress -arch i386 -bundle -Wl,-exported_symbols_list,$MATLAB_ROOT/extern/lib/maci/mexFunction.map"
-				MEXLIB=" -L$MATLAB_ROOT/bin/maci/ -lmx -lmex -lmat -lstdc++ -largeArrayDims"
-				if test $MATLAB_MAJOR -ge 7; then 
-					 if test $MATLAB_MINOR -ge 9; then 
-						  MEXLINK="-O -Wl,-flat_namespace -undefined suppress -bundle -Wl,-exported_symbols_list,$MATLAB_ROOT/extern/lib/maci64/mexFunction.map"
-							 MEXLIB=" -L$MATLAB_ROOT/bin/maci64/ -lmx -lmex -lmat -lstdc++"
-					 fi
-				fi
-				MEXEXT=`$MATLAB_ROOT/bin/mexext`
-				MEXEXT=".$MEXEXT"
-			;;
-			*cygwin*) 
-				if  test $VENDOR = intel-win7-32; then
-					MEXLIB="-dll -export:mexFunction -LIBPATH:\"$MATLAB_ROOT\extern\lib\win32\microsoft\" libmx.lib libmex.lib libmat.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  -NOLOGO -INCREMENTAL:NO -manifest" 
-				elif  test $VENDOR = intel-win7-64; then
-					MEXLIB="-dll -export:mexFunction -LIBPATH:\"$MATLAB_ROOT\extern\lib\win64\microsoft\" libmx.lib libmex.lib libmat.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  -NOLOGO -INCREMENTAL:NO -manifest" 
-				fi
-				MEXEXT=`$MATLAB_ROOT/bin/mexext.bat`
-				MEXEXT=".$MEXEXT"
-			;;
-		esac
+		dnl 4. get MEXLIB MEXLINK and MEXEXT (experimental)
+		MEXLINK=$(mex -v 2>&1 < /dev/null | grep LDFLAGS     | sed -e "s/         LDFLAGS            = //g")
+		MEXLIB=$( mex -v 2>&1 < /dev/null | grep CXXLIBS     | sed -e "s/         CXXLIBS            = //g")
+		MEXEXT=$( mex -v 2>&1 < /dev/null | grep LDEXTENSION | sed -e "s/         LDEXTENSION        = //g")
+		dnl dnl OS-dependent variables and checks (old stuff)
+		dnl case "${host_os}" in
+		dnl 	*linux*)
+		dnl 		if test "${host_cpu}" = "x86_64";
+		dnl 		then
+		dnl 			MEXLIB="-Wl,-rpath-link,$MATLAB_ROOT/bin/glnxa64 -L$MATLAB_ROOT/bin/glnxa64/ -lmx -lmex -lmat -lm"
+		dnl 			MEXLINK="-pthread -shared -W2,--version-script,${MATLAB_ROOT}/extern/lib/glnxa64/mexFunction.map";
+		dnl 		else
+		dnl 			MEXLIB=-L"$MATLAB_ROOT/bin/glnx86/ -lmex"
+		dnl 			MEXLINK="-pthread -shared -W2,--version-script,${MATLAB_ROOT}/extern/lib/glnx86/mexFunction.map";
+		dnl 		fi
+		dnl 		MEXEXT=`$MATLAB_ROOT/bin/mexext`
+		dnl 		MEXEXT=".$MEXEXT"
+		dnl 	;;
+		dnl 	*darwin*)
+		dnl 		dnl mex -v gives all the flags for compilation of mex files
+		dnl 		dnl if matlab version is 7.9 or more, we must use mexmaci64 (64 bits)
+		dnl 		MEXLINK="-O -Wl,-flat_namespace -undefined suppress -arch i386 -bundle -Wl,-exported_symbols_list,$MATLAB_ROOT/extern/lib/maci/mexFunction.map"
+		dnl 		MEXLIB=" -L$MATLAB_ROOT/bin/maci/ -lmx -lmex -lmat -lstdc++ -largeArrayDims"
+		dnl 		if test $MATLAB_MAJOR -ge 7; then 
+		dnl 			 if test $MATLAB_MINOR -ge 9; then 
+		dnl 				  MEXLINK="-O -Wl,-flat_namespace -undefined suppress -bundle -Wl,-exported_symbols_list,$MATLAB_ROOT/extern/lib/maci64/mexFunction.map"
+		dnl 					 MEXLIB=" -L$MATLAB_ROOT/bin/maci64/ -lmx -lmex -lmat -lstdc++"
+		dnl 			 fi
+		dnl 		fi
+		dnl 		MEXEXT=`$MATLAB_ROOT/bin/mexext`
+		dnl 		MEXEXT=".$MEXEXT"
+		dnl 	;;
+		dnl 	*cygwin*) 
+		dnl 		if  test $VENDOR = intel-win7-32; then
+		dnl 			MEXLIB="-dll -export:mexFunction -LIBPATH:\"$MATLAB_ROOT\extern\lib\win32\microsoft\" libmx.lib libmex.lib libmat.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  -NOLOGO -INCREMENTAL:NO -manifest" 
+		dnl 		elif  test $VENDOR = intel-win7-64; then
+		dnl 			MEXLIB="-dll -export:mexFunction -LIBPATH:\"$MATLAB_ROOT\extern\lib\win64\microsoft\" libmx.lib libmex.lib libmat.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  -NOLOGO -INCREMENTAL:NO -manifest" 
+		dnl 		fi
+		dnl 		MEXEXT=`$MATLAB_ROOT/bin/mexext.bat`
+		dnl 		MEXEXT=".$MEXEXT"
+		dnl 	;;
+		dnl esac
 	   AC_MSG_RESULT(done)
 
@@ -208,5 +229,5 @@
 		MATLABWRAPPEREXT=$MEXEXT
 		AC_SUBST([MATLABWRAPPEREXT])
-		AC_SUBST([MEXLIB]) 
+	    AC_SUBST([MEXLIB]) 
 		AC_SUBST([MEXLINK])
 	fi
@@ -315,5 +336,22 @@
 	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"
@@ -342,25 +380,7 @@
 	fi
 	AM_CONDITIONAL([PYTHON], [test x$HAVE_PYTHON = xyes])
+	AM_CONDITIONAL([PYTHON3], [test x$HAVE_PYTHON3 = xyes])
 	AC_MSG_RESULT($HAVE_PYTHON)
 
-	dnl python-version
-	HAVE_PYTHON3="no"
-	if test x$HAVE_PYTHON = xyes; then
-		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)
-	fi
-	AM_CONDITIONAL([PYTHON3], [test x$HAVE_PYTHON3 = xyes])
 	dnl }}}
 	dnl python-numpy{{{
@@ -373,5 +393,5 @@
 		dnl defaults
 		HAVE_PYTHON_NUMPY=yes
-		PYTHON_NUMPYINCL=-I$PYTHON_NUMPY_ROOT
+		PYTHON_NUMPYINCL="-I$PYTHON_NUMPY_ROOT -I$PYTHON_NUMPY_ROOT/core/include/numpy"
 
 		AC_DEFINE([_HAVE_PYTHON_NUMPY_],[1],[with Python-Numpy in ISSM src])
@@ -454,4 +474,13 @@
 	AC_MSG_RESULT($HAVE_ADOLC)
 	dnl }}}
+	dnl adolc-version{{{
+	AC_ARG_WITH([adolc-version],
+		AS_HELP_STRING([--with-adolc-version=number], [adolc version.]),
+		[ADOLC_VERSION=$withval],[ADOLC_VERSION=2]) 
+	AC_MSG_CHECKING(for adolc-version) 
+
+	AC_DEFINE_UNQUOTED([_ADOLC_VERSION_],$ADOLC_VERSION,[ADOLC version])
+	AC_MSG_RESULT($ADOLC_VERSION)
+	dnl }}}
 	dnl adic2{{{
 	AC_ARG_WITH([adic2-dir],
@@ -493,5 +522,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])
@@ -533,7 +562,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?
@@ -577,5 +606,5 @@
 				;;
 			esac
-	
+
 			METISINCL=-I"$METIS_ROOT/include" 
 			AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
@@ -589,9 +618,10 @@
 	fi
 	AM_CONDITIONAL([METIS], [test x$HAVE_METIS = xyes])
+	AC_MSG_RESULT($HAVE_METIS)
 	dnl }}}
 	dnl mpi{{{
 	AC_MSG_CHECKING(for mpi)
 	AC_ARG_WITH([mpi-lib],
-		AS_HELP_STRING([--with-mpi-lib = otions],[mpi options, for ex: "-L$MPIROOT -lmpich]),
+		AS_HELP_STRING([--with-mpi-lib = options],[mpi options, for ex: "-L$MPIROOT -lmpich]),
 		[MPILIB=$withval],[MPILIB=""])
 	
@@ -607,5 +637,5 @@
 		else
 			HAVE_MPI=yes
-			MPIINCL=-I"$MPI_INCLUDE/"
+			MPIINCL=-I"$MPI_INCLUDE"
 			AC_DEFINE([_HAVE_MPI_],[1],[with Mpi in ISSM src])
 			AC_DEFINE([HAVE_MPI],[1],[Mpi Flag for Dakota (DO NOT REMOVE)])
@@ -646,4 +676,7 @@
 	AC_MSG_CHECKING(for petsc headers and libraries in $PETSC_ROOT for architecture $PETSC_ARCH)
 	
+	dnl To ge PETSc's libraries:
+	dnl cd externalpackages/petsc/src
+	dnl make getlinklibs
 	if test -d "$PETSC_ROOT"; then
 
@@ -653,21 +686,21 @@
 			*cygwin*)
 			if test "$PETSC_MAJOR" = "2" ; then
-				PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/$PETSC_ARCH/lib\" -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib/$PETSC_ARCH\" libpetscksp.lib  libpetscdm.lib  libpetscmat.lib  libpetscvec.lib libpetscsnes.lib libpetscts.lib libmpiuni.lib libpetsc.lib"
+				PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib/$PETSC_ARCH\" libpetscksp.lib  libpetscdm.lib  libpetscmat.lib  libpetscvec.lib libpetscsnes.lib libpetscts.lib libmpiuni.lib libpetsc.lib"
 			else
-				PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/$PETSC_ARCH/lib\" -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib/$PETSC_ARCH\" libpetsc.lib"
+				PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib/$PETSC_ARCH\" libpetsc.lib"
 			fi
 			;;
 			*linux*)
 			if test "$PETSC_MAJOR" = "2" ; then
-			PETSCLIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetsc  -lpetscsnes -lpetscts"
+			PETSCLIB="-L$PETSC_ROOT/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetsc  -lpetscsnes -lpetscts"
 			else
-			PETSCLIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetsc"
+			PETSCLIB="-L$PETSC_ROOT/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetsc -ldl"
 			fi
 			;;
 			*darwin*)
 			if test "$PETSC_MAJOR" = "2" ; then
-			PETSCLIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib/$PETSC_ARCH/ -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lpetsc"
+			PETSCLIB="-L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH/ -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lpetsc"
 			else
-			PETSCLIB="-L$PETSC_ROOT/$PETSC_ARCH/lib -L$PETSC_ROOT/lib/$PETSC_ARCH/ -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetsc"
+			PETSCLIB="-L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH/ -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetsc"
 			fi
 			;;
@@ -1121,4 +1154,19 @@
 
 	dnl Capabilities
+	dnl with-kml{{{
+	AC_ARG_WITH([kml],
+		AS_HELP_STRING([--with-kml = YES],[compile with kml capabilities (default is yes)]),
+		[KML=$withval],[KML=yes]) 
+	AC_MSG_CHECKING(for kml capability compilation)
+
+	if test "x$KML" = "xyes"; then
+		HAVE_KML=yes
+		AC_DEFINE([_HAVE_KML_],[1],[with kml capability])
+	else
+		HAVE_KML=no
+	fi
+	AM_CONDITIONAL([KML], [test x$HAVE_KML = xyes])
+	AC_MSG_RESULT($HAVE_KML)
+	dnl }}}
 	dnl with-kriging{{{
 	AC_ARG_WITH([kriging],
Index: sm/trunk/m4/libtool.m4
===================================================================
--- /issm/trunk/m4/libtool.m4	(revision 13394)
+++ 	(revision )
@@ -1,7357 +1,0 @@
-# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
-#
-#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
-#                 2006, 2007, 2008 Free Software Foundation, Inc.
-#   Written by Gordon Matzigkeit, 1996
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-m4_define([_LT_COPYING], [dnl
-#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
-#                 2006, 2007, 2008 Free Software Foundation, Inc.
-#   Written by Gordon Matzigkeit, 1996
-#
-#   This file is part of GNU Libtool.
-#
-# GNU Libtool is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of
-# the License, or (at your option) any later version.
-#
-# As a special exception to the GNU General Public License,
-# if you distribute this file as part of a program or library that
-# is built using GNU Libtool, you may include this file under the
-# same distribution terms that you use for the rest of that program.
-#
-# GNU Libtool is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with GNU Libtool; see the file COPYING.  If not, a copy
-# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
-# obtained by writing to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-])
-
-# serial 56 LT_INIT
-
-
-# LT_PREREQ(VERSION)
-# ------------------
-# Complain and exit if this libtool version is less that VERSION.
-m4_defun([LT_PREREQ],
-[m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1,
-       [m4_default([$3],
-		   [m4_fatal([Libtool version $1 or higher is required],
-		             63)])],
-       [$2])])
-
-
-# _LT_CHECK_BUILDDIR
-# ------------------
-# Complain if the absolute build directory name contains unusual characters
-m4_defun([_LT_CHECK_BUILDDIR],
-[case `pwd` in
-  *\ * | *\	*)
-    AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;;
-esac
-])
-
-
-# LT_INIT([OPTIONS])
-# ------------------
-AC_DEFUN([LT_INIT],
-[AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT
-AC_BEFORE([$0], [LT_LANG])dnl
-AC_BEFORE([$0], [LT_OUTPUT])dnl
-AC_BEFORE([$0], [LTDL_INIT])dnl
-m4_require([_LT_CHECK_BUILDDIR])dnl
-
-dnl Autoconf doesn't catch unexpanded LT_ macros by default:
-m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl
-m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl
-dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4
-dnl unless we require an AC_DEFUNed macro:
-AC_REQUIRE([LTOPTIONS_VERSION])dnl
-AC_REQUIRE([LTSUGAR_VERSION])dnl
-AC_REQUIRE([LTVERSION_VERSION])dnl
-AC_REQUIRE([LTOBSOLETE_VERSION])dnl
-m4_require([_LT_PROG_LTMAIN])dnl
-
-dnl Parse OPTIONS
-_LT_SET_OPTIONS([$0], [$1])
-
-# This can be used to rebuild libtool when needed
-LIBTOOL_DEPS="$ltmain"
-
-# Always use our own libtool.
-LIBTOOL='$(SHELL) $(top_builddir)/libtool'
-AC_SUBST(LIBTOOL)dnl
-
-_LT_SETUP
-
-# Only expand once:
-m4_define([LT_INIT])
-])# LT_INIT
-
-# Old names:
-AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT])
-AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_PROG_LIBTOOL], [])
-dnl AC_DEFUN([AM_PROG_LIBTOOL], [])
-
-
-# _LT_CC_BASENAME(CC)
-# -------------------
-# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
-m4_defun([_LT_CC_BASENAME],
-[for cc_temp in $1""; do
-  case $cc_temp in
-    compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
-    distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$ECHO "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
-])
-
-
-# _LT_FILEUTILS_DEFAULTS
-# ----------------------
-# It is okay to use these file commands and assume they have been set
-# sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'.
-m4_defun([_LT_FILEUTILS_DEFAULTS],
-[: ${CP="cp -f"}
-: ${MV="mv -f"}
-: ${RM="rm -f"}
-])# _LT_FILEUTILS_DEFAULTS
-
-
-# _LT_SETUP
-# ---------
-m4_defun([_LT_SETUP],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_CANONICAL_BUILD])dnl
-_LT_DECL([], [host_alias], [0], [The host system])dnl
-_LT_DECL([], [host], [0])dnl
-_LT_DECL([], [host_os], [0])dnl
-dnl
-_LT_DECL([], [build_alias], [0], [The build system])dnl
-_LT_DECL([], [build], [0])dnl
-_LT_DECL([], [build_os], [0])dnl
-dnl
-AC_REQUIRE([AC_PROG_CC])dnl
-AC_REQUIRE([LT_PATH_LD])dnl
-AC_REQUIRE([LT_PATH_NM])dnl
-dnl
-AC_REQUIRE([AC_PROG_LN_S])dnl
-test -z "$LN_S" && LN_S="ln -s"
-_LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl
-dnl
-AC_REQUIRE([LT_CMD_MAX_LEN])dnl
-_LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl
-_LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl
-dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_CHECK_SHELL_FEATURES])dnl
-m4_require([_LT_CMD_RELOAD])dnl
-m4_require([_LT_CHECK_MAGIC_METHOD])dnl
-m4_require([_LT_CMD_OLD_ARCHIVE])dnl
-m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
-
-_LT_CONFIG_LIBTOOL_INIT([
-# See if we are running on zsh, and set the options which allow our
-# commands through without removal of \ escapes INIT.
-if test -n "\${ZSH_VERSION+set}" ; then
-   setopt NO_GLOB_SUBST
-fi
-])
-if test -n "${ZSH_VERSION+set}" ; then
-   setopt NO_GLOB_SUBST
-fi
-
-_LT_CHECK_OBJDIR
-
-m4_require([_LT_TAG_COMPILER])dnl
-_LT_PROG_ECHO_BACKSLASH
-
-case $host_os in
-aix3*)
-  # AIX sometimes has problems with the GCC collect2 program.  For some
-  # reason, if we set the COLLECT_NAMES environment variable, the problems
-  # vanish in a puff of smoke.
-  if test "X${COLLECT_NAMES+set}" != Xset; then
-    COLLECT_NAMES=
-    export COLLECT_NAMES
-  fi
-  ;;
-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
-can_build_shared=yes
-
-# All known linkers require a `.a' archive for static linking (except MSVC,
-# which needs '.lib').
-libext=a
-
-with_gnu_ld="$lt_cv_prog_gnu_ld"
-
-old_CC="$CC"
-old_CFLAGS="$CFLAGS"
-
-# Set sane defaults for various variables
-test -z "$CC" && CC=cc
-test -z "$LTCC" && LTCC=$CC
-test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
-test -z "$LD" && LD=ld
-test -z "$ac_objext" && ac_objext=o
-
-_LT_CC_BASENAME([$compiler])
-
-# Only perform the check for file, if the check method requires it
-test -z "$MAGIC_CMD" && MAGIC_CMD=file
-case $deplibs_check_method in
-file_magic*)
-  if test "$file_magic_cmd" = '$MAGIC_CMD'; then
-    _LT_PATH_MAGIC
-  fi
-  ;;
-esac
-
-# Use C for the default configuration in the libtool script
-LT_SUPPORTED_TAG([CC])
-_LT_LANG_C_CONFIG
-_LT_LANG_DEFAULT_CONFIG
-_LT_CONFIG_COMMANDS
-])# _LT_SETUP
-
-
-# _LT_PROG_LTMAIN
-# ---------------
-# Note that this code is called both from `configure', and `config.status'
-# now that we use AC_CONFIG_COMMANDS to generate libtool.  Notably,
-# `config.status' has no value for ac_aux_dir unless we are using Automake,
-# so we pass a copy along to make sure it has a sensible value anyway.
-m4_defun([_LT_PROG_LTMAIN],
-[m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl
-_LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir'])
-ltmain="$ac_aux_dir/ltmain.sh"
-])# _LT_PROG_LTMAIN
-
-
-## ------------------------------------- ##
-## Accumulate code for creating libtool. ##
-## ------------------------------------- ##
-
-# So that we can recreate a full libtool script including additional
-# tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS
-# in macros and then make a single call at the end using the `libtool'
-# label.
-
-
-# _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS])
-# ----------------------------------------
-# Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later.
-m4_define([_LT_CONFIG_LIBTOOL_INIT],
-[m4_ifval([$1],
-          [m4_append([_LT_OUTPUT_LIBTOOL_INIT],
-                     [$1
-])])])
-
-# Initialize.
-m4_define([_LT_OUTPUT_LIBTOOL_INIT])
-
-
-# _LT_CONFIG_LIBTOOL([COMMANDS])
-# ------------------------------
-# Register COMMANDS to be passed to AC_CONFIG_COMMANDS later.
-m4_define([_LT_CONFIG_LIBTOOL],
-[m4_ifval([$1],
-          [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS],
-                     [$1
-])])])
-
-# Initialize.
-m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS])
-
-
-# _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS])
-# -----------------------------------------------------
-m4_defun([_LT_CONFIG_SAVE_COMMANDS],
-[_LT_CONFIG_LIBTOOL([$1])
-_LT_CONFIG_LIBTOOL_INIT([$2])
-])
-
-
-# _LT_FORMAT_COMMENT([COMMENT])
-# -----------------------------
-# Add leading comment marks to the start of each line, and a trailing
-# full-stop to the whole comment if one is not present already.
-m4_define([_LT_FORMAT_COMMENT],
-[m4_ifval([$1], [
-m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])],
-              [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.])
-)])
-
-
-
-## ------------------------ ##
-## FIXME: Eliminate VARNAME ##
-## ------------------------ ##
-
-
-# _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?])
-# -------------------------------------------------------------------
-# CONFIGNAME is the name given to the value in the libtool script.
-# VARNAME is the (base) name used in the configure script.
-# VALUE may be 0, 1 or 2 for a computed quote escaped value based on
-# VARNAME.  Any other value will be used directly.
-m4_define([_LT_DECL],
-[lt_if_append_uniq([lt_decl_varnames], [$2], [, ],
-    [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name],
-	[m4_ifval([$1], [$1], [$2])])
-    lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3])
-    m4_ifval([$4],
-	[lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])])
-    lt_dict_add_subkey([lt_decl_dict], [$2],
-	[tagged?], [m4_ifval([$5], [yes], [no])])])
-])
-
-
-# _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION])
-# --------------------------------------------------------
-m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])])
-
-
-# lt_decl_tag_varnames([SEPARATOR], [VARNAME1...])
-# ------------------------------------------------
-m4_define([lt_decl_tag_varnames],
-[_lt_decl_filter([tagged?], [yes], $@)])
-
-
-# _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..])
-# ---------------------------------------------------------
-m4_define([_lt_decl_filter],
-[m4_case([$#],
-  [0], [m4_fatal([$0: too few arguments: $#])],
-  [1], [m4_fatal([$0: too few arguments: $#: $1])],
-  [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)],
-  [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)],
-  [lt_dict_filter([lt_decl_dict], $@)])[]dnl
-])
-
-
-# lt_decl_quote_varnames([SEPARATOR], [VARNAME1...])
-# --------------------------------------------------
-m4_define([lt_decl_quote_varnames],
-[_lt_decl_filter([value], [1], $@)])
-
-
-# lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...])
-# ---------------------------------------------------
-m4_define([lt_decl_dquote_varnames],
-[_lt_decl_filter([value], [2], $@)])
-
-
-# lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...])
-# ---------------------------------------------------
-m4_define([lt_decl_varnames_tagged],
-[m4_assert([$# <= 2])dnl
-_$0(m4_quote(m4_default([$1], [[, ]])),
-    m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]),
-    m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))])
-m4_define([_lt_decl_varnames_tagged],
-[m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])])
-
-
-# lt_decl_all_varnames([SEPARATOR], [VARNAME1...])
-# ------------------------------------------------
-m4_define([lt_decl_all_varnames],
-[_$0(m4_quote(m4_default([$1], [[, ]])),
-     m4_if([$2], [],
-	   m4_quote(lt_decl_varnames),
-	m4_quote(m4_shift($@))))[]dnl
-])
-m4_define([_lt_decl_all_varnames],
-[lt_join($@, lt_decl_varnames_tagged([$1],
-			lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl
-])
-
-
-# _LT_CONFIG_STATUS_DECLARE([VARNAME])
-# ------------------------------------
-# Quote a variable value, and forward it to `config.status' so that its
-# declaration there will have the same value as in `configure'.  VARNAME
-# 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"`'])
-
-
-# _LT_CONFIG_STATUS_DECLARATIONS
-# ------------------------------
-# We delimit libtool config variables with single quotes, so when
-# we write them to config.status, we have to be sure to quote all
-# embedded single quotes properly.  In configure, this macro expands
-# each variable declared with _LT_DECL (and _LT_TAGDECL) into:
-#
-#    <var>='`$ECHO "X$<var>" | $Xsed -e "$delay_single_quote_subst"`'
-m4_defun([_LT_CONFIG_STATUS_DECLARATIONS],
-[m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames),
-    [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])])
-
-
-# _LT_LIBTOOL_TAGS
-# ----------------
-# Output comment and list of tags supported by the script
-m4_defun([_LT_LIBTOOL_TAGS],
-[_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl
-available_tags="_LT_TAGS"dnl
-])
-
-
-# _LT_LIBTOOL_DECLARE(VARNAME, [TAG])
-# -----------------------------------
-# Extract the dictionary values for VARNAME (optionally with TAG) and
-# expand to a commented shell variable setting:
-#
-#    # Some comment about what VAR is for.
-#    visible_name=$lt_internal_name
-m4_define([_LT_LIBTOOL_DECLARE],
-[_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1],
-					   [description])))[]dnl
-m4_pushdef([_libtool_name],
-    m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl
-m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])),
-    [0], [_libtool_name=[$]$1],
-    [1], [_libtool_name=$lt_[]$1],
-    [2], [_libtool_name=$lt_[]$1],
-    [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl
-m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl
-])
-
-
-# _LT_LIBTOOL_CONFIG_VARS
-# -----------------------
-# Produce commented declarations of non-tagged libtool config variables
-# suitable for insertion in the LIBTOOL CONFIG section of the `libtool'
-# script.  Tagged libtool config variables (even for the LIBTOOL CONFIG
-# section) are produced by _LT_LIBTOOL_TAG_VARS.
-m4_defun([_LT_LIBTOOL_CONFIG_VARS],
-[m4_foreach([_lt_var],
-    m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)),
-    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])])
-
-
-# _LT_LIBTOOL_TAG_VARS(TAG)
-# -------------------------
-m4_define([_LT_LIBTOOL_TAG_VARS],
-[m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames),
-    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])])
-
-
-# _LT_TAGVAR(VARNAME, [TAGNAME])
-# ------------------------------
-m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])])
-
-
-# _LT_CONFIG_COMMANDS
-# -------------------
-# Send accumulated output to $CONFIG_STATUS.  Thanks to the lists of
-# variables for single and double quote escaping we saved from calls
-# to _LT_DECL, we can put quote escaped variables declarations
-# into `config.status', and then the shell code to quote escape them in
-# for loops in `config.status'.  Finally, any additional code accumulated
-# from calls to _LT_CONFIG_LIBTOOL_INIT is expanded.
-m4_defun([_LT_CONFIG_COMMANDS],
-[AC_PROVIDE_IFELSE([LT_OUTPUT],
-	dnl If the libtool generation code has been placed in $CONFIG_LT,
-	dnl instead of duplicating it all over again into config.status,
-	dnl then we will have config.status run $CONFIG_LT later, so it
-	dnl needs to know what name is stored there:
-        [AC_CONFIG_COMMANDS([libtool],
-            [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])],
-    dnl If the libtool generation code is destined for config.status,
-    dnl expand the accumulated commands and init code now:
-    [AC_CONFIG_COMMANDS([libtool],
-        [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])])
-])#_LT_CONFIG_COMMANDS
-
-
-# Initialize.
-m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT],
-[
-
-# 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
-
-sed_quote_subst='$sed_quote_subst'
-double_quote_subst='$double_quote_subst'
-delay_variable_subst='$delay_variable_subst'
-_LT_CONFIG_STATUS_DECLARATIONS
-LTCC='$LTCC'
-LTCFLAGS='$LTCFLAGS'
-compiler='$compiler_DEFAULT'
-
-# Quote evaled strings.
-for var in lt_decl_all_varnames([[ \
-]], lt_decl_quote_varnames); do
-    case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in
-    *[[\\\\\\\`\\"\\\$]]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
-      ;;
-    *)
-      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
-      ;;
-    esac
-done
-
-# Double-quote double-evaled strings.
-for var in lt_decl_all_varnames([[ \
-]], lt_decl_dquote_varnames); do
-    case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in
-    *[[\\\\\\\`\\"\\\$]]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
-      ;;
-    *)
-      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
-      ;;
-    esac
-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_OUTPUT
-# ---------
-# This macro allows early generation of the libtool script (before
-# AC_OUTPUT is called), incase it is used in configure for compilation
-# tests.
-AC_DEFUN([LT_OUTPUT],
-[: ${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_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
-{
-  echo
-  AS_BOX([Running $as_me.])
-} >&AS_MESSAGE_LOG_FD
-
-lt_cl_help="\
-\`$as_me' creates a local libtool stub from the current configuration,
-for use in further configure time tests before the real libtool is
-generated.
-
-Usage: $[0] [[OPTIONS]]
-
-  -h, --help      print this help, then exit
-  -V, --version   print version number, then exit
-  -q, --quiet     do not print progress messages
-  -d, --debug     don't remove temporary files
-
-Report bugs to <bug-libtool@gnu.org>."
-
-lt_cl_version="\
-m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl
-m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION])
-configured by $[0], generated by m4_PACKAGE_STRING.
-
-Copyright (C) 2008 Free Software Foundation, Inc.
-This config.lt script is free software; the Free Software Foundation
-gives unlimited permision to copy, distribute and modify it."
-
-while test $[#] != 0
-do
-  case $[1] in
-    --version | --v* | -V )
-      echo "$lt_cl_version"; exit 0 ;;
-    --help | --h* | -h )
-      echo "$lt_cl_help"; exit 0 ;;
-    --debug | --d* | -d )
-      debug=: ;;
-    --quiet | --q* | --silent | --s* | -q )
-      lt_cl_silent=: ;;
-
-    -*) AC_MSG_ERROR([unrecognized option: $[1]
-Try \`$[0] --help' for more information.]) ;;
-
-    *) AC_MSG_ERROR([unrecognized argument: $[1]
-Try \`$[0] --help' for more information.]) ;;
-  esac
-  shift
-done
-
-if $lt_cl_silent; then
-  exec AS_MESSAGE_FD>/dev/null
-fi
-_LTEOF
-
-cat >>"$CONFIG_LT" <<_LTEOF
-_LT_OUTPUT_LIBTOOL_COMMANDS_INIT
-_LTEOF
-
-cat >>"$CONFIG_LT" <<\_LTEOF
-AC_MSG_NOTICE([creating $ofile])
-_LT_OUTPUT_LIBTOOL_COMMANDS
-AS_EXIT(0)
-_LTEOF
-chmod +x "$CONFIG_LT"
-
-# configure is writing to config.log, but config.lt does its own redirection,
-# appending to config.log, which fails on DOS, as config.log is still kept
-# 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_OUTPUT
-
-
-# _LT_CONFIG(TAG)
-# ---------------
-# If TAG is the built-in tag, create an initial libtool script with a
-# default configuration from the untagged config vars.  Otherwise add code
-# to config.status for appending the configuration named by TAG from the
-# matching tagged config vars.
-m4_defun([_LT_CONFIG],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-_LT_CONFIG_SAVE_COMMANDS([
-  m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl
-  m4_if(_LT_TAG, [C], [
-    # See if we are running on zsh, and set the options which allow our
-    # commands through without removal of \ escapes.
-    if test -n "${ZSH_VERSION+set}" ; then
-      setopt NO_GLOB_SUBST
-    fi
-
-    cfgfile="${ofile}T"
-    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
-    $RM "$cfgfile"
-
-    cat <<_LT_EOF >> "$cfgfile"
-#! $SHELL
-
-# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
-# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
-# NOTE: Changes made to this file will be lost: look at ltmain.sh.
-#
-_LT_COPYING
-_LT_LIBTOOL_TAGS
-
-# ### BEGIN LIBTOOL CONFIG
-_LT_LIBTOOL_CONFIG_VARS
-_LT_LIBTOOL_TAG_VARS
-# ### END LIBTOOL CONFIG
-
-_LT_EOF
-
-  case $host_os in
-  aix3*)
-    cat <<\_LT_EOF >> "$cfgfile"
-# AIX sometimes has problems with the GCC collect2 program.  For some
-# reason, if we set the COLLECT_NAMES environment variable, the problems
-# vanish in a puff of smoke.
-if test "X${COLLECT_NAMES+set}" != Xset; then
-  COLLECT_NAMES=
-  export COLLECT_NAMES
-fi
-_LT_EOF
-    ;;
-  esac
-
-  _LT_PROG_LTMAIN
-
-  # We use sed instead of cat because bash on DJGPP gets confused if
-  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
-  # 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" ||
-    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
-  chmod +x "$ofile"
-],
-[cat <<_LT_EOF >> "$ofile"
-
-dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded
-dnl in a comment (ie after a #).
-# ### BEGIN LIBTOOL TAG CONFIG: $1
-_LT_LIBTOOL_TAG_VARS(_LT_TAG)
-# ### END LIBTOOL TAG CONFIG: $1
-_LT_EOF
-])dnl /m4_if
-],
-[m4_if([$1], [], [
-    PACKAGE='$PACKAGE'
-    VERSION='$VERSION'
-    TIMESTAMP='$TIMESTAMP'
-    RM='$RM'
-    ofile='$ofile'], [])
-])dnl /_LT_CONFIG_SAVE_COMMANDS
-])# _LT_CONFIG
-
-
-# LT_SUPPORTED_TAG(TAG)
-# ---------------------
-# Trace this macro to discover what tags are supported by the libtool
-# --tag option, using:
-#    autoconf --trace 'LT_SUPPORTED_TAG:$1'
-AC_DEFUN([LT_SUPPORTED_TAG], [])
-
-
-# C support is built-in for now
-m4_define([_LT_LANG_C_enabled], [])
-m4_define([_LT_TAGS], [])
-
-
-# LT_LANG(LANG)
-# -------------
-# Enable libtool support for the given language if not already enabled.
-AC_DEFUN([LT_LANG],
-[AC_BEFORE([$0], [LT_OUTPUT])dnl
-m4_case([$1],
-  [C],			[_LT_LANG(C)],
-  [C++],		[_LT_LANG(CXX)],
-  [Java],		[_LT_LANG(GCJ)],
-  [Fortran 77],		[_LT_LANG(F77)],
-  [Fortran],		[_LT_LANG(FC)],
-  [Windows Resource],	[_LT_LANG(RC)],
-  [m4_ifdef([_LT_LANG_]$1[_CONFIG],
-    [_LT_LANG($1)],
-    [m4_fatal([$0: unsupported language: "$1"])])])dnl
-])# LT_LANG
-
-
-# _LT_LANG(LANGNAME)
-# ------------------
-m4_defun([_LT_LANG],
-[m4_ifdef([_LT_LANG_]$1[_enabled], [],
-  [LT_SUPPORTED_TAG([$1])dnl
-  m4_append([_LT_TAGS], [$1 ])dnl
-  m4_define([_LT_LANG_]$1[_enabled], [])dnl
-  _LT_LANG_$1_CONFIG($1)])dnl
-])# _LT_LANG
-
-
-# _LT_LANG_DEFAULT_CONFIG
-# -----------------------
-m4_defun([_LT_LANG_DEFAULT_CONFIG],
-[AC_PROVIDE_IFELSE([AC_PROG_CXX],
-  [LT_LANG(CXX)],
-  [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])])
-
-AC_PROVIDE_IFELSE([AC_PROG_F77],
-  [LT_LANG(F77)],
-  [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])])
-
-AC_PROVIDE_IFELSE([AC_PROG_FC],
-  [LT_LANG(FC)],
-  [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])])
-
-dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal
-dnl pulling things in needlessly.
-AC_PROVIDE_IFELSE([AC_PROG_GCJ],
-  [LT_LANG(GCJ)],
-  [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],
-    [LT_LANG(GCJ)],
-    [AC_PROVIDE_IFELSE([LT_PROG_GCJ],
-      [LT_LANG(GCJ)],
-      [m4_ifdef([AC_PROG_GCJ],
-	[m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])])
-       m4_ifdef([A][M_PROG_GCJ],
-	[m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])])
-       m4_ifdef([LT_PROG_GCJ],
-	[m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])])
-
-AC_PROVIDE_IFELSE([LT_PROG_RC],
-  [LT_LANG(RC)],
-  [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])])
-])# _LT_LANG_DEFAULT_CONFIG
-
-# Obsolete macros:
-AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)])
-AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)])
-AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)])
-AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_CXX], [])
-dnl AC_DEFUN([AC_LIBTOOL_F77], [])
-dnl AC_DEFUN([AC_LIBTOOL_FC], [])
-dnl AC_DEFUN([AC_LIBTOOL_GCJ], [])
-
-
-# _LT_TAG_COMPILER
-# ----------------
-m4_defun([_LT_TAG_COMPILER],
-[AC_REQUIRE([AC_PROG_CC])dnl
-
-_LT_DECL([LTCC], [CC], [1], [A C compiler])dnl
-_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl
-_LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl
-_LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl
-
-# If no C compiler was specified, use CC.
-LTCC=${LTCC-"$CC"}
-
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
-
-# Allow CC to be a program name with arguments.
-compiler=$CC
-])# _LT_TAG_COMPILER
-
-
-# _LT_COMPILER_BOILERPLATE
-# ------------------------
-# Check for compiler boilerplate output or warnings with
-# the simple compiler test code.
-m4_defun([_LT_COMPILER_BOILERPLATE],
-[m4_require([_LT_DECL_SED])dnl
-ac_outfile=conftest.$ac_objext
-echo "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=`cat conftest.err`
-$RM conftest*
-])# _LT_COMPILER_BOILERPLATE
-
-
-# _LT_LINKER_BOILERPLATE
-# ----------------------
-# Check for linker boilerplate output or warnings with
-# the simple link test code.
-m4_defun([_LT_LINKER_BOILERPLATE],
-[m4_require([_LT_DECL_SED])dnl
-ac_outfile=conftest.$ac_objext
-echo "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=`cat conftest.err`
-$RM -r conftest*
-])# _LT_LINKER_BOILERPLATE
-
-# _LT_REQUIRED_DARWIN_CHECKS
-# -------------------------
-m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[
-  case $host_os in
-    rhapsody* | darwin*)
-    AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:])
-    AC_CHECK_TOOL([NMEDIT], [nmedit], [:])
-    AC_CHECK_TOOL([LIPO], [lipo], [:])
-    AC_CHECK_TOOL([OTOOL], [otool], [:])
-    AC_CHECK_TOOL([OTOOL64], [otool64], [:])
-    _LT_DECL([], [DSYMUTIL], [1],
-      [Tool to manipulate archived DWARF debug symbol files on Mac OS X])
-    _LT_DECL([], [NMEDIT], [1],
-      [Tool to change global to local symbols on Mac OS X])
-    _LT_DECL([], [LIPO], [1],
-      [Tool to manipulate fat objects and archives on Mac OS X])
-    _LT_DECL([], [OTOOL], [1],
-      [ldd/readelf like tool for Mach-O binaries on Mac OS X])
-    _LT_DECL([], [OTOOL64], [1],
-      [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4])
-
-    AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod],
-      [lt_cv_apple_cc_single_mod=no
-      if test -z "${LT_MULTI_MODULE}"; then
-	# By default we will add the -single_module flag. You can override
-	# by either setting the environment variable LT_MULTI_MODULE
-	# non-empty at configure time, or by adding -multi_module to the
-	# link flags.
-	rm -rf libconftest.dylib*
-	echo "int foo(void){return 1;}" > conftest.c
-	echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
--dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD
-	$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
-	  -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
-	  lt_cv_apple_cc_single_mod=yes
-	else
-	  cat conftest.err >&AS_MESSAGE_LOG_FD
-	fi
-	rm -rf libconftest.dylib*
-	rm -f conftest.*
-      fi])
-    AC_CACHE_CHECK([for -exported_symbols_list linker flag],
-      [lt_cv_ld_exported_symbols_list],
-      [lt_cv_ld_exported_symbols_list=no
-      save_LDFLAGS=$LDFLAGS
-      echo "_main" > conftest.sym
-      LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
-      AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
-	[lt_cv_ld_exported_symbols_list=yes],
-	[lt_cv_ld_exported_symbols_list=no])
-	LDFLAGS="$save_LDFLAGS"
-    ])
-    case $host_os in
-    rhapsody* | darwin1.[[012]])
-      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
-    darwin1.*)
-      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
-    darwin*) # darwin 5.x on
-      # if running on 10.5 or later, the deployment target defaults
-      # to the OS version, if on x86, and 10.4, the deployment
-      # target defaults to 10.4. Don't you love it?
-      case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
-	10.0,*86*-darwin8*|10.0,*-darwin[[91]]*)
-	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
-	10.[[012]]*)
-	  _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
-	10.*)
-	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
-      esac
-    ;;
-  esac
-    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
-      _lt_dar_single_mod='$single_module'
-    fi
-    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
-      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
-    else
-      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
-    fi
-    if test "$DSYMUTIL" != ":"; then
-      _lt_dsymutil='~$DSYMUTIL $lib || :'
-    else
-      _lt_dsymutil=
-    fi
-    ;;
-  esac
-])
-
-
-# _LT_DARWIN_LINKER_FEATURES
-# --------------------------
-# Checks for linker and compiler features on darwin
-m4_defun([_LT_DARWIN_LINKER_FEATURES],
-[
-  m4_require([_LT_REQUIRED_DARWIN_CHECKS])
-  _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-  _LT_TAGVAR(hardcode_direct, $1)=no
-  _LT_TAGVAR(hardcode_automatic, $1)=yes
-  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
-  _LT_TAGVAR(whole_archive_flag_spec, $1)=''
-  _LT_TAGVAR(link_all_deplibs, $1)=yes
-  _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined"
-  case $cc_basename in
-     ifort*) _lt_dar_can_shared=yes ;;
-     *) _lt_dar_can_shared=$GCC ;;
-  esac
-  if test "$_lt_dar_can_shared" = "yes"; then
-    output_verbose_link_cmd=echo
-    _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}"
-    _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
-    _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
-    m4_if([$1], [CXX],
-[   if test "$lt_cv_apple_cc_single_mod" != "yes"; then
-      _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}"
-      _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}"
-    fi
-],[])
-  else
-  _LT_TAGVAR(ld_shlibs, $1)=no
-  fi
-])
-
-# _LT_SYS_MODULE_PATH_AIX
-# -----------------------
-# Links a minimal program and checks the executable
-# for the system default hardcoded library path. In most cases,
-# this is /usr/lib:/lib, but when the MPI compilers are used
-# the location of the communication and MPI libs are included too.
-# If we don't find anything, use the default library path according
-# to the aix ld manual.
-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
-])# _LT_SYS_MODULE_PATH_AIX
-
-
-# _LT_SHELL_INIT(ARG)
-# -------------------
-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
-
-
-# _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.
-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','`
-  ;;
-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)
-])
-_LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts])
-_LT_DECL([], [ECHO], [1],
-    [An echo program that does not interpret backslashes])
-])# _LT_PROG_ECHO_BACKSLASH
-
-
-# _LT_ENABLE_LOCK
-# ---------------
-m4_defun([_LT_ENABLE_LOCK],
-[AC_ARG_ENABLE([libtool-lock],
-  [AS_HELP_STRING([--disable-libtool-lock],
-    [avoid locking (might break parallel builds)])])
-test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
-
-# Some flags need to be propagated to the compiler or linker for good
-# libtool support.
-case $host in
-ia64-*-hpux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.$ac_objext` in
-      *ELF-32*)
-	HPUX_IA64_MODE="32"
-	;;
-      *ELF-64*)
-	HPUX_IA64_MODE="64"
-	;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-*-*-irix6*)
-  # Find out which ABI we are using.
-  echo '[#]line __oline__ "configure"' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    if test "$lt_cv_prog_gnu_ld" = yes; then
-      case `/usr/bin/file conftest.$ac_objext` in
-	*32-bit*)
-	  LD="${LD-ld} -melf32bsmip"
-	  ;;
-	*N32*)
-	  LD="${LD-ld} -melf32bmipn32"
-	  ;;
-	*64-bit*)
-	  LD="${LD-ld} -melf64bmip"
-	;;
-      esac
-    else
-      case `/usr/bin/file conftest.$ac_objext` in
-	*32-bit*)
-	  LD="${LD-ld} -32"
-	  ;;
-	*N32*)
-	  LD="${LD-ld} -n32"
-	  ;;
-	*64-bit*)
-	  LD="${LD-ld} -64"
-	  ;;
-      esac
-    fi
-  fi
-  rm -rf conftest*
-  ;;
-
-x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \
-s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.o` in
-      *32-bit*)
-	case $host in
-	  x86_64-*kfreebsd*-gnu)
-	    LD="${LD-ld} -m elf_i386_fbsd"
-	    ;;
-	  x86_64-*linux*)
-	    LD="${LD-ld} -m elf_i386"
-	    ;;
-	  ppc64-*linux*|powerpc64-*linux*)
-	    LD="${LD-ld} -m elf32ppclinux"
-	    ;;
-	  s390x-*linux*)
-	    LD="${LD-ld} -m elf_s390"
-	    ;;
-	  sparc64-*linux*)
-	    LD="${LD-ld} -m elf32_sparc"
-	    ;;
-	esac
-	;;
-      *64-bit*)
-	case $host in
-	  x86_64-*kfreebsd*-gnu)
-	    LD="${LD-ld} -m elf_x86_64_fbsd"
-	    ;;
-	  x86_64-*linux*)
-	    LD="${LD-ld} -m elf_x86_64"
-	    ;;
-	  ppc*-*linux*|powerpc*-*linux*)
-	    LD="${LD-ld} -m elf64ppc"
-	    ;;
-	  s390*-*linux*|s390*-*tpf*)
-	    LD="${LD-ld} -m elf64_s390"
-	    ;;
-	  sparc*-*linux*)
-	    LD="${LD-ld} -m elf64_sparc"
-	    ;;
-	esac
-	;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-
-*-*-sco3.2v5*)
-  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
-  SAVE_CFLAGS="$CFLAGS"
-  CFLAGS="$CFLAGS -belf"
-  AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
-    [AC_LANG_PUSH(C)
-     AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no])
-     AC_LANG_POP])
-  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
-    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
-    CFLAGS="$SAVE_CFLAGS"
-  fi
-  ;;
-sparc*-*solaris*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.o` in
-    *64-bit*)
-      case $lt_cv_prog_gnu_ld in
-      yes*) LD="${LD-ld} -m elf64_sparc" ;;
-      *)
-	if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
-	  LD="${LD-ld} -64"
-	fi
-	;;
-      esac
-      ;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-esac
-
-need_locks="$enable_libtool_lock"
-])# _LT_ENABLE_LOCK
-
-
-# _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])
-
-AC_CHECK_TOOL(STRIP, strip, :)
-test -z "$STRIP" && STRIP=:
-_LT_DECL([], [STRIP], [1], [A symbol stripping program])
-
-AC_CHECK_TOOL(RANLIB, ranlib, :)
-test -z "$RANLIB" && RANLIB=:
-_LT_DECL([], [RANLIB], [1],
-    [Commands used to install an old-style archive])
-
-# Determine commands to create old-style static archives.
-old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
-old_postinstall_cmds='chmod 644 $oldlib'
-old_postuninstall_cmds=
-
-if test -n "$RANLIB"; then
-  case $host_os in
-  openbsd*)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib"
-    ;;
-  *)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib"
-    ;;
-  esac
-  old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib"
-fi
-_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_CMD_OLD_ARCHIVE
-
-
-# _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
-#		[OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE])
-# ----------------------------------------------------------------
-# Check whether the given compiler option works
-AC_DEFUN([_LT_COMPILER_OPTION],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_SED])dnl
-AC_CACHE_CHECK([$1], [$2],
-  [$2=no
-   m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4])
-   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag="$3"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   # The option is referenced via a variable to avoid confusing sed.
-   lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:__oline__: $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
-   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
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
-       $2=yes
-     fi
-   fi
-   $RM conftest*
-])
-
-if test x"[$]$2" = xyes; then
-    m4_if([$5], , :, [$5])
-else
-    m4_if([$6], , :, [$6])
-fi
-])# _LT_COMPILER_OPTION
-
-# Old name:
-AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], [])
-
-
-# _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
-#                  [ACTION-SUCCESS], [ACTION-FAILURE])
-# ----------------------------------------------------
-# Check whether the given linker option works
-AC_DEFUN([_LT_LINKER_OPTION],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_SED])dnl
-AC_CACHE_CHECK([$1], [$2],
-  [$2=no
-   save_LDFLAGS="$LDFLAGS"
-   LDFLAGS="$LDFLAGS $3"
-   echo "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # 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
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         $2=yes
-       fi
-     else
-       $2=yes
-     fi
-   fi
-   $RM -r conftest*
-   LDFLAGS="$save_LDFLAGS"
-])
-
-if test x"[$]$2" = xyes; then
-    m4_if([$4], , :, [$4])
-else
-    m4_if([$5], , :, [$5])
-fi
-])# _LT_LINKER_OPTION
-
-# Old name:
-AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], [])
-
-
-# LT_CMD_MAX_LEN
-#---------------
-AC_DEFUN([LT_CMD_MAX_LEN],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-# find the maximum length of command line arguments
-AC_MSG_CHECKING([the maximum length of command line arguments])
-AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
-  i=0
-  teststring="ABCD"
-
-  case $build_os in
-  msdosdjgpp*)
-    # On DJGPP, this test can blow up pretty badly due to problems in libc
-    # (any single argument exceeding 2000 bytes causes a buffer overrun
-    # during glob expansion).  Even if it were fixed, the result of this
-    # check would be larger than it should be.
-    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
-    ;;
-
-  gnu*)
-    # Under GNU Hurd, this test is not required because there is
-    # no limit to the length of command line arguments.
-    # Libtool will interpret -1 as no limit whatsoever
-    lt_cv_sys_max_cmd_len=-1;
-    ;;
-
-  cygwin* | mingw* | cegcc*)
-    # On Win9x/ME, this test blows up -- it succeeds, but takes
-    # about 5 minutes as the teststring grows exponentially.
-    # Worse, since 9x/ME are not pre-emptively multitasking,
-    # you end up with a "frozen" computer, even though with patience
-    # the test eventually succeeds (with a max line length of 256k).
-    # 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;
-    ;;
-
-  amigaos*)
-    # On AmigaOS with pdksh, this test takes hours, literally.
-    # So we just punt and use a minimum line length of 8192.
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
-
-  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
-    # This has been around since 386BSD, at least.  Likely further.
-    if test -x /sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
-    elif test -x /usr/sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
-    else
-      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
-    fi
-    # And add a safety zone
-    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
-    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
-    ;;
-
-  interix*)
-    # We know the value 262144 and hardcode it with a safety zone (like BSD)
-    lt_cv_sys_max_cmd_len=196608
-    ;;
-
-  osf*)
-    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
-    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
-    # nice to cause kernel panics so lets avoid the loop below.
-    # First set a reasonable default.
-    lt_cv_sys_max_cmd_len=16384
-    #
-    if test -x /sbin/sysconfig; then
-      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
-        *1*) lt_cv_sys_max_cmd_len=-1 ;;
-      esac
-    fi
-    ;;
-  sco3.2v5*)
-    lt_cv_sys_max_cmd_len=102400
-    ;;
-  sysv5* | sco5v6* | sysv4.2uw2*)
-    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
-    if test -n "$kargmax"; then
-      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[	 ]]//'`
-    else
-      lt_cv_sys_max_cmd_len=32768
-    fi
-    ;;
-  *)
-    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
-    if test -n "$lt_cv_sys_max_cmd_len"; then
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
-    else
-      # Make teststring a little bigger before we do anything with it.
-      # a 1K string should be a reasonable start.
-      for i in 1 2 3 4 5 6 7 8 ; do
-        teststring=$teststring$teststring
-      done
-      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
-      # If test is not a shell built-in, we'll probably end up computing a
-      # 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 &&
-	      test $i != 17 # 1/2 MB should be enough
-      do
-        i=`expr $i + 1`
-        teststring=$teststring$teststring
-      done
-      # Only check the string length outside the loop.
-      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
-      teststring=
-      # Add a significant safety factor because C++ compilers can tack on
-      # massive amounts of additional arguments before passing them to the
-      # linker.  It appears as though 1/2 is a usable value.
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
-    fi
-    ;;
-  esac
-])
-if test -n $lt_cv_sys_max_cmd_len ; then
-  AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
-else
-  AC_MSG_RESULT(none)
-fi
-max_cmd_len=$lt_cv_sys_max_cmd_len
-_LT_DECL([], [max_cmd_len], [0],
-    [What is the maximum length of a command?])
-])# LT_CMD_MAX_LEN
-
-# Old name:
-AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], [])
-
-
-# _LT_HEADER_DLFCN
-# ----------------
-m4_defun([_LT_HEADER_DLFCN],
-[AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl
-])# _LT_HEADER_DLFCN
-
-
-# _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
-#                      ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
-# ----------------------------------------------------------------
-m4_defun([_LT_TRY_DLOPEN_SELF],
-[m4_require([_LT_HEADER_DLFCN])dnl
-if test "$cross_compiling" = yes; then :
-  [$4]
-else
-  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
-  lt_status=$lt_dlunknown
-  cat > conftest.$ac_ext <<_LT_EOF
-[#line __oline__ "configure"
-#include "confdefs.h"
-
-#if HAVE_DLFCN_H
-#include <dlfcn.h>
-#endif
-
-#include <stdio.h>
-
-#ifdef RTLD_GLOBAL
-#  define LT_DLGLOBAL		RTLD_GLOBAL
-#else
-#  ifdef DL_GLOBAL
-#    define LT_DLGLOBAL		DL_GLOBAL
-#  else
-#    define LT_DLGLOBAL		0
-#  endif
-#endif
-
-/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
-   find out it does not work in some platform. */
-#ifndef LT_DLLAZY_OR_NOW
-#  ifdef RTLD_LAZY
-#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
-#  else
-#    ifdef DL_LAZY
-#      define LT_DLLAZY_OR_NOW		DL_LAZY
-#    else
-#      ifdef RTLD_NOW
-#        define LT_DLLAZY_OR_NOW	RTLD_NOW
-#      else
-#        ifdef DL_NOW
-#          define LT_DLLAZY_OR_NOW	DL_NOW
-#        else
-#          define LT_DLLAZY_OR_NOW	0
-#        endif
-#      endif
-#    endif
-#  endif
-#endif
-
-void fnord() { int i=42;}
-int main ()
-{
-  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
-  int status = $lt_dlunknown;
-
-  if (self)
-    {
-      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
-      else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
-      /* dlclose (self); */
-    }
-  else
-    puts (dlerror ());
-
-  return status;
-}]
-_LT_EOF
-  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
-    (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
-    lt_status=$?
-    case x$lt_status in
-      x$lt_dlno_uscore) $1 ;;
-      x$lt_dlneed_uscore) $2 ;;
-      x$lt_dlunknown|x*) $3 ;;
-    esac
-  else :
-    # compilation failed
-    $3
-  fi
-fi
-rm -fr conftest*
-])# _LT_TRY_DLOPEN_SELF
-
-
-# LT_SYS_DLOPEN_SELF
-# ------------------
-AC_DEFUN([LT_SYS_DLOPEN_SELF],
-[m4_require([_LT_HEADER_DLFCN])dnl
-if test "x$enable_dlopen" != xyes; then
-  enable_dlopen=unknown
-  enable_dlopen_self=unknown
-  enable_dlopen_self_static=unknown
-else
-  lt_cv_dlopen=no
-  lt_cv_dlopen_libs=
-
-  case $host_os in
-  beos*)
-    lt_cv_dlopen="load_add_on"
-    lt_cv_dlopen_libs=
-    lt_cv_dlopen_self=yes
-    ;;
-
-  mingw* | pw32* | cegcc*)
-    lt_cv_dlopen="LoadLibrary"
-    lt_cv_dlopen_libs=
-    ;;
-
-  cygwin*)
-    lt_cv_dlopen="dlopen"
-    lt_cv_dlopen_libs=
-    ;;
-
-  darwin*)
-  # if libdl is installed we need to link against it
-    AC_CHECK_LIB([dl], [dlopen],
-		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[
-    lt_cv_dlopen="dyld"
-    lt_cv_dlopen_libs=
-    lt_cv_dlopen_self=yes
-    ])
-    ;;
-
-  *)
-    AC_CHECK_FUNC([shl_load],
-	  [lt_cv_dlopen="shl_load"],
-      [AC_CHECK_LIB([dld], [shl_load],
-	    [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"],
-	[AC_CHECK_FUNC([dlopen],
-	      [lt_cv_dlopen="dlopen"],
-	  [AC_CHECK_LIB([dl], [dlopen],
-		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],
-	    [AC_CHECK_LIB([svld], [dlopen],
-		  [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"],
-	      [AC_CHECK_LIB([dld], [dld_link],
-		    [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"])
-	      ])
-	    ])
-	  ])
-	])
-      ])
-    ;;
-  esac
-
-  if test "x$lt_cv_dlopen" != xno; then
-    enable_dlopen=yes
-  else
-    enable_dlopen=no
-  fi
-
-  case $lt_cv_dlopen in
-  dlopen)
-    save_CPPFLAGS="$CPPFLAGS"
-    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
-
-    save_LDFLAGS="$LDFLAGS"
-    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
-
-    save_LIBS="$LIBS"
-    LIBS="$lt_cv_dlopen_libs $LIBS"
-
-    AC_CACHE_CHECK([whether a program can dlopen itself],
-	  lt_cv_dlopen_self, [dnl
-	  _LT_TRY_DLOPEN_SELF(
-	    lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes,
-	    lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross)
-    ])
-
-    if test "x$lt_cv_dlopen_self" = xyes; then
-      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
-      AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
-	  lt_cv_dlopen_self_static, [dnl
-	  _LT_TRY_DLOPEN_SELF(
-	    lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes,
-	    lt_cv_dlopen_self_static=no,  lt_cv_dlopen_self_static=cross)
-      ])
-    fi
-
-    CPPFLAGS="$save_CPPFLAGS"
-    LDFLAGS="$save_LDFLAGS"
-    LIBS="$save_LIBS"
-    ;;
-  esac
-
-  case $lt_cv_dlopen_self in
-  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
-  *) enable_dlopen_self=unknown ;;
-  esac
-
-  case $lt_cv_dlopen_self_static in
-  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
-  *) enable_dlopen_self_static=unknown ;;
-  esac
-fi
-_LT_DECL([dlopen_support], [enable_dlopen], [0],
-	 [Whether dlopen is supported])
-_LT_DECL([dlopen_self], [enable_dlopen_self], [0],
-	 [Whether dlopen of programs is supported])
-_LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0],
-	 [Whether dlopen of statically linked programs is supported])
-])# LT_SYS_DLOPEN_SELF
-
-# Old name:
-AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], [])
-
-
-# _LT_COMPILER_C_O([TAGNAME])
-# ---------------------------
-# Check to see if options -c and -o are simultaneously supported by compiler.
-# This macro does not hard code the compiler like AC_PROG_CC_C_O.
-m4_defun([_LT_COMPILER_C_O],
-[m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_TAG_COMPILER])dnl
-AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext],
-  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)],
-  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no
-   $RM -r conftest 2>/dev/null
-   mkdir conftest
-   cd conftest
-   mkdir out
-   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-   lt_compiler_flag="-o out/conftest2.$ac_objext"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:__oline__: $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
-   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
-     $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
-       _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
-     fi
-   fi
-   chmod u+w . 2>&AS_MESSAGE_LOG_FD
-   $RM conftest*
-   # SGI C++ compiler will create directory out/ii_files/ for
-   # template instantiation
-   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
-   $RM out/* && rmdir out
-   cd ..
-   $RM -r conftest
-   $RM conftest*
-])
-_LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1],
-	[Does compiler simultaneously support -c and -o options?])
-])# _LT_COMPILER_C_O
-
-
-# _LT_COMPILER_FILE_LOCKS([TAGNAME])
-# ----------------------------------
-# Check to see if we can do hard links to lock some files if needed
-m4_defun([_LT_COMPILER_FILE_LOCKS],
-[m4_require([_LT_ENABLE_LOCK])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-_LT_COMPILER_C_O([$1])
-
-hard_links="nottested"
-if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then
-  # do not overwrite the value of need_locks provided by the user
-  AC_MSG_CHECKING([if we can lock with hard links])
-  hard_links=yes
-  $RM conftest*
-  ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  touch conftest.a
-  ln conftest.a conftest.b 2>&5 || hard_links=no
-  ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  AC_MSG_RESULT([$hard_links])
-  if test "$hard_links" = no; then
-    AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe])
-    need_locks=warn
-  fi
-else
-  need_locks=no
-fi
-_LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?])
-])# _LT_COMPILER_FILE_LOCKS
-
-
-# _LT_CHECK_OBJDIR
-# ----------------
-m4_defun([_LT_CHECK_OBJDIR],
-[AC_CACHE_CHECK([for objdir], [lt_cv_objdir],
-[rm -f .libs 2>/dev/null
-mkdir .libs 2>/dev/null
-if test -d .libs; then
-  lt_cv_objdir=.libs
-else
-  # MS-DOS does not allow filenames that begin with a dot.
-  lt_cv_objdir=_libs
-fi
-rmdir .libs 2>/dev/null])
-objdir=$lt_cv_objdir
-_LT_DECL([], [objdir], [0],
-         [The name of the directory that contains temporary libtool files])dnl
-m4_pattern_allow([LT_OBJDIR])dnl
-AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/",
-  [Define to the sub-directory in which libtool stores uninstalled libraries.])
-])# _LT_CHECK_OBJDIR
-
-
-# _LT_LINKER_HARDCODE_LIBPATH([TAGNAME])
-# --------------------------------------
-# Check hardcoding attributes.
-m4_defun([_LT_LINKER_HARDCODE_LIBPATH],
-[AC_MSG_CHECKING([how to hardcode library paths into programs])
-_LT_TAGVAR(hardcode_action, $1)=
-if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" ||
-   test -n "$_LT_TAGVAR(runpath_var, $1)" ||
-   test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then
-
-  # We can hardcode non-existent directories.
-  if test "$_LT_TAGVAR(hardcode_direct, $1)" != no &&
-     # If the only mechanism to avoid hardcoding is shlibpath_var, we
-     # have to relink, otherwise we might link with an installed library
-     # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no &&
-     test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then
-    # Linking always hardcodes the temporary library directory.
-    _LT_TAGVAR(hardcode_action, $1)=relink
-  else
-    # We can link without hardcoding, and we can hardcode nonexisting dirs.
-    _LT_TAGVAR(hardcode_action, $1)=immediate
-  fi
-else
-  # We cannot hardcode anything, or else we can only hardcode existing
-  # directories.
-  _LT_TAGVAR(hardcode_action, $1)=unsupported
-fi
-AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)])
-
-if test "$_LT_TAGVAR(hardcode_action, $1)" = relink ||
-   test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then
-  # Fast installation is not supported
-  enable_fast_install=no
-elif test "$shlibpath_overrides_runpath" = yes ||
-     test "$enable_shared" = no; then
-  # Fast installation is not necessary
-  enable_fast_install=needless
-fi
-_LT_TAGDECL([], [hardcode_action], [0],
-    [How to hardcode a shared library path into an executable])
-])# _LT_LINKER_HARDCODE_LIBPATH
-
-
-# _LT_CMD_STRIPLIB
-# ----------------
-m4_defun([_LT_CMD_STRIPLIB],
-[m4_require([_LT_DECL_EGREP])
-striplib=
-old_striplib=
-AC_MSG_CHECKING([whether stripping libraries is possible])
-if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
-  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
-  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
-  AC_MSG_RESULT([yes])
-else
-# FIXME - insert some real tests, host_os isn't really good enough
-  case $host_os in
-  darwin*)
-    if test -n "$STRIP" ; then
-      striplib="$STRIP -x"
-      old_striplib="$STRIP -S"
-      AC_MSG_RESULT([yes])
-    else
-      AC_MSG_RESULT([no])
-    fi
-    ;;
-  *)
-    AC_MSG_RESULT([no])
-    ;;
-  esac
-fi
-_LT_DECL([], [old_striplib], [1], [Commands to strip libraries])
-_LT_DECL([], [striplib], [1])
-])# _LT_CMD_STRIPLIB
-
-
-# _LT_SYS_DYNAMIC_LINKER([TAG])
-# -----------------------------
-# PORTME Fill in your ld.so characteristics
-m4_defun([_LT_SYS_DYNAMIC_LINKER],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_OBJDUMP])dnl
-m4_require([_LT_DECL_SED])dnl
-AC_MSG_CHECKING([dynamic linker characteristics])
-m4_if([$1],
-	[], [
-if test "$GCC" = yes; then
-  case $host_os in
-    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
-    *) 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
-    # 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
-  # Ok, now we have the path, separated by spaces, we can step through it
-  # and add multilib dir if necessary.
-  lt_tmp_lt_search_path_spec=
-  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
-  for lt_sys_path in $lt_search_path_spec; do
-    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
-      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
-    else
-      test -d "$lt_sys_path" && \
-	lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
-    fi
-  done
-  lt_search_path_spec=`$ECHO $lt_tmp_lt_search_path_spec | awk '
-BEGIN {RS=" "; FS="/|\n";} {
-  lt_foo="";
-  lt_count=0;
-  for (lt_i = NF; lt_i > 0; lt_i--) {
-    if ($lt_i != "" && $lt_i != ".") {
-      if ($lt_i == "..") {
-        lt_count++;
-      } else {
-        if (lt_count == 0) {
-          lt_foo="/" $lt_i lt_foo;
-        } else {
-          lt_count--;
-        }
-      }
-    }
-  }
-  if (lt_foo != "") { lt_freq[[lt_foo]]++; }
-  if (lt_freq[[lt_foo]] == 1) { print lt_foo; }
-}'`
-  sys_lib_search_path_spec=`$ECHO $lt_search_path_spec`
-else
-  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
-fi])
-library_names_spec=
-libname_spec='lib$name'
-soname_spec=
-shrext_cmds=".so"
-postinstall_cmds=
-postuninstall_cmds=
-finish_cmds=
-finish_eval=
-shlibpath_var=
-shlibpath_overrides_runpath=unknown
-version_type=none
-dynamic_linker="$host_os ld.so"
-sys_lib_dlsearch_path_spec="/lib /usr/lib"
-need_lib_prefix=unknown
-hardcode_into_libs=no
-
-# when you set need_version to no, make sure it does not cause -set_version
-# flags to be left without arguments
-need_version=unknown
-
-case $host_os in
-aix3*)
-  version_type=linux
-  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
-  shlibpath_var=LIBPATH
-
-  # AIX 3 has no versioning support, so we append a major version to the name.
-  soname_spec='${libname}${release}${shared_ext}$major'
-  ;;
-
-aix[[4-9]]*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  hardcode_into_libs=yes
-  if test "$host_cpu" = ia64; then
-    # AIX 5 supports IA64
-    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
-    shlibpath_var=LD_LIBRARY_PATH
-  else
-    # With GCC up to 2.95.x, collect2 would create an import file
-    # for dependence libraries.  The import file would start with
-    # the line `#! .'.  This would cause the generated library to
-    # depend on `.', always an invalid library.  This was fixed in
-    # development snapshots of GCC prior to 3.0.
-    case $host_os in
-      aix4 | aix4.[[01]] | aix4.[[01]].*)
-      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
-	   echo ' yes '
-	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
-	:
-      else
-	can_build_shared=no
-      fi
-      ;;
-    esac
-    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
-    # soname into executable. Probably we can add versioning support to
-    # collect2, so additional links can be useful in future.
-    if test "$aix_use_runtimelinking" = yes; then
-      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
-      # instead of lib<name>.a to let people know that these are not
-      # typical AIX shared libraries.
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    else
-      # We preserve .a as extension for shared libraries through AIX4.2
-      # and later when we are not doing run time linking.
-      library_names_spec='${libname}${release}.a $libname.a'
-      soname_spec='${libname}${release}${shared_ext}$major'
-    fi
-    shlibpath_var=LIBPATH
-  fi
-  ;;
-
-amigaos*)
-  case $host_cpu in
-  powerpc)
-    # Since July 2007 AmigaOS4 officially supports .so libraries.
-    # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    ;;
-  m68k)
-    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'
-    ;;
-  esac
-  ;;
-
-beos*)
-  library_names_spec='${libname}${shared_ext}'
-  dynamic_linker="$host_os ld.so"
-  shlibpath_var=LIBRARY_PATH
-  ;;
-
-bsdi[[45]]*)
-  version_type=linux
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
-  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
-  # the default ld.so.conf also contains /usr/contrib/lib and
-  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
-  # libtool to hard-code these into programs
-  ;;
-
-cygwin* | mingw* | pw32* | cegcc*)
-  version_type=windows
-  shrext_cmds=".dll"
-  need_version=no
-  need_lib_prefix=no
-
-  case $GCC,$host_os in
-  yes,cygwin* | yes,mingw* | yes,pw32* | yes,cegcc*)
-    library_names_spec='$libname.dll.a'
-    # 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~
-      chmod a+x \$dldir/$dlname~
-      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
-        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
-      fi'
-    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
-      dlpath=$dir/\$dldll~
-       $RM \$dlpath'
-    shlibpath_overrides_runpath=yes
-
-    case $host_os in
-    cygwin*)
-      # 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"
-      ;;
-    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*)
-      # pw32 DLLs use 'pw' prefix rather than 'lib'
-      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-      ;;
-    esac
-    ;;
-
-  *)
-    library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
-    ;;
-  esac
-  dynamic_linker='Win32 ld.exe'
-  # FIXME: first we should search . and the directory the executable is in
-  shlibpath_var=PATH
-  ;;
-
-darwin* | rhapsody*)
-  dynamic_linker="$host_os dyld"
-  version_type=darwin
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
-  soname_spec='${libname}${release}${major}$shared_ext'
-  shlibpath_overrides_runpath=yes
-  shlibpath_var=DYLD_LIBRARY_PATH
-  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
-m4_if([$1], [],[
-  sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"])
-  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
-  ;;
-
-dgux*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  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=LD_LIBRARY_PATH
-  ;;
-
-freebsd1*)
-  dynamic_linker=no
-  ;;
-
-freebsd* | dragonfly*)
-  # DragonFly does not have aout.  When/if they implement a new
-  # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[[123]]*) objformat=aout ;;
-    *) objformat=elf ;;
-    esac
-  fi
-  version_type=freebsd-$objformat
-  case $version_type in
-    freebsd-elf*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-      need_version=no
-      need_lib_prefix=no
-      ;;
-    freebsd-*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
-      need_version=yes
-      ;;
-  esac
-  shlibpath_var=LD_LIBRARY_PATH
-  case $host_os in
-  freebsd2*)
-    shlibpath_overrides_runpath=yes
-    ;;
-  freebsd3.[[01]]* | freebsdelf3.[[01]]*)
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
-  freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
-  freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
-    shlibpath_overrides_runpath=no
-    hardcode_into_libs=yes
-    ;;
-  *) # from 4.6 on, and DragonFly
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
-  esac
-  ;;
-
-gnu*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  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=LD_LIBRARY_PATH
-  hardcode_into_libs=yes
-  ;;
-
-hpux9* | hpux10* | hpux11*)
-  # Give a soname corresponding to the major version so that dld.sl refuses to
-  # link against other versions.
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  case $host_cpu in
-  ia64*)
-    shrext_cmds='.so'
-    hardcode_into_libs=yes
-    dynamic_linker="$host_os dld.so"
-    shlibpath_var=LD_LIBRARY_PATH
-    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    if test "X$HPUX_IA64_MODE" = X32; then
-      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
-    else
-      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
-    fi
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
-    ;;
-  hppa*64*)
-    shrext_cmds='.sl'
-    hardcode_into_libs=yes
-    dynamic_linker="$host_os dld.sl"
-    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
-    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
-    ;;
-  *)
-    shrext_cmds='.sl'
-    dynamic_linker="$host_os dld.sl"
-    shlibpath_var=SHLIB_PATH
-    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    ;;
-  esac
-  # HP-UX runs *really* slowly unless shared libraries are mode 555.
-  postinstall_cmds='chmod 555 $lib'
-  ;;
-
-interix[[3-9]]*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $host_os in
-    nonstopux*) version_type=nonstopux ;;
-    *)
-	if test "$lt_cv_prog_gnu_ld" = yes; then
-		version_type=linux
-	else
-		version_type=irix
-	fi ;;
-  esac
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
-  case $host_os in
-  irix5* | nonstopux*)
-    libsuff= shlibsuff=
-    ;;
-  *)
-    case $LD in # libtool.m4 will add one of these switches to LD
-    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
-      libsuff= shlibsuff= libmagic=32-bit;;
-    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
-      libsuff=32 shlibsuff=N32 libmagic=N32;;
-    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
-      libsuff=64 shlibsuff=64 libmagic=64-bit;;
-    *) libsuff= shlibsuff= libmagic=never-match;;
-    esac
-    ;;
-  esac
-  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
-  shlibpath_overrides_runpath=no
-  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
-  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
-  hardcode_into_libs=yes
-  ;;
-
-# No shared lib support for Linux oldld, aout, or coff.
-linux*oldld* | linux*aout* | linux*coff*)
-  dynamic_linker=no
-  ;;
-
-# This must be Linux ELF.
-linux* | k*bsd*-gnu)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
-  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
-
-  # This implies no fast_install, which is unacceptable.
-  # Some rework will be needed to allow for fast_install
-  # before this can be enabled.
-  hardcode_into_libs=yes
-
-  # 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' ' '`
-    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
-  fi
-
-  # We used to test for /lib/ld.so.1 and disable shared libraries on
-  # powerpc, because MkLinux only supported shared libraries with the
-  # GNU dynamic linker.  Since this was broken with cross compilers,
-  # most powerpc-linux boxes support dynamic linking these days and
-  # people can always --disable-shared, the test was removed, and we
-  # assume the GNU/Linux dynamic linker is in use.
-  dynamic_linker='GNU/Linux ld.so'
-  ;;
-
-netbsd*)
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-    dynamic_linker='NetBSD (a.out) ld.so'
-  else
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    dynamic_linker='NetBSD ld.elf_so'
-  fi
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  ;;
-
-newsos6)
-  version_type=linux
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  ;;
-
-*nto* | *qnx*)
-  version_type=qnx
-  need_lib_prefix=no
-  need_version=no
-  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=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  dynamic_linker='ldqnx.so'
-  ;;
-
-openbsd*)
-  version_type=sunos
-  sys_lib_dlsearch_path_spec="/usr/lib"
-  need_lib_prefix=no
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
-    *)				need_version=no  ;;
-  esac
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[[89]] | openbsd2.[[89]].*)
-	shlibpath_overrides_runpath=no
-	;;
-      *)
-	shlibpath_overrides_runpath=yes
-	;;
-      esac
-  else
-    shlibpath_overrides_runpath=yes
-  fi
-  ;;
-
-os2*)
-  libname_spec='$name'
-  shrext_cmds=".dll"
-  need_lib_prefix=no
-  library_names_spec='$libname${shared_ext} $libname.a'
-  dynamic_linker='OS/2 ld.exe'
-  shlibpath_var=LIBPATH
-  ;;
-
-osf3* | osf4* | osf5*)
-  version_type=osf
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
-  ;;
-
-rdos*)
-  dynamic_linker=no
-  ;;
-
-solaris*)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  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=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  # ldd complains unless libraries are executable
-  postinstall_cmds='chmod +x $lib'
-  ;;
-
-sunos4*)
-  version_type=sunos
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  if test "$with_gnu_ld" = yes; then
-    need_lib_prefix=no
-  fi
-  need_version=yes
-  ;;
-
-sysv4 | sysv4.3*)
-  version_type=linux
-  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=LD_LIBRARY_PATH
-  case $host_vendor in
-    sni)
-      shlibpath_overrides_runpath=no
-      need_lib_prefix=no
-      runpath_var=LD_RUN_PATH
-      ;;
-    siemens)
-      need_lib_prefix=no
-      ;;
-    motorola)
-      need_lib_prefix=no
-      need_version=no
-      shlibpath_overrides_runpath=no
-      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
-      ;;
-  esac
-  ;;
-
-sysv4*MP*)
-  if test -d /usr/nec ;then
-    version_type=linux
-    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
-    soname_spec='$libname${shared_ext}.$major'
-    shlibpath_var=LD_LIBRARY_PATH
-  fi
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=freebsd-elf
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  if test "$with_gnu_ld" = yes; then
-    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
-  else
-    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec='/usr/lib'
-  ;;
-
-tpf*)
-  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
-uts4*)
-  version_type=linux
-  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=LD_LIBRARY_PATH
-  ;;
-
-*)
-  dynamic_linker=no
-  ;;
-esac
-AC_MSG_RESULT([$dynamic_linker])
-test "$dynamic_linker" = no && can_build_shared=no
-
-variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
-if test "$GCC" = yes; then
-  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
-fi
-
-if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
-  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
-fi
-if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
-  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
-fi
-
-_LT_DECL([], [variables_saved_for_relink], [1],
-    [Variables whose values should be saved in libtool wrapper scripts and
-    restored at link time])
-_LT_DECL([], [need_lib_prefix], [0],
-    [Do we need the "lib" prefix for modules?])
-_LT_DECL([], [need_version], [0], [Do we need a version for libraries?])
-_LT_DECL([], [version_type], [0], [Library versioning type])
-_LT_DECL([], [runpath_var], [0],  [Shared library runtime path variable])
-_LT_DECL([], [shlibpath_var], [0],[Shared library path variable])
-_LT_DECL([], [shlibpath_overrides_runpath], [0],
-    [Is shlibpath searched before the hard-coded library search path?])
-_LT_DECL([], [libname_spec], [1], [Format of library name prefix])
-_LT_DECL([], [library_names_spec], [1],
-    [[List of archive names.  First name is the real one, the rest are links.
-    The last name is the one that the linker finds with -lNAME]])
-_LT_DECL([], [soname_spec], [1],
-    [[The coded name of the library, if different from the real name]])
-_LT_DECL([], [postinstall_cmds], [2],
-    [Command to use after installation of a shared archive])
-_LT_DECL([], [postuninstall_cmds], [2],
-    [Command to use after uninstallation of a shared archive])
-_LT_DECL([], [finish_cmds], [2],
-    [Commands used to finish a libtool library installation in a directory])
-_LT_DECL([], [finish_eval], [1],
-    [[As "finish_cmds", except a single script fragment to be evaled but
-    not shown]])
-_LT_DECL([], [hardcode_into_libs], [0],
-    [Whether we should hardcode library paths into libraries])
-_LT_DECL([], [sys_lib_search_path_spec], [2],
-    [Compile-time system search path for libraries])
-_LT_DECL([], [sys_lib_dlsearch_path_spec], [2],
-    [Run-time system search path for libraries])
-])# _LT_SYS_DYNAMIC_LINKER
-
-
-# _LT_PATH_TOOL_PREFIX(TOOL)
-# --------------------------
-# find a file program which can recognize shared library
-AC_DEFUN([_LT_PATH_TOOL_PREFIX],
-[m4_require([_LT_DECL_EGREP])dnl
-AC_MSG_CHECKING([for $1])
-AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
-[case $MAGIC_CMD in
-[[\\/*] |  ?:[\\/]*])
-  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
-  ;;
-*)
-  lt_save_MAGIC_CMD="$MAGIC_CMD"
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-dnl $ac_dummy forces splitting on constant user-supplied paths.
-dnl POSIX.2 word splitting is done only on the output of word expansions,
-dnl not every word.  This closes a longstanding sh security hole.
-  ac_dummy="m4_if([$2], , $PATH, [$2])"
-  for ac_dir in $ac_dummy; do
-    IFS="$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$1; then
-      lt_cv_path_MAGIC_CMD="$ac_dir/$1"
-      if test -n "$file_magic_test_file"; then
-	case $deplibs_check_method in
-	"file_magic "*)
-	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
-	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
-	    $EGREP "$file_magic_regex" > /dev/null; then
-	    :
-	  else
-	    cat <<_LT_EOF 1>&2
-
-*** Warning: the command libtool uses to detect shared libraries,
-*** $file_magic_cmd, produces output that libtool cannot recognize.
-*** The result is that libtool may fail to recognize shared libraries
-*** as such.  This will affect the creation of libtool libraries that
-*** depend on shared libraries, but programs linked with such libtool
-*** libraries will work regardless of this problem.  Nevertheless, you
-*** may want to report the problem to your system manager and/or to
-*** bug-libtool@gnu.org
-
-_LT_EOF
-	  fi ;;
-	esac
-      fi
-      break
-    fi
-  done
-  IFS="$lt_save_ifs"
-  MAGIC_CMD="$lt_save_MAGIC_CMD"
-  ;;
-esac])
-MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-if test -n "$MAGIC_CMD"; then
-  AC_MSG_RESULT($MAGIC_CMD)
-else
-  AC_MSG_RESULT(no)
-fi
-_LT_DECL([], [MAGIC_CMD], [0],
-	 [Used to examine libraries when file_magic_cmd begins with "file"])dnl
-])# _LT_PATH_TOOL_PREFIX
-
-# Old name:
-AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], [])
-
-
-# _LT_PATH_MAGIC
-# --------------
-# find a file program which can recognize a shared library
-m4_defun([_LT_PATH_MAGIC],
-[_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
-if test -z "$lt_cv_path_MAGIC_CMD"; then
-  if test -n "$ac_tool_prefix"; then
-    _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH)
-  else
-    MAGIC_CMD=:
-  fi
-fi
-])# _LT_PATH_MAGIC
-
-
-# LT_PATH_LD
-# ----------
-# find the pathname to the GNU or non-GNU linker
-AC_DEFUN([LT_PATH_LD],
-[AC_REQUIRE([AC_PROG_CC])dnl
-AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_CANONICAL_BUILD])dnl
-m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_DECL_EGREP])dnl
-
-AC_ARG_WITH([gnu-ld],
-    [AS_HELP_STRING([--with-gnu-ld],
-	[assume the C compiler uses GNU ld @<:@default=no@:>@])],
-    [test "$withval" = no || with_gnu_ld=yes],
-    [with_gnu_ld=no])dnl
-
-ac_prog=ld
-if test "$GCC" = yes; then
-  # Check if gcc -print-prog-name=ld gives a path.
-  AC_MSG_CHECKING([for ld used by $CC])
-  case $host in
-  *-*-mingw*)
-    # gcc leaves a trailing carriage return which upsets mingw
-    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
-  *)
-    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
-  esac
-  case $ac_prog in
-    # Accept absolute paths.
-    [[\\/]]* | ?:[[\\/]]*)
-      re_direlt='/[[^/]][[^/]]*/\.\./'
-      # Canonicalize the pathname of ld
-      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
-      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
-	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
-      done
-      test -z "$LD" && LD="$ac_prog"
-      ;;
-  "")
-    # If it fails, then pretend we aren't using GCC.
-    ac_prog=ld
-    ;;
-  *)
-    # If it is relative, then search for the first ld in PATH.
-    with_gnu_ld=unknown
-    ;;
-  esac
-elif test "$with_gnu_ld" = yes; then
-  AC_MSG_CHECKING([for GNU ld])
-else
-  AC_MSG_CHECKING([for non-GNU ld])
-fi
-AC_CACHE_VAL(lt_cv_path_LD,
-[if test -z "$LD"; then
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-  for ac_dir in $PATH; do
-    IFS="$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=.
-    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
-      lt_cv_path_LD="$ac_dir/$ac_prog"
-      # Check to see if the program is GNU ld.  I'd rather use --version,
-      # but apparently some variants of GNU ld only accept -v.
-      # Break only if it was the GNU/non-GNU ld that we prefer.
-      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
-      *GNU* | *'with BFD'*)
-	test "$with_gnu_ld" != no && break
-	;;
-      *)
-	test "$with_gnu_ld" != yes && break
-	;;
-      esac
-    fi
-  done
-  IFS="$lt_save_ifs"
-else
-  lt_cv_path_LD="$LD" # Let the user override the test with a path.
-fi])
-LD="$lt_cv_path_LD"
-if test -n "$LD"; then
-  AC_MSG_RESULT($LD)
-else
-  AC_MSG_RESULT(no)
-fi
-test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
-_LT_PATH_LD_GNU
-AC_SUBST([LD])
-
-_LT_TAGDECL([], [LD], [1], [The linker used to build libraries])
-])# LT_PATH_LD
-
-# Old names:
-AU_ALIAS([AM_PROG_LD], [LT_PATH_LD])
-AU_ALIAS([AC_PROG_LD], [LT_PATH_LD])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AM_PROG_LD], [])
-dnl AC_DEFUN([AC_PROG_LD], [])
-
-
-# _LT_PATH_LD_GNU
-#- --------------
-m4_defun([_LT_PATH_LD_GNU],
-[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
-[# I'd rather use --version here, but apparently some GNU lds only accept -v.
-case `$LD -v 2>&1 </dev/null` in
-*GNU* | *'with BFD'*)
-  lt_cv_prog_gnu_ld=yes
-  ;;
-*)
-  lt_cv_prog_gnu_ld=no
-  ;;
-esac])
-with_gnu_ld=$lt_cv_prog_gnu_ld
-])# _LT_PATH_LD_GNU
-
-
-# _LT_CMD_RELOAD
-# --------------
-# find reload flag for linker
-#   -- PORTME Some linkers may need a different reload flag.
-m4_defun([_LT_CMD_RELOAD],
-[AC_CACHE_CHECK([for $LD option to reload object files],
-  lt_cv_ld_reload_flag,
-  [lt_cv_ld_reload_flag='-r'])
-reload_flag=$lt_cv_ld_reload_flag
-case $reload_flag in
-"" | " "*) ;;
-*) reload_flag=" $reload_flag" ;;
-esac
-reload_cmds='$LD$reload_flag -o $output$reload_objs'
-case $host_os in
-  darwin*)
-    if test "$GCC" = yes; then
-      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
-    else
-      reload_cmds='$LD$reload_flag -o $output$reload_objs'
-    fi
-    ;;
-esac
-_LT_DECL([], [reload_flag], [1], [How to create reloadable object files])dnl
-_LT_DECL([], [reload_cmds], [2])dnl
-])# _LT_CMD_RELOAD
-
-
-# _LT_CHECK_MAGIC_METHOD
-# ----------------------
-# how to check for library dependencies
-#  -- PORTME fill in with the dynamic library characteristics
-m4_defun([_LT_CHECK_MAGIC_METHOD],
-[m4_require([_LT_DECL_EGREP])
-m4_require([_LT_DECL_OBJDUMP])
-AC_CACHE_CHECK([how to recognize dependent libraries],
-lt_cv_deplibs_check_method,
-[lt_cv_file_magic_cmd='$MAGIC_CMD'
-lt_cv_file_magic_test_file=
-lt_cv_deplibs_check_method='unknown'
-# Need to set the preceding variable on all platforms that support
-# interlibrary dependencies.
-# 'none' -- dependencies not supported.
-# `unknown' -- same as none, but documents that we really don't know.
-# 'pass_all' -- all dependencies passed with no checks.
-# 'test_compile' -- check by making test program.
-# 'file_magic [[regex]]' -- check by looking for files in library path
-# which responds to the $file_magic_cmd with a given extended regex.
-# If you have `file' or equivalent on your system and you're not sure
-# whether `pass_all' will *always* work, you probably want this one.
-
-case $host_os in
-aix[[4-9]]*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-beos*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-bsdi[[45]]*)
-  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)'
-  lt_cv_file_magic_cmd='/usr/bin/file -L'
-  lt_cv_file_magic_test_file=/shlib/libc.so
-  ;;
-
-cygwin*)
-  # func_win32_libid is a shell function defined in ltmain.sh
-  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
-  lt_cv_file_magic_cmd='func_win32_libid'
-  ;;
-
-mingw* | pw32*)
-  # Base MSYS/MinGW do not provide the 'file' command needed by
-  # 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
-    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)?'
-    lt_cv_file_magic_cmd='$OBJDUMP -f'
-  fi
-  ;;
-
-cegcc)
-  # use the weaker test based on 'objdump'. See mingw*.
-  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
-  lt_cv_file_magic_cmd='$OBJDUMP -f'
-  ;;
-
-darwin* | rhapsody*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-freebsd* | dragonfly*)
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
-    case $host_cpu in
-    i*86 )
-      # Not sure whether the presence of OpenBSD here was a mistake.
-      # Let's accept both of them until this is cleared up.
-      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library'
-      lt_cv_file_magic_cmd=/usr/bin/file
-      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
-      ;;
-    esac
-  else
-    lt_cv_deplibs_check_method=pass_all
-  fi
-  ;;
-
-gnu*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-hpux10.20* | hpux11*)
-  lt_cv_file_magic_cmd=/usr/bin/file
-  case $host_cpu in
-  ia64*)
-    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64'
-    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
-    ;;
-  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_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_file_magic_test_file=/usr/lib/libc.sl
-    ;;
-  esac
-  ;;
-
-interix[[3-9]]*)
-  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
-  lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$'
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $LD in
-  *-32|*"-32 ") libmagic=32-bit;;
-  *-n32|*"-n32 ") libmagic=N32;;
-  *-64|*"-64 ") libmagic=64-bit;;
-  *) libmagic=never-match;;
-  esac
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-# This must be Linux ELF.
-linux* | k*bsd*-gnu)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-netbsd*)
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
-    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
-  else
-    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$'
-  fi
-  ;;
-
-newos6*)
-  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)'
-  lt_cv_file_magic_cmd=/usr/bin/file
-  lt_cv_file_magic_test_file=/usr/lib/libnls.so
-  ;;
-
-*nto* | *qnx*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-openbsd*)
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$'
-  else
-    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
-  fi
-  ;;
-
-osf3* | osf4* | osf5*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-rdos*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-solaris*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-sysv4 | sysv4.3*)
-  case $host_vendor in
-  motorola)
-    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
-    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
-    ;;
-  ncr)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  sequent)
-    lt_cv_file_magic_cmd='/bin/file'
-    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )'
-    ;;
-  sni)
-    lt_cv_file_magic_cmd='/bin/file'
-    lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib"
-    lt_cv_file_magic_test_file=/lib/libc.so
-    ;;
-  siemens)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  pc)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  esac
-  ;;
-
-tpf*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-esac
-])
-file_magic_cmd=$lt_cv_file_magic_cmd
-deplibs_check_method=$lt_cv_deplibs_check_method
-test -z "$deplibs_check_method" && deplibs_check_method=unknown
-
-_LT_DECL([], [deplibs_check_method], [1],
-    [Method to check whether dependent libraries are shared objects])
-_LT_DECL([], [file_magic_cmd], [1],
-    [Command to use when deplibs_check_method == "file_magic"])
-])# _LT_CHECK_MAGIC_METHOD
-
-
-# LT_PATH_NM
-# ----------
-# find the pathname to a BSD- or MS-compatible name lister
-AC_DEFUN([LT_PATH_NM],
-[AC_REQUIRE([AC_PROG_CC])dnl
-AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM,
-[if test -n "$NM"; then
-  # Let the user override the test.
-  lt_cv_path_NM="$NM"
-else
-  lt_nm_to_check="${ac_tool_prefix}nm"
-  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
-    lt_nm_to_check="$lt_nm_to_check nm"
-  fi
-  for lt_tmp_nm in $lt_nm_to_check; do
-    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
-      IFS="$lt_save_ifs"
-      test -z "$ac_dir" && ac_dir=.
-      tmp_nm="$ac_dir/$lt_tmp_nm"
-      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
-	# Check to see if the nm accepts a BSD-compat flag.
-	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
-	#   nm: unknown option "B" ignored
-	# Tru64's nm complains that /dev/null is an invalid object file
-	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
-	*/dev/null* | *'Invalid file or object type'*)
-	  lt_cv_path_NM="$tmp_nm -B"
-	  break
-	  ;;
-	*)
-	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
-	  */dev/null*)
-	    lt_cv_path_NM="$tmp_nm -p"
-	    break
-	    ;;
-	  *)
-	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
-	    continue # so that we can try to find one that supports BSD flags
-	    ;;
-	  esac
-	  ;;
-	esac
-      fi
-    done
-    IFS="$lt_save_ifs"
-  done
-  : ${lt_cv_path_NM=no}
-fi])
-if test "$lt_cv_path_NM" != "no"; then
-  NM="$lt_cv_path_NM"
-else
-  # Didn't find any BSD compatible name lister, look for dumpbin.
-  AC_CHECK_TOOLS(DUMPBIN, ["dumpbin -symbols" "link -dump -symbols"], :)
-  AC_SUBST([DUMPBIN])
-  if test "$DUMPBIN" != ":"; then
-    NM="$DUMPBIN"
-  fi
-fi
-test -z "$NM" && NM=nm
-AC_SUBST([NM])
-_LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl
-
-AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface],
-  [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 "$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 "$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)
-  cat conftest.out >&AS_MESSAGE_LOG_FD
-  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
-    lt_cv_nm_interface="MS dumpbin"
-  fi
-  rm -f conftest*])
-])# LT_PATH_NM
-
-# Old names:
-AU_ALIAS([AM_PROG_NM], [LT_PATH_NM])
-AU_ALIAS([AC_PROG_NM], [LT_PATH_NM])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AM_PROG_NM], [])
-dnl AC_DEFUN([AC_PROG_NM], [])
-
-
-# LT_LIB_M
-# --------
-# check for math library
-AC_DEFUN([LT_LIB_M],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-LIBM=
-case $host in
-*-*-beos* | *-*-cygwin* | *-*-pw32* | *-*-darwin*)
-  # These system don't have libm, or don't need it
-  ;;
-*-ncr-sysv4.3*)
-  AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw")
-  AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm")
-  ;;
-*)
-  AC_CHECK_LIB(m, cos, LIBM="-lm")
-  ;;
-esac
-AC_SUBST([LIBM])
-])# LT_LIB_M
-
-# Old name:
-AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_CHECK_LIBM], [])
-
-
-# _LT_COMPILER_NO_RTTI([TAGNAME])
-# -------------------------------
-m4_defun([_LT_COMPILER_NO_RTTI],
-[m4_require([_LT_TAG_COMPILER])dnl
-
-_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
-
-if test "$GCC" = yes; then
-  _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
-
-  _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions],
-    lt_cv_prog_compiler_rtti_exceptions,
-    [-fno-rtti -fno-exceptions], [],
-    [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"])
-fi
-_LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1],
-	[Compiler flag to turn off builtin functions])
-])# _LT_COMPILER_NO_RTTI
-
-
-# _LT_CMD_GLOBAL_SYMBOLS
-# ----------------------
-m4_defun([_LT_CMD_GLOBAL_SYMBOLS],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_PROG_CC])dnl
-AC_REQUIRE([LT_PATH_NM])dnl
-AC_REQUIRE([LT_PATH_LD])dnl
-m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_TAG_COMPILER])dnl
-
-# Check for command to grab the raw symbol name followed by C symbol from nm.
-AC_MSG_CHECKING([command to parse $NM output from $compiler object])
-AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe],
-[
-# These are sane defaults that work on at least a few old systems.
-# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
-
-# Character class describing NM global symbol codes.
-symcode='[[BCDEGRST]]'
-
-# Regexp to match symbols that can be accessed directly from C.
-sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)'
-
-# Define system-specific variables.
-case $host_os in
-aix*)
-  symcode='[[BCDT]]'
-  ;;
-cygwin* | mingw* | pw32* | cegcc*)
-  symcode='[[ABCDGISTW]]'
-  ;;
-hpux*)
-  if test "$host_cpu" = ia64; then
-    symcode='[[ABCDEGRST]]'
-  fi
-  ;;
-irix* | nonstopux*)
-  symcode='[[BCDEGRST]]'
-  ;;
-osf*)
-  symcode='[[BCDEGQRST]]'
-  ;;
-solaris*)
-  symcode='[[BDRT]]'
-  ;;
-sco3.2v5*)
-  symcode='[[DT]]'
-  ;;
-sysv4.2uw2*)
-  symcode='[[DT]]'
-  ;;
-sysv5* | sco5v6* | unixware* | OpenUNIX*)
-  symcode='[[ABDT]]'
-  ;;
-sysv4)
-  symcode='[[DFNSTU]]'
-  ;;
-esac
-
-# If we're using GNU nm, then use its standard symbol codes.
-case `$NM -V 2>&1` in
-*GNU* | *'with BFD'*)
-  symcode='[[ABCDGIRSTW]]' ;;
-esac
-
-# Transform an extracted symbol line into a proper C declaration.
-# Some systems (esp. on ia64) link data and code symbols differently,
-# so use this general approach.
-lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
-
-# 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'"
-
-# Handle CRLF in mingw tool chain
-opt_cr=
-case $build_os in
-mingw*)
-  opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp
-  ;;
-esac
-
-# Try without a prefix underscore, then with it.
-for ac_symprfx in "" "_"; do
-
-  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
-  symxfrm="\\1 $ac_symprfx\\2 \\2"
-
-  # Write the raw and C identifiers.
-  if test "$lt_cv_nm_interface" = "MS dumpbin"; then
-    # Fake it for dumpbin and say T for any non-static function
-    # and D for any global variable.
-    # Also find C++ and __fastcall symbols from MSVC++,
-    # which start with @ or ?.
-    lt_cv_sys_global_symbol_pipe="$AWK ['"\
-"     {last_section=section; section=\$ 3};"\
-"     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
-"     \$ 0!~/External *\|/{next};"\
-"     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
-"     {if(hide[section]) next};"\
-"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
-"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
-"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
-"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
-"     ' prfx=^$ac_symprfx]"
-  else
-    lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[	 ]]\($symcode$symcode*\)[[	 ]][[	 ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
-  fi
-
-  # Check to see that the pipe works correctly.
-  pipe_works=no
-
-  rm -f conftest*
-  cat > conftest.$ac_ext <<_LT_EOF
-#ifdef __cplusplus
-extern "C" {
-#endif
-char nm_test_var;
-void nm_test_func(void);
-void nm_test_func(void){}
-#ifdef __cplusplus
-}
-#endif
-int main(){nm_test_var='a';nm_test_func();return(0);}
-_LT_EOF
-
-  if AC_TRY_EVAL(ac_compile); then
-    # 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
-      # Try sorting and uniquifying the output.
-      if sort "$nlist" | uniq > "$nlist"T; then
-	mv -f "$nlist"T "$nlist"
-      else
-	rm -f "$nlist"T
-      fi
-
-      # Make sure that we snagged all the symbols we need.
-      if $GREP ' nm_test_var$' "$nlist" >/dev/null; then
-	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
-	  cat <<_LT_EOF > conftest.$ac_ext
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-_LT_EOF
-	  # Now generate the symbol file.
-	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext'
-
-	  cat <<_LT_EOF >> conftest.$ac_ext
-
-/* The mapping between symbol names and symbols.  */
-const struct {
-  const char *name;
-  void       *address;
-}
-lt__PROGRAM__LTX_preloaded_symbols[[]] =
-{
-  { "@PROGRAM@", (void *) 0 },
-_LT_EOF
-	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
-	  cat <<\_LT_EOF >> conftest.$ac_ext
-  {0, (void *) 0}
-};
-
-/* This works around a problem in FreeBSD linker */
-#ifdef FREEBSD_WORKAROUND
-static const void *lt_preloaded_setup() {
-  return lt__PROGRAM__LTX_preloaded_symbols;
-}
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-_LT_EOF
-	  # Now try linking the two files.
-	  mv conftest.$ac_objext conftstm.$ac_objext
-	  lt_save_LIBS="$LIBS"
-	  lt_save_CFLAGS="$CFLAGS"
-	  LIBS="conftstm.$ac_objext"
-	  CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
-	  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
-	    pipe_works=yes
-	  fi
-	  LIBS="$lt_save_LIBS"
-	  CFLAGS="$lt_save_CFLAGS"
-	else
-	  echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
-	fi
-      else
-	echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD
-      fi
-    else
-      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
-    fi
-  else
-    echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD
-    cat conftest.$ac_ext >&5
-  fi
-  rm -rf conftest* conftst*
-
-  # Do not use the global_symbol_pipe unless it works.
-  if test "$pipe_works" = yes; then
-    break
-  else
-    lt_cv_sys_global_symbol_pipe=
-  fi
-done
-])
-if test -z "$lt_cv_sys_global_symbol_pipe"; then
-  lt_cv_sys_global_symbol_to_cdecl=
-fi
-if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
-  AC_MSG_RESULT(failed)
-else
-  AC_MSG_RESULT(ok)
-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])
-_LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1],
-    [Transform the output of nm in a proper C declaration])
-_LT_DECL([global_symbol_to_c_name_address],
-    [lt_cv_sys_global_symbol_to_c_name_address], [1],
-    [Transform the output of nm in a C name address pair])
-_LT_DECL([global_symbol_to_c_name_address_lib_prefix],
-    [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_CMD_GLOBAL_SYMBOLS
-
-
-# _LT_COMPILER_PIC([TAGNAME])
-# ---------------------------
-m4_defun([_LT_COMPILER_PIC],
-[m4_require([_LT_TAG_COMPILER])dnl
-_LT_TAGVAR(lt_prog_compiler_wl, $1)=
-_LT_TAGVAR(lt_prog_compiler_pic, $1)=
-_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.
-  if test "$GXX" = yes; then
-    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-
-    case $host_os in
-    aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-        ;;
-      m68k)
-            # FIXME: we need at least 68020 code to build shared libraries, but
-            # adding the `-m68020' flag to GCC prevents building anything better,
-            # like `-m68040'.
-            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
-        ;;
-      esac
-      ;;
-
-    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
-    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).
-      # Although the cygwin gcc ignores -fPIC, still need this for old-style
-      # (--disable-auto-import) libraries
-      m4_if([$1], [GCJ], [],
-	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
-      ;;
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
-      ;;
-    *djgpp*)
-      # DJGPP does not support shared libraries at all
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)=
-      ;;
-    interix[[3-9]]*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
-      fi
-      ;;
-    hpux*)
-      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
-      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
-      # sets the default TLS model and affects inlining.
-      case $host_cpu in
-      hppa*64*)
-	;;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	;;
-      esac
-      ;;
-    *qnx* | *nto*)
-      # QNX uses GNU C++, but need to define -shared option too, otherwise
-      # it will coredump.
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
-      ;;
-    *)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-      ;;
-    esac
-  else
-    case $host_os in
-      aix[[4-9]]*)
-	# All AIX code is PIC.
-	if test "$host_cpu" = ia64; then
-	  # AIX 5 now supports IA64 processor
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	else
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
-	fi
-	;;
-      chorus*)
-	case $cc_basename in
-	cxch68*)
-	  # Green Hills C++ Compiler
-	  # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
-	  ;;
-	esac
-	;;
-      dgux*)
-	case $cc_basename in
-	  ec++*)
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    ;;
-	  ghcx*)
-	    # Green Hills C++ Compiler
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      freebsd* | dragonfly*)
-	# FreeBSD uses GNU C++
-	;;
-      hpux9* | hpux10* | hpux11*)
-	case $cc_basename in
-	  CC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
-	    if test "$host_cpu" != ia64; then
-	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
-	    fi
-	    ;;
-	  aCC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
-	    case $host_cpu in
-	    hppa*64*|ia64*)
-	      # +Z the default
-	      ;;
-	    *)
-	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
-	      ;;
-	    esac
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      interix*)
-	# This is c89, which is MS Visual C++ (no shared libs)
-	# Anyone wants to do a port?
-	;;
-      irix5* | irix6* | nonstopux*)
-	case $cc_basename in
-	  CC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-	    # CC pic flag -KPIC is the default.
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      linux* | k*bsd*-gnu)
-	case $cc_basename in
-	  KCC*)
-	    # KAI C++ Compiler
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	    ;;
-	  ecpc* )
-	    # old Intel C++ for x86_64 which still supported -KPIC.
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-	    ;;
-	  icpc* )
-	    # Intel C++, used to be incompatible with GCC.
-	    # ICC 10 doesn't accept -KPIC any more.
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-	    ;;
-	  pgCC* | pgcpp*)
-	    # Portland Group C++ compiler
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	    ;;
-	  cxx*)
-	    # Compaq C++
-	    # Make sure the PIC flag is empty.  It appears that all Alpha
-	    # Linux and Compaq Tru64 Unix objects are PIC.
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-	    ;;
-	  xlc* | xlC*)
-	    # IBM XL 8.0 on PPC
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
-	    ;;
-	  *)
-	    case `$CC -V 2>&1 | sed 5q` in
-	    *Sun\ C*)
-	      # Sun C++ 5.9
-	      _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 '
-	      ;;
-	    esac
-	    ;;
-	esac
-	;;
-      lynxos*)
-	;;
-      m88k*)
-	;;
-      mvs*)
-	case $cc_basename in
-	  cxx*)
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      netbsd*)
-	;;
-      *qnx* | *nto*)
-        # QNX uses GNU C++, but need to define -shared option too, otherwise
-        # it will coredump.
-        _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
-        ;;
-      osf3* | osf4* | osf5*)
-	case $cc_basename in
-	  KCC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
-	    ;;
-	  RCC*)
-	    # Rational C++ 2.4.1
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-	    ;;
-	  cxx*)
-	    # Digital/Compaq C++
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    # Make sure the PIC flag is empty.  It appears that all Alpha
-	    # Linux and Compaq Tru64 Unix objects are PIC.
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      psos*)
-	;;
-      solaris*)
-	case $cc_basename in
-	  CC*)
-	    # Sun C++ 4.2, 5.x and Centerline C++
-	    _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 '
-	    ;;
-	  gcx*)
-	    # Green Hills C++ Compiler
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      sunos4*)
-	case $cc_basename in
-	  CC*)
-	    # Sun C++ 4.x
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	    ;;
-	  lcc*)
-	    # Lucid
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-	case $cc_basename in
-	  CC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	    ;;
-	esac
-	;;
-      tandem*)
-	case $cc_basename in
-	  NCC*)
-	    # NonStop-UX NCC 3.20
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      vxworks*)
-	;;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
-	;;
-    esac
-  fi
-],
-[
-  if test "$GCC" = yes; then
-    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-
-    case $host_os in
-      aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-        ;;
-      m68k)
-            # FIXME: we need at least 68020 code to build shared libraries, but
-            # adding the `-m68020' flag to GCC prevents building anything better,
-            # like `-m68040'.
-            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
-        ;;
-      esac
-      ;;
-
-    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
-
-    mingw* | cygwin* | pw32* | os2* | 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).
-      # Although the cygwin gcc ignores -fPIC, still need this for old-style
-      # (--disable-auto-import) libraries
-      m4_if([$1], [GCJ], [],
-	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
-      ;;
-
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
-      ;;
-
-    hpux*)
-      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
-      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
-      # sets the default TLS model and affects inlining.
-      case $host_cpu in
-      hppa*64*)
-	# +Z the default
-	;;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	;;
-      esac
-      ;;
-
-    interix[[3-9]]*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-
-    msdosdjgpp*)
-      # Just because we use GCC doesn't mean we suddenly get shared libraries
-      # on systems that don't support them.
-      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
-      enable_shared=no
-      ;;
-
-    *nto* | *qnx*)
-      # QNX uses GNU C++, but need to define -shared option too, otherwise
-      # it will coredump.
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
-      fi
-      ;;
-
-    *)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-      ;;
-    esac
-  else
-    # PORTME Check for flag to pass linker flags through the system compiler.
-    case $host_os in
-    aix*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      else
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
-      fi
-      ;;
-
-    mingw* | cygwin* | pw32* | os2* | 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'])
-      ;;
-
-    hpux9* | hpux10* | hpux11*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
-	;;
-      esac
-      # Is there a better lt_prog_compiler_static that works with the bundled CC?
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      # PIC (with -KPIC) is the default.
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-      ;;
-
-    linux* | k*bsd*-gnu)
-      case $cc_basename in
-      # old Intel for x86_64 which still supported -KPIC.
-      ecc*)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-        ;;
-      # icc used to be incompatible with GCC.
-      # ICC 10 doesn't accept -KPIC any more.
-      icc* | ifort*)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-        ;;
-      # Lahey Fortran 8.1.
-      lf95*)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='--static'
-	;;
-      pgcc* | pgf77* | pgf90* | pgf95*)
-        # Portland Group compilers (*not* the Pentium gcc compiler,
-	# which looks to be a dead project)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-        ;;
-      ccc*)
-        _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-        # All Alpha code is PIC.
-        _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-        ;;
-      xl*)
-	# IBM XL C 8.0/Fortran 10.1 on PPC
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
-	;;
-      *)
-	case `$CC -V 2>&1 | sed 5q` in
-	*Sun\ C*)
-	  # Sun C 5.9
-	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	  _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'
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	  _LT_TAGVAR(lt_prog_compiler_wl, $1)=''
-	  ;;
-	esac
-	;;
-      esac
-      ;;
-
-    newsos6)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    *nto* | *qnx*)
-      # QNX uses GNU C++, but need to define -shared option too, otherwise
-      # it will coredump.
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
-      ;;
-
-    osf3* | osf4* | osf5*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      # All OSF/1 code is PIC.
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-      ;;
-
-    rdos*)
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-      ;;
-
-    solaris*)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      case $cc_basename in
-      f77* | f90* | f95*)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';;
-      esac
-      ;;
-
-    sunos4*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    sysv4 | sysv4.2uw2* | sysv4.3*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec ;then
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      fi
-      ;;
-
-    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    unicos*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
-      ;;
-
-    uts4*)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    *)
-      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
-      ;;
-    esac
-  fi
-])
-case $host_os in
-  # For platforms which do not support PIC, -DPIC is meaningless:
-  *djgpp*)
-    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
-    ;;
-  *)
-    _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])"
-    ;;
-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])
-
-#
-# Check to make sure the PIC flag actually works.
-#
-if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
-  _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works],
-    [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)],
-    [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [],
-    [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in
-     "" | " "*) ;;
-     *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;;
-     esac],
-    [_LT_TAGVAR(lt_prog_compiler_pic, $1)=
-     _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no])
-fi
-_LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1],
-	[Additional compiler flags for building library objects])
-
-#
-# Check to make sure the static flag actually works.
-#
-wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\"
-_LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works],
-  _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1),
-  $lt_tmp_static_flag,
-  [],
-  [_LT_TAGVAR(lt_prog_compiler_static, $1)=])
-_LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1],
-	[Compiler flag to prevent dynamic linking])
-])# _LT_COMPILER_PIC
-
-
-# _LT_LINKER_SHLIBS([TAGNAME])
-# ----------------------------
-# See if the linker supports building shared libraries.
-m4_defun([_LT_LINKER_SHLIBS],
-[AC_REQUIRE([LT_PATH_LD])dnl
-AC_REQUIRE([LT_PATH_NM])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
-m4_require([_LT_TAG_COMPILER])dnl
-AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
-m4_if([$1], [CXX], [
-  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  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
-    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'
-    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'
-    fi
-    ;;
-  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'
-  ;;
-  *)
-    _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=
-  _LT_TAGVAR(allow_undefined_flag, $1)=
-  _LT_TAGVAR(always_export_symbols, $1)=no
-  _LT_TAGVAR(archive_cmds, $1)=
-  _LT_TAGVAR(archive_expsym_cmds, $1)=
-  _LT_TAGVAR(compiler_needs_object, $1)=no
-  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
-  _LT_TAGVAR(export_dynamic_flag_spec, $1)=
-  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  _LT_TAGVAR(hardcode_automatic, $1)=no
-  _LT_TAGVAR(hardcode_direct, $1)=no
-  _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
-  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
-  _LT_TAGVAR(inherit_rpath, $1)=no
-  _LT_TAGVAR(link_all_deplibs, $1)=unknown
-  _LT_TAGVAR(module_cmds, $1)=
-  _LT_TAGVAR(module_expsym_cmds, $1)=
-  _LT_TAGVAR(old_archive_from_new_cmds, $1)=
-  _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)=
-  _LT_TAGVAR(thread_safe_flag_spec, $1)=
-  _LT_TAGVAR(whole_archive_flag_spec, $1)=
-  # include_expsyms should be a list of space-separated symbols to be *always*
-  # included in the symbol list
-  _LT_TAGVAR(include_expsyms, $1)=
-  # exclude_expsyms can be an extended regexp of symbols to exclude
-  # it will be wrapped by ` (' and `)$', so one must not match beginning or
-  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
-  # as well as any symbol that contains `d'.
-  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
-  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
-  # platforms (ab)use it in PIC code, but their linkers get confused if
-  # the symbol is explicitly referenced.  Since portable code cannot
-  # rely on this symbol name, it's probably fine to never include it in
-  # preloaded symbol tables.
-  # Exclude shared library initialization/finalization symbols.
-dnl Note also adjust exclude_expsyms for C++ above.
-  extract_expsyms_cmds=
-
-  case $host_os in
-  cygwin* | mingw* | pw32* | cegcc*)
-    # FIXME: the MSVC++ port hasn't been tested in a loooong time
-    # When not using gcc, we currently assume that we are using
-    # Microsoft Visual C++.
-    if test "$GCC" != yes; then
-      with_gnu_ld=no
-    fi
-    ;;
-  interix*)
-    # we just hope/assume this is gcc and not c89 (= MSVC++)
-    with_gnu_ld=yes
-    ;;
-  openbsd*)
-    with_gnu_ld=no
-    ;;
-  esac
-
-  _LT_TAGVAR(ld_shlibs, $1)=yes
-  if test "$with_gnu_ld" = yes; then
-    # If archive_cmds runs LD, not CC, wlarc should be empty
-    wlarc='${wl}'
-
-    # Set some defaults for GNU ld with shared library support. These
-    # are reset later if shared libraries are not supported. Putting them
-    # here allows them to be overridden if necessary.
-    runpath_var=LD_RUN_PATH
-    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
-      _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-    else
-      _LT_TAGVAR(whole_archive_flag_spec, $1)=
-    fi
-    supports_anon_versioning=no
-    case `$LD -v 2>&1` in
-      *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
-      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
-      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
-      *\ 2.11.*) ;; # other 2.11 versions
-      *) supports_anon_versioning=yes ;;
-    esac
-
-    # See if GNU ld supports shared libraries.
-    case $host_os in
-    aix[[3-9]]*)
-      # On AIX/PPC, the GNU linker is very broken
-      if test "$host_cpu" != ia64; then
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: the GNU linker, at least up to release 2.9.1, 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.
-
-_LT_EOF
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-            _LT_TAGVAR(archive_expsym_cmds, $1)=''
-        ;;
-      m68k)
-            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
-            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-            _LT_TAGVAR(hardcode_minus_L, $1)=yes
-        ;;
-      esac
-      ;;
-
-    beos*)
-      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	# Joseph Beckenbach <jrb3@best.com> says some releases of gcc
-	# support --undefined.  This deserves some investigation.  FIXME
-	_LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    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
-      _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'
-
-      if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-	# 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 $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    interix[[3-9]]*)
-      _LT_TAGVAR(hardcode_direct, $1)=no
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-      # Instead, shared libraries are loaded at an image base (0x10000000 by
-      # default) and relocated if they conflict, which is a slow very memory
-      # consuming and fragmenting process.  To avoid this, we pick a random,
-      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      ;;
-
-    gnu* | linux* | tpf* | k*bsd*-gnu)
-      tmp_diet=no
-      if test "$host_os" = linux-dietlibc; then
-	case $cc_basename in
-	  diet\ *) tmp_diet=yes;;	# linux-dietlibc with static linking (!diet-dyn)
-	esac
-      fi
-      if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
-	 && test "$tmp_diet" = no
-      then
-	tmp_addflag=
-	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'
-	  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'
-	  tmp_addflag=' $pic_flag -Mnomain' ;;
-	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
-	  tmp_addflag=' -i_dynamic' ;;
-	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
-	  tmp_addflag=' -i_dynamic -nofor_main' ;;
-	ifc* | ifort*)			# Intel Fortran compiler
-	  tmp_addflag=' -nofor_main' ;;
-	lf95*)				# Lahey Fortran 8.1
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)=
-	  tmp_sharedflag='--shared' ;;
-	xl[[cC]]*)			# IBM XL C 8.0 on PPC (deal with xlf below)
-	  tmp_sharedflag='-qmkshrobj'
-	  tmp_addflag= ;;
-	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(compiler_needs_object, $1)=yes
-	  tmp_sharedflag='-G' ;;
-	*Sun\ F*)			# Sun Fortran 8.3
-	  tmp_sharedflag='-G' ;;
-	esac
-	_LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$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~
-	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
-        fi
-
-	case $cc_basename in
-	xlf*)
-	  # 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'
-	  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'
-	  fi
-	  ;;
-	esac
-      else
-        _LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    netbsd*)
-      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
-	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'
-      fi
-      ;;
-
-    solaris*)
-      if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: The releases 2.8.* of the GNU linker cannot reliably
-*** create shared libraries on Solaris systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.9.1 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_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'
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
-      case `$LD -v 2>&1` in
-        *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*)
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
-*** reliably create shared libraries on SCO systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-	;;
-	*)
-	  # For security reasons, it is highly recommended that you always
-	  # use absolute paths for naming shared libraries, and exclude the
-	  # DT_RUNPATH tag from executables and libraries.  But doing so
-	  # requires that you compile everything twice, which is a pain.
-	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	    _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'
-	  else
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	  fi
-	;;
-      esac
-      ;;
-
-    sunos4*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-      wlarc=
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    *)
-      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'
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-    esac
-
-    if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then
-      runpath_var=
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)=
-      _LT_TAGVAR(whole_archive_flag_spec, $1)=
-    fi
-  else
-    # PORTME fill in a description of your system's linker (not GNU ld)
-    case $host_os in
-    aix3*)
-      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-      _LT_TAGVAR(always_export_symbols, $1)=yes
-      _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
-      # Note: this linker hardcodes the directories in LIBPATH if there
-      # are no directories specified by -L.
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
-	# Neither direct hardcoding nor static linking is supported with a
-	# broken collect2.
-	_LT_TAGVAR(hardcode_direct, $1)=unsupported
-      fi
-      ;;
-
-    aix[[4-9]]*)
-      if test "$host_cpu" = ia64; then
-	# On IA64, the linker does run time linking by default, so we don't
-	# have to do anything special.
-	aix_use_runtimelinking=no
-	exp_sym_flag='-Bexport'
-	no_entry_flag=""
-      else
-	# 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
-	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'
-	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'
-	fi
-	aix_use_runtimelinking=no
-
-	# Test if we are trying to use run time linking or normal
-	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
-	# need to do runtime linking.
-	case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
-	  for ld_flag in $LDFLAGS; do
-	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
-	    aix_use_runtimelinking=yes
-	    break
-	  fi
-	  done
-	  ;;
-	esac
-
-	exp_sym_flag='-bexport'
-	no_entry_flag='-bnoentry'
-      fi
-
-      # When large executables or shared objects are built, AIX ld can
-      # have problems creating the table of contents.  If linking a library
-      # or program results in "error TOC overflow" add -mminimal-toc to
-      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
-
-      _LT_TAGVAR(archive_cmds, $1)=''
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
-
-      if test "$GCC" = yes; then
-	case $host_os in aix4.[[012]]|aix4.[[012]].*)
-	# We only want to do this on AIX 4.2 and lower, the check
-	# below for broken collect2 doesn't work under 4.3+
-	  collect2name=`${CC} -print-prog-name=collect2`
-	  if test -f "$collect2name" &&
-	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
-	  then
-	  # We have reworked collect2
-	  :
-	  else
-	  # We have old collect2
-	  _LT_TAGVAR(hardcode_direct, $1)=unsupported
-	  # It fails to find uninstalled libraries when the uninstalled
-	  # path is not listed in the libpath.  Setting hardcode_minus_L
-	  # to unsupported forces relinking
-	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-	  _LT_TAGVAR(hardcode_libdir_separator, $1)=
-	  fi
-	  ;;
-	esac
-	shared_flag='-shared'
-	if test "$aix_use_runtimelinking" = yes; then
-	  shared_flag="$shared_flag "'${wl}-G'
-	fi
-      else
-	# not using gcc
-	if test "$host_cpu" = ia64; then
-	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-	# chokes on -Wl,-G. The following line is correct:
-	  shared_flag='-G'
-	else
-	  if test "$aix_use_runtimelinking" = yes; then
-	    shared_flag='${wl}-G'
-	  else
-	    shared_flag='${wl}-bM:SRE'
-	  fi
-	fi
-      fi
-
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
-      # It seems that -bexpall does not export symbols beginning with
-      # underscore (_), so it is better to generate a list of symbols to export.
-      _LT_TAGVAR(always_export_symbols, $1)=yes
-      if test "$aix_use_runtimelinking" = yes; then
-	# Warning - without using the other runtime loading flags (-brtl),
-	# -berok will link without error, but may produce a broken library.
-	_LT_TAGVAR(allow_undefined_flag, $1)='-berok'
-        # Determine the default libpath from the value encoded in an
-        # empty executable.
-        _LT_SYS_MODULE_PATH_AIX
-        _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"
-      else
-	if test "$host_cpu" = ia64; then
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
-	  _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
-	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-	else
-	 # Determine the default libpath from the value encoded in an
-	 # empty executable.
-	 _LT_SYS_MODULE_PATH_AIX
-	 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-	  # Warning - without using the other run time loading flags,
-	  # -berok will link without error, but may produce a broken library.
-	  _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'
-	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
-	fi
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-            _LT_TAGVAR(archive_expsym_cmds, $1)=''
-        ;;
-      m68k)
-            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
-            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-            _LT_TAGVAR(hardcode_minus_L, $1)=yes
-        ;;
-      esac
-      ;;
-
-    bsdi[[45]]*)
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic
-      ;;
-
-    cygwin* | mingw* | pw32* | cegcc*)
-      # When not using gcc, we currently assume that we are using
-      # Microsoft Visual C++.
-      # 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
-      ;;
-
-    darwin* | rhapsody*)
-      _LT_DARWIN_LINKER_FEATURES($1)
-      ;;
-
-    dgux*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    freebsd1*)
-      _LT_TAGVAR(ld_shlibs, $1)=no
-      ;;
-
-    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
-    # support.  Future versions do this automatically, but an explicit c++rt0.o
-    # does not break anything, and helps significantly (at the cost of a little
-    # extra space).
-    freebsd2.2*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
-    freebsd2*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    # 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(hardcode_libdir_flag_spec, $1)='-R$libdir'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    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'
-      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'
-      fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-
-      # hardcode_minus_L: Not really in the search PATH,
-      # but as the default location of the library.
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-      ;;
-
-    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'
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      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
-	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	# hardcode_minus_L: Not really in the search PATH,
-	# but as the default location of the library.
-	_LT_TAGVAR(hardcode_minus_L, $1)=yes
-      fi
-      ;;
-
-    hpux11*)
-      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
-	case $host_cpu in
-	hppa*64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	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 -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      else
-	case $host_cpu in
-	hppa*64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      fi
-      if test "$with_gnu_ld" = no; then
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	case $host_cpu in
-	hppa*64*|ia64*)
-	  _LT_TAGVAR(hardcode_direct, $1)=no
-	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	  ;;
-	*)
-	  _LT_TAGVAR(hardcode_direct, $1)=yes
-	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-
-	  # hardcode_minus_L: Not really in the search PATH,
-	  # but as the default location of the library.
-	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
-	  ;;
-	esac
-      fi
-      ;;
-
-    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'
-	# 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"
-      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'
-      fi
-      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      _LT_TAGVAR(inherit_rpath, $1)=yes
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      ;;
-
-    netbsd*)
-      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
-      fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    newsos6)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    *nto* | *qnx*)
-      ;;
-
-    openbsd*)
-      if test -f /usr/libexec/ld.so; then
-	_LT_TAGVAR(hardcode_direct, $1)=yes
-	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	else
-	  case $host_os in
-	   openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
-	     _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	     ;;
-	   *)
-	     _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	     ;;
-	  esac
-	fi
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    os2*)
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _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(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
-      ;;
-
-    osf3*)
-      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'
-      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'
-      fi
-      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      ;;
-
-    osf4* | osf5*)	# as osf3* with the addition of -msym flag
-      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(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_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'
-
-	# Both c and cxx compiler support -rpath directly
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
-      fi
-      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      ;;
-
-    solaris*)
-      _LT_TAGVAR(no_undefined_flag, $1)=' -z defs'
-      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_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'
-      else
-	case `$CC -V 2>&1` in
-	*"Compilers 5.0"*)
-	  wlarc=''
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
-	  ;;
-	*)
-	  wlarc='${wl}'
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $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 -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
-	  ;;
-	esac
-      fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      case $host_os in
-      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
-      *)
-	# The compiler driver will combine and reorder linker options,
-	# but understands `-z linker_flag'.  GCC discards it without `$wl',
-	# but is careful enough not to reorder.
-	# Supported since Solaris 2.6 (maybe 2.5.1?)
-	if test "$GCC" = yes; then
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
-	else
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
-	fi
-	;;
-      esac
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      ;;
-
-    sunos4*)
-      if test "x$host_vendor" = xsequent; then
-	# Use $CC to link under sequent, because it throws in some extra .o
-	# files that make .init and .fini sections work.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    sysv4)
-      case $host_vendor in
-	sni)
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true???
-	;;
-	siemens)
-	  ## LD is ld it makes a PLAMLIB
-	  ## CC just makes a GrossModule.
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags'
-	  _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs'
-	  _LT_TAGVAR(hardcode_direct, $1)=no
-        ;;
-	motorola)
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie
-	;;
-      esac
-      runpath_var='LD_RUN_PATH'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    sysv4.3*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	_LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	runpath_var=LD_RUN_PATH
-	hardcode_runpath_var=yes
-	_LT_TAGVAR(ld_shlibs, $1)=yes
-      fi
-      ;;
-
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
-      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      runpath_var='LD_RUN_PATH'
-
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_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'
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
-      # link with -lc, and that would cause any symbols used from libc to
-      # always be unresolved, which means just about no library would
-      # ever link correctly.  If we're not using GNU ld we use -z text
-      # though, which does catch some bad symbols but isn't as heavy-handed
-      # as -z defs.
-      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-      _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
-      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
-      runpath_var='LD_RUN_PATH'
-
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_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'
-      fi
-      ;;
-
-    uts4*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    *)
-      _LT_TAGVAR(ld_shlibs, $1)=no
-      ;;
-    esac
-
-    if test x$host_vendor = xsni; then
-      case $host in
-      sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym'
-	;;
-      esac
-    fi
-  fi
-])
-AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
-test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
-
-_LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld
-
-_LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl
-_LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl
-_LT_DECL([], [extract_expsyms_cmds], [2],
-    [The commands to extract the exported symbol list from a shared archive])
-
-#
-# Do we need to explicitly link libc?
-#
-case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in
-x|xyes)
-  # Assume -lc should be added
-  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-
-  if test "$enable_shared" = yes && test "$GCC" = yes; then
-    case $_LT_TAGVAR(archive_cmds, $1) in
-    *'~'*)
-      # FIXME: we may have to deal with multi-command sequences.
-      ;;
-    '$CC '*)
-      # Test whether the compiler implicitly links with -lc since on some
-      # 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)])
-      ;;
-    esac
-  fi
-  ;;
-esac
-
-_LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0],
-    [Whether or not to add -lc for building shared libraries])
-_LT_TAGDECL([allow_libtool_libs_with_static_runtimes],
-    [enable_shared_with_static_runtimes], [0],
-    [Whether or not to disallow shared libs when runtime libs are static])
-_LT_TAGDECL([], [export_dynamic_flag_spec], [1],
-    [Compiler flag to allow reflexive dlopens])
-_LT_TAGDECL([], [whole_archive_flag_spec], [1],
-    [Compiler flag to generate shared objects directly from archives])
-_LT_TAGDECL([], [compiler_needs_object], [1],
-    [Whether the compiler copes with passing no objects directly])
-_LT_TAGDECL([], [old_archive_from_new_cmds], [2],
-    [Create an old-style archive from a shared archive])
-_LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2],
-    [Create a temporary old-style archive to link instead of a shared archive])
-_LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive])
-_LT_TAGDECL([], [archive_expsym_cmds], [2])
-_LT_TAGDECL([], [module_cmds], [2],
-    [Commands used to build a loadable module if different from building
-    a shared archive.])
-_LT_TAGDECL([], [module_expsym_cmds], [2])
-_LT_TAGDECL([], [with_gnu_ld], [1],
-    [Whether we are building with GNU ld or not])
-_LT_TAGDECL([], [allow_undefined_flag], [1],
-    [Flag that allows shared libraries with undefined symbols to be built])
-_LT_TAGDECL([], [no_undefined_flag], [1],
-    [Flag that enforces no undefined symbols])
-_LT_TAGDECL([], [hardcode_libdir_flag_spec], [1],
-    [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])
-_LT_TAGDECL([], [hardcode_direct], [0],
-    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
-    DIR into the resulting binary])
-_LT_TAGDECL([], [hardcode_direct_absolute], [0],
-    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
-    DIR into the resulting binary and the resulting library dependency is
-    "absolute", i.e impossible to change by setting ${shlibpath_var} if the
-    library is relocated])
-_LT_TAGDECL([], [hardcode_minus_L], [0],
-    [Set to "yes" if using the -LDIR flag during linking hardcodes DIR
-    into the resulting binary])
-_LT_TAGDECL([], [hardcode_shlibpath_var], [0],
-    [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
-    into the resulting binary])
-_LT_TAGDECL([], [hardcode_automatic], [0],
-    [Set to "yes" if building a shared library automatically hardcodes DIR
-    into the library and all subsequent libraries and executables linked
-    against it])
-_LT_TAGDECL([], [inherit_rpath], [0],
-    [Set to yes if linker adds runtime paths of dependent libraries
-    to runtime path list])
-_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])
-_LT_TAGDECL([], [export_symbols_cmds], [2],
-    [The commands to list exported symbols])
-_LT_TAGDECL([], [exclude_expsyms], [1],
-    [Symbols that should not be listed in the preloaded symbols])
-_LT_TAGDECL([], [include_expsyms], [1],
-    [Symbols that must always be exported])
-_LT_TAGDECL([], [prelink_cmds], [2],
-    [Commands necessary for linking programs (against libraries) with templates])
-_LT_TAGDECL([], [file_list_spec], [1],
-    [Specify filename containing input files])
-dnl FIXME: Not yet implemented
-dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1],
-dnl    [Compiler flag to generate thread safe objects])
-])# _LT_LINKER_SHLIBS
-
-
-# _LT_LANG_C_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_C_CONFIG],
-[m4_require([_LT_DECL_EGREP])dnl
-lt_save_CC="$CC"
-AC_LANG_PUSH(C)
-
-# Source file extension for C test sources.
-ac_ext=c
-
-# Object file extension for compiled C test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code="int some_variable = 0;"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code='int main(){return(0);}'
-
-_LT_TAG_COMPILER
-# Save the default compiler, since it gets overwritten when the other
-# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP.
-compiler_DEFAULT=$CC
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-## 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_SYS_DYNAMIC_LINKER($1)
-  _LT_LINKER_HARDCODE_LIBPATH($1)
-  LT_SYS_DLOPEN_SELF
-  _LT_CMD_STRIPLIB
-
-  # Report which library types will actually be built
-  AC_MSG_CHECKING([if libtool supports shared libraries])
-  AC_MSG_RESULT([$can_build_shared])
-
-  AC_MSG_CHECKING([whether to build shared libraries])
-  test "$can_build_shared" = "no" && enable_shared=no
-
-  # On AIX, shared libraries and static libraries use the same namespace, and
-  # are all built from PIC.
-  case $host_os in
-  aix3*)
-    test "$enable_shared" = yes && enable_static=no
-    if test -n "$RANLIB"; then
-      archive_cmds="$archive_cmds~\$RANLIB \$lib"
-      postinstall_cmds='$RANLIB $lib'
-    fi
-    ;;
-
-  aix[[4-9]]*)
-    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-      test "$enable_shared" = yes && enable_static=no
-    fi
-    ;;
-  esac
-  AC_MSG_RESULT([$enable_shared])
-
-  AC_MSG_CHECKING([whether to build static libraries])
-  # Make sure either enable_shared or enable_static is yes.
-  test "$enable_shared" = yes || enable_static=yes
-  AC_MSG_RESULT([$enable_static])
-
-  _LT_CONFIG($1)
-fi
-AC_LANG_POP
-CC="$lt_save_CC"
-])# _LT_LANG_C_CONFIG
-
-
-# _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
-if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
-    ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
-    (test "X$CXX" != "Xg++"))) ; then
-  AC_PROG_CXXCPP
-else
-  _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++)
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-_LT_TAGVAR(allow_undefined_flag, $1)=
-_LT_TAGVAR(always_export_symbols, $1)=no
-_LT_TAGVAR(archive_expsym_cmds, $1)=
-_LT_TAGVAR(compiler_needs_object, $1)=no
-_LT_TAGVAR(export_dynamic_flag_spec, $1)=
-_LT_TAGVAR(hardcode_direct, $1)=no
-_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
-_LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
-_LT_TAGVAR(hardcode_automatic, $1)=no
-_LT_TAGVAR(inherit_rpath, $1)=no
-_LT_TAGVAR(module_cmds, $1)=
-_LT_TAGVAR(module_expsym_cmds, $1)=
-_LT_TAGVAR(link_all_deplibs, $1)=unknown
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(no_undefined_flag, $1)=
-_LT_TAGVAR(whole_archive_flag_spec, $1)=
-_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
-
-# Source file extension for C++ test sources.
-ac_ext=cpp
-
-# Object file extension for compiled C++ test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# No sense in running all these tests if we already determined that
-# the CXX compiler isn't working.  Some variables (like enable_shared)
-# are currently assumed to apply to all compilers on this platform,
-# and will be corrupted by setting them based on a non-working compiler.
-if test "$_lt_caught_CXX_error" != yes; then
-  # Code to be used in simple compile tests
-  lt_simple_compile_test_code="int some_variable = 0;"
-
-  # Code to be used in simple link tests
-  lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }'
-
-  # 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_LD=$LD
-  lt_save_GCC=$GCC
-  GCC=$GXX
-  lt_save_with_gnu_ld=$with_gnu_ld
-  lt_save_path_LD=$lt_cv_path_LD
-  if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
-    lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
-  else
-    $as_unset lt_cv_prog_gnu_ld
-  fi
-  if test -n "${lt_cv_path_LDCXX+set}"; then
-    lt_cv_path_LD=$lt_cv_path_LDCXX
-  else
-    $as_unset lt_cv_path_LD
-  fi
-  test -z "${LDCXX+set}" || LD=$LDCXX
-  CC=${CXX-"c++"}
-  compiler=$CC
-  _LT_TAGVAR(compiler, $1)=$CC
-  _LT_CC_BASENAME([$compiler])
-
-  if test -n "$compiler"; then
-    # We don't want -fno-exception when compiling C++ code, so set the
-    # no_builtin_flag separately
-    if test "$GXX" = yes; then
-      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
-    else
-      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
-    fi
-
-    if test "$GXX" = yes; then
-      # Set up default GNU C++ configuration
-
-      LT_PATH_LD
-
-      # Check if GNU C++ uses GNU ld as the underlying linker, since the
-      # 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(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-
-        # If archive_cmds runs LD, not CC, wlarc should be empty
-        # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
-        #     investigate it a little bit more. (MM)
-        wlarc='${wl}'
-
-        # ancient GNU ld didn't support --whole-archive et. al.
-        if eval "`$CC -print-prog-name=ld` --help 2>&1" |
-	  $GREP 'no-whole-archive' > /dev/null; then
-          _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-        else
-          _LT_TAGVAR(whole_archive_flag_spec, $1)=
-        fi
-      else
-        with_gnu_ld=no
-        wlarc=
-
-        # A generic and very simple default shared library creation
-        # command for GNU C++ for the case where it uses the native
-        # linker, instead of GNU ld.  If possible, this setting should
-        # overridden to take advantage of the native linker features on
-        # the platform it is being used on.
-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
-      fi
-
-      # 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"'
-
-    else
-      GXX=no
-      with_gnu_ld=no
-      wlarc=
-    fi
-
-    # PORTME: fill in a description of your system's C++ link characteristics
-    AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
-    _LT_TAGVAR(ld_shlibs, $1)=yes
-    case $host_os in
-      aix3*)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-      aix[[4-9]]*)
-        if test "$host_cpu" = ia64; then
-          # On IA64, the linker does run time linking by default, so we don't
-          # have to do anything special.
-          aix_use_runtimelinking=no
-          exp_sym_flag='-Bexport'
-          no_entry_flag=""
-        else
-          aix_use_runtimelinking=no
-
-          # Test if we are trying to use run time linking or normal
-          # AIX style linking. If -brtl is somewhere in LDFLAGS, we
-          # need to do runtime linking.
-          case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
-	    for ld_flag in $LDFLAGS; do
-	      case $ld_flag in
-	      *-brtl*)
-	        aix_use_runtimelinking=yes
-	        break
-	        ;;
-	      esac
-	    done
-	    ;;
-          esac
-
-          exp_sym_flag='-bexport'
-          no_entry_flag='-bnoentry'
-        fi
-
-        # When large executables or shared objects are built, AIX ld can
-        # have problems creating the table of contents.  If linking a library
-        # or program results in "error TOC overflow" add -mminimal-toc to
-        # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-        # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
-
-        _LT_TAGVAR(archive_cmds, $1)=''
-        _LT_TAGVAR(hardcode_direct, $1)=yes
-        _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-        _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
-        _LT_TAGVAR(link_all_deplibs, $1)=yes
-        _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
-
-        if test "$GXX" = yes; then
-          case $host_os in aix4.[[012]]|aix4.[[012]].*)
-          # We only want to do this on AIX 4.2 and lower, the check
-          # below for broken collect2 doesn't work under 4.3+
-	  collect2name=`${CC} -print-prog-name=collect2`
-	  if test -f "$collect2name" &&
-	     strings "$collect2name" | $GREP resolve_lib_name >/dev/null
-	  then
-	    # We have reworked collect2
-	    :
-	  else
-	    # We have old collect2
-	    _LT_TAGVAR(hardcode_direct, $1)=unsupported
-	    # It fails to find uninstalled libraries when the uninstalled
-	    # path is not listed in the libpath.  Setting hardcode_minus_L
-	    # to unsupported forces relinking
-	    _LT_TAGVAR(hardcode_minus_L, $1)=yes
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-	    _LT_TAGVAR(hardcode_libdir_separator, $1)=
-	  fi
-          esac
-          shared_flag='-shared'
-	  if test "$aix_use_runtimelinking" = yes; then
-	    shared_flag="$shared_flag "'${wl}-G'
-	  fi
-        else
-          # not using gcc
-          if test "$host_cpu" = ia64; then
-	  # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-	  # chokes on -Wl,-G. The following line is correct:
-	  shared_flag='-G'
-          else
-	    if test "$aix_use_runtimelinking" = yes; then
-	      shared_flag='${wl}-G'
-	    else
-	      shared_flag='${wl}-bM:SRE'
-	    fi
-          fi
-        fi
-
-        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
-        # It seems that -bexpall does not export symbols beginning with
-        # underscore (_), so it is better to generate a list of symbols to
-	# export.
-        _LT_TAGVAR(always_export_symbols, $1)=yes
-        if test "$aix_use_runtimelinking" = yes; then
-          # Warning - without using the other runtime loading flags (-brtl),
-          # -berok will link without error, but may produce a broken library.
-          _LT_TAGVAR(allow_undefined_flag, $1)='-berok'
-          # Determine the default libpath from the value encoded in an empty
-          # executable.
-          _LT_SYS_MODULE_PATH_AIX
-          _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"
-        else
-          if test "$host_cpu" = ia64; then
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
-	    _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
-	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-          else
-	    # Determine the default libpath from the value encoded in an
-	    # empty executable.
-	    _LT_SYS_MODULE_PATH_AIX
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-	    # Warning - without using the other run time loading flags,
-	    # -berok will link without error, but may produce a broken library.
-	    _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'
-	    _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-	    # This is similar to how AIX traditionally builds its shared
-	    # libraries.
-	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
-          fi
-        fi
-        ;;
-
-      beos*)
-	if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	  # Joseph Beckenbach <jrb3@best.com> says some releases of gcc
-	  # support --undefined.  This deserves some investigation.  FIXME
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	else
-	  _LT_TAGVAR(ld_shlibs, $1)=no
-	fi
-	;;
-
-      chorus*)
-        case $cc_basename in
-          *)
-	  # FIXME: insert proper C++ library support
-	  _LT_TAGVAR(ld_shlibs, $1)=no
-	  ;;
-        esac
-        ;;
-
-      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
-        ;;
-      darwin* | rhapsody*)
-        _LT_DARWIN_LINKER_FEATURES($1)
-	;;
-
-      dgux*)
-        case $cc_basename in
-          ec++*)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          ghcx*)
-	    # Green Hills C++ Compiler
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          *)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-        esac
-        ;;
-
-      freebsd[[12]]*)
-        # C++ shared libraries reported to be fairly broken before
-	# switch to ELF
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-
-      freebsd-elf*)
-        _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-        ;;
-
-      freebsd* | dragonfly*)
-        # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
-        # conventions
-        _LT_TAGVAR(ld_shlibs, $1)=yes
-        ;;
-
-      gnu*)
-        ;;
-
-      hpux9*)
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-        _LT_TAGVAR(hardcode_direct, $1)=yes
-        _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
-				             # but as the default
-				             # location of the library.
-
-        case $cc_basename in
-          CC*)
-            # FIXME: insert proper C++ library support
-            _LT_TAGVAR(ld_shlibs, $1)=no
-            ;;
-          aCC*)
-            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${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'
-            # Commands to make compiler produce verbose output that lists
-            # what "hidden" libraries, object files and flags are used when
-            # linking a shared library.
-            #
-            # There doesn't appear to be a way to prevent this compiler from
-            # explicitly linking system object files so we need to strip them
-            # 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'
-            ;;
-          *)
-            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'
-            else
-              # FIXME: insert proper C++ library support
-              _LT_TAGVAR(ld_shlibs, $1)=no
-            fi
-            ;;
-        esac
-        ;;
-
-      hpux10*|hpux11*)
-        if test $with_gnu_ld = no; then
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-	  _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-          case $host_cpu in
-            hppa*64*|ia64*)
-              ;;
-            *)
-	      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-              ;;
-          esac
-        fi
-        case $host_cpu in
-          hppa*64*|ia64*)
-            _LT_TAGVAR(hardcode_direct, $1)=no
-            _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-            ;;
-          *)
-            _LT_TAGVAR(hardcode_direct, $1)=yes
-            _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-            _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
-					         # but as the default
-					         # location of the library.
-            ;;
-        esac
-
-        case $cc_basename in
-          CC*)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          aCC*)
-	    case $host_cpu in
-	      hppa*64*)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	        ;;
-	      ia64*)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	        ;;
-	      *)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	        ;;
-	    esac
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    #
-	    # There doesn't appear to be a way to prevent this compiler from
-	    # explicitly linking system object files so we need to strip them
-	    # 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'
-	    ;;
-          *)
-	    if test "$GXX" = yes; then
-	      if test $with_gnu_ld = no; then
-	        case $host_cpu in
-	          hppa*64*)
-	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	            ;;
-	          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 -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	            ;;
-	        esac
-	      fi
-	    else
-	      # FIXME: insert proper C++ library support
-	      _LT_TAGVAR(ld_shlibs, $1)=no
-	    fi
-	    ;;
-        esac
-        ;;
-
-      interix[[3-9]]*)
-	_LT_TAGVAR(hardcode_direct, $1)=no
-	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	# Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-	# Instead, shared libraries are loaded at an image base (0x10000000 by
-	# default) and relocated if they conflict, which is a slow very memory
-	# consuming and fragmenting process.  To avoid this, we pick a random,
-	# 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-	# time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-	;;
-      irix5* | irix6*)
-        case $cc_basename in
-          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'
-
-	    # Archives containing C++ object files must be created using
-	    # "CC -ar", where "CC" is the IRIX C++ compiler.  This is
-	    # necessary to make sure instantiated templates are included
-	    # in the archive.
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs'
-	    ;;
-          *)
-	    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'
-	      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'
-	      fi
-	    fi
-	    _LT_TAGVAR(link_all_deplibs, $1)=yes
-	    ;;
-        esac
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-        _LT_TAGVAR(inherit_rpath, $1)=yes
-        ;;
-
-      linux* | k*bsd*-gnu)
-        case $cc_basename in
-          KCC*)
-	    # Kuck and Associates, Inc. (KAI) C++ Compiler
-
-	    # KCC will only create a shared library if the output file
-	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
-	    # to its proper name (with version) after linking.
-	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    #
-	    # There doesn't appear to be a way to prevent this compiler from
-	    # explicitly linking system object files so we need to strip them
-	    # 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'
-
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-
-	    # Archives containing C++ object files must be created using
-	    # "CC -Bstatic", where "CC" is the KAI C++ compiler.
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
-	    ;;
-	  icpc* | ecpc* )
-	    # Intel C++
-	    with_gnu_ld=yes
-	    # version 8.0 and above of icpc choke on multiply defined symbols
-	    # if we add $predep_objects and $postdep_objects, however 7.1 and
-	    # earlier do not add the objects themselves.
-	    case `$CC -V 2>&1` in
-	      *"Version 7."*)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-		;;
-	      *)  # Version 8.0 or newer
-	        tmp_idyn=
-	        case $host_cpu in
-		  ia64*) tmp_idyn=' -i_dynamic';;
-		esac
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-		;;
-	    esac
-	    _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
-	    ;;
-          pgCC* | pgcpp*)
-            # Portland Group C++ compiler
-	    case `$CC -V` in
-	    *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`"'
-	      _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`~
-		$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'
-	      _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'
-	      ;;
-	    *) # Version 6 will 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'
-	      ;;
-	    esac
-
-	    _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'
-            ;;
-	  cxx*)
-	    # Compaq C++
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
-
-	    runpath_var=LD_RUN_PATH
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
-	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    #
-	    # There doesn't appear to be a way to prevent this compiler from
-	    # explicitly linking system object files so we need to strip them
-	    # 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'
-	    ;;
-	  xl*)
-	    # IBM XL 8.0 on PPC, with GNU ld
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$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~
-		$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
-	    fi
-	    ;;
-	  *)
-	    case `$CC -V 2>&1 | sed 5q` in
-	    *Sun\ C*)
-	      # Sun C++ 5.9
-	      _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
-	      _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	      _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(compiler_needs_object, $1)=yes
-
-	      # Not sure whether something based on
-	      # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1
-	      # would be better.
-	      output_verbose_link_cmd='echo'
-
-	      # Archives containing C++ object files must be created using
-	      # "CC -xar", where "CC" is the Sun C++ compiler.  This is
-	      # necessary to make sure instantiated templates are included
-	      # in the archive.
-	      _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
-	      ;;
-	    esac
-	    ;;
-	esac
-	;;
-
-      lynxos*)
-        # FIXME: insert proper C++ library support
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	;;
-
-      m88k*)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-	;;
-
-      mvs*)
-        case $cc_basename in
-          cxx*)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-	  *)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-	esac
-	;;
-
-      netbsd*)
-        if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable  -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
-	  wlarc=
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	  _LT_TAGVAR(hardcode_direct, $1)=yes
-	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	fi
-	# Workaround some broken pre-1.5 toolchains
-	output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
-	;;
-
-      *nto* | *qnx*)
-        _LT_TAGVAR(ld_shlibs, $1)=yes
-	;;
-
-      openbsd2*)
-        # C++ shared libraries are fairly broken
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	;;
-
-      openbsd*)
-	if test -f /usr/libexec/ld.so; then
-	  _LT_TAGVAR(hardcode_direct, $1)=yes
-	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-	  fi
-	  output_verbose_link_cmd=echo
-	else
-	  _LT_TAGVAR(ld_shlibs, $1)=no
-	fi
-	;;
-
-      osf3* | osf4* | osf5*)
-        case $cc_basename in
-          KCC*)
-	    # Kuck and Associates, Inc. (KAI) C++ Compiler
-
-	    # KCC will only create a shared library if the output file
-	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
-	    # to its proper name (with version) after linking.
-	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
-
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	    # Archives containing C++ object files must be created using
-	    # the KAI C++ compiler.
-	    case $host in
-	      osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;;
-	      *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;;
-	    esac
-	    ;;
-          RCC*)
-	    # Rational C++ 2.4.1
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          cxx*)
-	    case $host in
-	      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(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_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~
-	          $RM $lib.exp'
-	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
-		;;
-	    esac
-
-	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    #
-	    # There doesn't appear to be a way to prevent this compiler from
-	    # explicitly linking system object files so we need to strip them
-	    # 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'
-	    ;;
-	  *)
-	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
-	      _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	      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}-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'
-		  ;;
-	      esac
-
-	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	      # 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"'
-
-	    else
-	      # FIXME: insert proper C++ library support
-	      _LT_TAGVAR(ld_shlibs, $1)=no
-	    fi
-	    ;;
-        esac
-        ;;
-
-      psos*)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-
-      sunos4*)
-        case $cc_basename in
-          CC*)
-	    # Sun C++ 4.x
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          lcc*)
-	    # Lucid
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          *)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-        esac
-        ;;
-
-      solaris*)
-        case $cc_basename in
-          CC*)
-	    # Sun C++ 4.2, 5.x and Centerline C++
-            _LT_TAGVAR(archive_cmds_need_lc,$1)=yes
-	    _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $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 -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
-
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	    _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	    case $host_os in
-	      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
-	      *)
-		# The compiler driver will combine and reorder linker options,
-		# but understands `-z linker_flag'.
-	        # Supported since Solaris 2.6 (maybe 2.5.1?)
-		_LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
-	        ;;
-	    esac
-	    _LT_TAGVAR(link_all_deplibs, $1)=yes
-
-	    output_verbose_link_cmd='echo'
-
-	    # Archives containing C++ object files must be created using
-	    # "CC -xar", where "CC" is the Sun C++ compiler.  This is
-	    # necessary to make sure instantiated templates are included
-	    # in the archive.
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
-	    ;;
-          gcx*)
-	    # Green Hills C++ Compiler
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
-
-	    # The C++ compiler must be used to create the archive.
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
-	    ;;
-          *)
-	    # GNU C++ compiler with Solaris linker
-	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
-	      _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_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'
-
-	        # 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"'
-	      else
-	        # g++ 2.7 appears to require `-G' NOT `-shared' on this
-	        # platform.
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -G -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 -G -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 -G $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
-	      fi
-
-	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir'
-	      case $host_os in
-		solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
-		*)
-		  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
-		  ;;
-	      esac
-	    fi
-	    ;;
-        esac
-        ;;
-
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
-      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      runpath_var='LD_RUN_PATH'
-
-      case $cc_basename in
-        CC*)
-	  _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(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-      esac
-      ;;
-
-      sysv5* | sco3.2v5* | sco5v6*)
-	# Note: We can NOT use -z defs as we might desire, because we do not
-	# link with -lc, and that would cause any symbols used from libc to
-	# always be unresolved, which means just about no library would
-	# ever link correctly.  If we're not using GNU ld we use -z text
-	# though, which does catch some bad symbols but isn't as heavy-handed
-	# as -z defs.
-	_LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-	_LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
-	_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
-	_LT_TAGVAR(hardcode_libdir_separator, $1)=':'
-	_LT_TAGVAR(link_all_deplibs, $1)=yes
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
-	runpath_var='LD_RUN_PATH'
-
-	case $cc_basename in
-          CC*)
-	    _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(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	    ;;
-	esac
-      ;;
-
-      tandem*)
-        case $cc_basename in
-          NCC*)
-	    # NonStop-UX NCC 3.20
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          *)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-        esac
-        ;;
-
-      vxworks*)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-
-      *)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-    esac
-
-    AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
-    test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
-
-    _LT_TAGVAR(GCC, $1)="$GXX"
-    _LT_TAGVAR(LD, $1)="$LD"
-
-    ## 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...
-    _LT_SYS_HIDDEN_LIBDEPS($1)
-    _LT_COMPILER_PIC($1)
-    _LT_COMPILER_C_O($1)
-    _LT_COMPILER_FILE_LOCKS($1)
-    _LT_LINKER_SHLIBS($1)
-    _LT_SYS_DYNAMIC_LINKER($1)
-    _LT_LINKER_HARDCODE_LIBPATH($1)
-
-    _LT_CONFIG($1)
-  fi # test -n "$compiler"
-
-  CC=$lt_save_CC
-  LDCXX=$LD
-  LD=$lt_save_LD
-  GCC=$lt_save_GCC
-  with_gnu_ld=$lt_save_with_gnu_ld
-  lt_cv_path_LDCXX=$lt_cv_path_LD
-  lt_cv_path_LD=$lt_save_path_LD
-  lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
-  lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
-fi # test "$_lt_caught_CXX_error" != yes
-
-AC_LANG_POP
-])# _LT_LANG_CXX_CONFIG
-
-
-# _LT_SYS_HIDDEN_LIBDEPS([TAGNAME])
-# ---------------------------------
-# Figure out "hidden" library dependencies from verbose
-# compiler output when linking a shared library.
-# Parse the compiler output and extract the necessary
-# objects, libraries and library flags.
-m4_defun([_LT_SYS_HIDDEN_LIBDEPS],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-# Dependencies to place before and after the object being linked:
-_LT_TAGVAR(predep_objects, $1)=
-_LT_TAGVAR(postdep_objects, $1)=
-_LT_TAGVAR(predeps, $1)=
-_LT_TAGVAR(postdeps, $1)=
-_LT_TAGVAR(compiler_lib_search_path, $1)=
-
-dnl we can't use the lt_simple_compile_test_code here,
-dnl because it contains code intended for an executable,
-dnl not a library.  It's possible we should let each
-dnl tag define a new lt_????_link_test_code variable,
-dnl but it's only used here...
-m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF
-int a;
-void foo (void) { a = 0; }
-_LT_EOF
-], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF
-class Foo
-{
-public:
-  Foo (void) { a = 0; }
-private:
-  int a;
-};
-_LT_EOF
-], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF
-      subroutine foo
-      implicit none
-      integer*4 a
-      a=0
-      return
-      end
-_LT_EOF
-], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF
-      subroutine foo
-      implicit none
-      integer a
-      a=0
-      return
-      end
-_LT_EOF
-], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF
-public class foo {
-  private int a;
-  public void bar (void) {
-    a = 0;
-  }
-};
-_LT_EOF
-])
-dnl Parse the compiler output and extract the necessary
-dnl objects, libraries and library flags.
-if AC_TRY_EVAL(ac_compile); then
-  # Parse the compiler output and extract the necessary
-  # objects, libraries and library flags.
-
-  # Sentinel used to keep track of whether or not we are before
-  # the conftest object file.
-  pre_test_object_deps_done=no
-
-  for p in `eval "$output_verbose_link_cmd"`; do
-    case $p in
-
-    -L* | -R* | -l*)
-       # Some compilers place space between "-{L,R}" and the path.
-       # Remove the space.
-       if test $p = "-L" ||
-          test $p = "-R"; then
-	 prev=$p
-	 continue
-       else
-	 prev=
-       fi
-
-       if test "$pre_test_object_deps_done" = no; then
-	 case $p in
-	 -L* | -R*)
-	   # Internal compiler library paths should come after those
-	   # provided the user.  The postdeps already come after the
-	   # user supplied libs so there is no need to process them.
-	   if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then
-	     _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}"
-	   else
-	     _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}"
-	   fi
-	   ;;
-	 # The "-l" case would never come before the object being
-	 # linked, so don't bother handling this case.
-	 esac
-       else
-	 if test -z "$_LT_TAGVAR(postdeps, $1)"; then
-	   _LT_TAGVAR(postdeps, $1)="${prev}${p}"
-	 else
-	   _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}"
-	 fi
-       fi
-       ;;
-
-    *.$objext)
-       # This assumes that the test object file only shows up
-       # once in the compiler output.
-       if test "$p" = "conftest.$objext"; then
-	 pre_test_object_deps_done=yes
-	 continue
-       fi
-
-       if test "$pre_test_object_deps_done" = no; then
-	 if test -z "$_LT_TAGVAR(predep_objects, $1)"; then
-	   _LT_TAGVAR(predep_objects, $1)="$p"
-	 else
-	   _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p"
-	 fi
-       else
-	 if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then
-	   _LT_TAGVAR(postdep_objects, $1)="$p"
-	 else
-	   _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p"
-	 fi
-       fi
-       ;;
-
-    *) ;; # Ignore the rest.
-
-    esac
-  done
-
-  # Clean up.
-  rm -f a.out a.exe
-else
-  echo "libtool.m4: error: problem compiling $1 test program"
-fi
-
-$RM -f confest.$objext
-
-# PORTME: override above test on systems where it is broken
-m4_if([$1], [CXX],
-[case $host_os in
-interix[[3-9]]*)
-  # Interix 3.5 installs completely hosed .la files for C++, so rather than
-  # hack all around it, let's just trust "g++" to DTRT.
-  _LT_TAGVAR(predep_objects,$1)=
-  _LT_TAGVAR(postdep_objects,$1)=
-  _LT_TAGVAR(postdeps,$1)=
-  ;;
-
-linux*)
-  case `$CC -V 2>&1 | sed 5q` in
-  *Sun\ C*)
-    # Sun C++ 5.9
-
-    # The more standards-conforming stlport4 library is
-    # incompatible with the Cstd library. Avoid specifying
-    # it if it's in CXXFLAGS. Ignore libCrun as
-    # -library=stlport4 depends on it.
-    case " $CXX $CXXFLAGS " in
-    *" -library=stlport4 "*)
-      solaris_use_stlport4=yes
-      ;;
-    esac
-
-    if test "$solaris_use_stlport4" != yes; then
-      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
-    fi
-    ;;
-  esac
-  ;;
-
-solaris*)
-  case $cc_basename in
-  CC*)
-    # The more standards-conforming stlport4 library is
-    # incompatible with the Cstd library. Avoid specifying
-    # it if it's in CXXFLAGS. Ignore libCrun as
-    # -library=stlport4 depends on it.
-    case " $CXX $CXXFLAGS " in
-    *" -library=stlport4 "*)
-      solaris_use_stlport4=yes
-      ;;
-    esac
-
-    # Adding this requires a known-good setup of shared libraries for
-    # Sun compiler versions before 5.6, else PIC objects from an old
-    # archive will be linked into the output, leading to subtle bugs.
-    if test "$solaris_use_stlport4" != yes; then
-      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
-    fi
-    ;;
-  esac
-  ;;
-esac
-])
-
-case " $_LT_TAGVAR(postdeps, $1) " in
-*" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;;
-esac
- _LT_TAGVAR(compiler_lib_search_dirs, $1)=
-if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then
- _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'`
-fi
-_LT_TAGDECL([], [compiler_lib_search_dirs], [1],
-    [The directories searched by this compiler when creating a shared library])
-_LT_TAGDECL([], [predep_objects], [1],
-    [Dependencies to place before and after the objects being linked to
-    create a shared library])
-_LT_TAGDECL([], [postdep_objects], [1])
-_LT_TAGDECL([], [predeps], [1])
-_LT_TAGDECL([], [postdeps], [1])
-_LT_TAGDECL([], [compiler_lib_search_path], [1],
-    [The library search path used internally by the compiler when linking
-    a shared library])
-])# _LT_SYS_HIDDEN_LIBDEPS
-
-
-# _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])
-# --------------------------
-# Ensure that the configuration variables for a Fortran 77 compiler are
-# suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_F77_CONFIG],
-[AC_REQUIRE([_LT_PROG_F77])dnl
-AC_LANG_PUSH(Fortran 77)
-
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-_LT_TAGVAR(allow_undefined_flag, $1)=
-_LT_TAGVAR(always_export_symbols, $1)=no
-_LT_TAGVAR(archive_expsym_cmds, $1)=
-_LT_TAGVAR(export_dynamic_flag_spec, $1)=
-_LT_TAGVAR(hardcode_direct, $1)=no
-_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
-_LT_TAGVAR(hardcode_automatic, $1)=no
-_LT_TAGVAR(inherit_rpath, $1)=no
-_LT_TAGVAR(module_cmds, $1)=
-_LT_TAGVAR(module_expsym_cmds, $1)=
-_LT_TAGVAR(link_all_deplibs, $1)=unknown
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(no_undefined_flag, $1)=
-_LT_TAGVAR(whole_archive_flag_spec, $1)=
-_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
-
-# Source file extension for f77 test sources.
-ac_ext=f
-
-# Object file extension for compiled f77 test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# No sense in running all these tests if we already determined that
-# the F77 compiler isn't working.  Some variables (like enable_shared)
-# are currently assumed to apply to all compilers on this platform,
-# and will be corrupted by setting them based on a non-working compiler.
-if test "$_lt_disable_F77" != yes; then
-  # Code to be used in simple compile tests
-  lt_simple_compile_test_code="\
-      subroutine t
-      return
-      end
-"
-
-  # Code to be used in simple link tests
-  lt_simple_link_test_code="\
-      program t
-      end
-"
-
-  # 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_GCC=$GCC
-  CC=${F77-"f77"}
-  compiler=$CC
-  _LT_TAGVAR(compiler, $1)=$CC
-  _LT_CC_BASENAME([$compiler])
-  GCC=$G77
-  if test -n "$compiler"; then
-    AC_MSG_CHECKING([if libtool supports shared libraries])
-    AC_MSG_RESULT([$can_build_shared])
-
-    AC_MSG_CHECKING([whether to build shared libraries])
-    test "$can_build_shared" = "no" && enable_shared=no
-
-    # On AIX, shared libraries and static libraries use the same namespace, and
-    # are all built from PIC.
-    case $host_os in
-      aix3*)
-        test "$enable_shared" = yes && enable_static=no
-        if test -n "$RANLIB"; then
-          archive_cmds="$archive_cmds~\$RANLIB \$lib"
-          postinstall_cmds='$RANLIB $lib'
-        fi
-        ;;
-      aix[[4-9]]*)
-	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-	  test "$enable_shared" = yes && enable_static=no
-	fi
-        ;;
-    esac
-    AC_MSG_RESULT([$enable_shared])
-
-    AC_MSG_CHECKING([whether to build static libraries])
-    # Make sure either enable_shared or enable_static is yes.
-    test "$enable_shared" = yes || enable_static=yes
-    AC_MSG_RESULT([$enable_static])
-
-    _LT_TAGVAR(GCC, $1)="$G77"
-    _LT_TAGVAR(LD, $1)="$LD"
-
-    ## 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...
-    _LT_COMPILER_PIC($1)
-    _LT_COMPILER_C_O($1)
-    _LT_COMPILER_FILE_LOCKS($1)
-    _LT_LINKER_SHLIBS($1)
-    _LT_SYS_DYNAMIC_LINKER($1)
-    _LT_LINKER_HARDCODE_LIBPATH($1)
-
-    _LT_CONFIG($1)
-  fi # test -n "$compiler"
-
-  GCC=$lt_save_GCC
-  CC="$lt_save_CC"
-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], [])
-
-
-# _LT_LANG_FC_CONFIG([TAG])
-# -------------------------
-# Ensure that the configuration variables for a Fortran compiler are
-# suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_FC_CONFIG],
-[AC_REQUIRE([_LT_PROG_FC])dnl
-AC_LANG_PUSH(Fortran)
-
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-_LT_TAGVAR(allow_undefined_flag, $1)=
-_LT_TAGVAR(always_export_symbols, $1)=no
-_LT_TAGVAR(archive_expsym_cmds, $1)=
-_LT_TAGVAR(export_dynamic_flag_spec, $1)=
-_LT_TAGVAR(hardcode_direct, $1)=no
-_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
-_LT_TAGVAR(hardcode_automatic, $1)=no
-_LT_TAGVAR(inherit_rpath, $1)=no
-_LT_TAGVAR(module_cmds, $1)=
-_LT_TAGVAR(module_expsym_cmds, $1)=
-_LT_TAGVAR(link_all_deplibs, $1)=unknown
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(no_undefined_flag, $1)=
-_LT_TAGVAR(whole_archive_flag_spec, $1)=
-_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
-
-# Source file extension for fc test sources.
-ac_ext=${ac_fc_srcext-f}
-
-# Object file extension for compiled fc test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# No sense in running all these tests if we already determined that
-# the FC compiler isn't working.  Some variables (like enable_shared)
-# are currently assumed to apply to all compilers on this platform,
-# and will be corrupted by setting them based on a non-working compiler.
-if test "$_lt_disable_FC" != yes; then
-  # Code to be used in simple compile tests
-  lt_simple_compile_test_code="\
-      subroutine t
-      return
-      end
-"
-
-  # Code to be used in simple link tests
-  lt_simple_link_test_code="\
-      program t
-      end
-"
-
-  # 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_GCC=$GCC
-  CC=${FC-"f95"}
-  compiler=$CC
-  GCC=$ac_cv_fc_compiler_gnu
-
-  _LT_TAGVAR(compiler, $1)=$CC
-  _LT_CC_BASENAME([$compiler])
-
-  if test -n "$compiler"; then
-    AC_MSG_CHECKING([if libtool supports shared libraries])
-    AC_MSG_RESULT([$can_build_shared])
-
-    AC_MSG_CHECKING([whether to build shared libraries])
-    test "$can_build_shared" = "no" && enable_shared=no
-
-    # On AIX, shared libraries and static libraries use the same namespace, and
-    # are all built from PIC.
-    case $host_os in
-      aix3*)
-        test "$enable_shared" = yes && enable_static=no
-        if test -n "$RANLIB"; then
-          archive_cmds="$archive_cmds~\$RANLIB \$lib"
-          postinstall_cmds='$RANLIB $lib'
-        fi
-        ;;
-      aix[[4-9]]*)
-	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-	  test "$enable_shared" = yes && enable_static=no
-	fi
-        ;;
-    esac
-    AC_MSG_RESULT([$enable_shared])
-
-    AC_MSG_CHECKING([whether to build static libraries])
-    # Make sure either enable_shared or enable_static is yes.
-    test "$enable_shared" = yes || enable_static=yes
-    AC_MSG_RESULT([$enable_static])
-
-    _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu"
-    _LT_TAGVAR(LD, $1)="$LD"
-
-    ## 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...
-    _LT_SYS_HIDDEN_LIBDEPS($1)
-    _LT_COMPILER_PIC($1)
-    _LT_COMPILER_C_O($1)
-    _LT_COMPILER_FILE_LOCKS($1)
-    _LT_LINKER_SHLIBS($1)
-    _LT_SYS_DYNAMIC_LINKER($1)
-    _LT_LINKER_HARDCODE_LIBPATH($1)
-
-    _LT_CONFIG($1)
-  fi # test -n "$compiler"
-
-  GCC=$lt_save_GCC
-  CC="$lt_save_CC"
-fi # test "$_lt_disable_FC" != yes
-
-AC_LANG_POP
-])# _LT_LANG_FC_CONFIG
-
-
-# _LT_LANG_GCJ_CONFIG([TAG])
-# --------------------------
-# Ensure that the configuration variables for the GNU Java Compiler compiler
-# are suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_GCJ_CONFIG],
-[AC_REQUIRE([LT_PROG_GCJ])dnl
-AC_LANG_SAVE
-
-# Source file extension for Java test sources.
-ac_ext=java
-
-# Object file extension for compiled Java test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code="class foo {}"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }'
-
-# 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_GCC=$GCC
-GCC=yes
-CC=${GCJ-"gcj"}
-compiler=$CC
-_LT_TAGVAR(compiler, $1)=$CC
-_LT_TAGVAR(LD, $1)="$LD"
-_LT_CC_BASENAME([$compiler])
-
-# GCJ 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
-
-## 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"
-])# _LT_LANG_GCJ_CONFIG
-
-
-# _LT_LANG_RC_CONFIG([TAG])
-# -------------------------
-# Ensure that the configuration variables for the Windows resource compiler
-# are suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_RC_CONFIG],
-[AC_REQUIRE([LT_PROG_RC])dnl
-AC_LANG_SAVE
-
-# Source file extension for RC test sources.
-ac_ext=rc
-
-# Object file extension for compiled RC test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }'
-
-# Code to be used in simple link tests
-lt_simple_link_test_code="$lt_simple_compile_test_code"
-
-# 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_GCC=$GCC
-GCC=
-CC=${RC-"windres"}
-compiler=$CC
-_LT_TAGVAR(compiler, $1)=$CC
-_LT_CC_BASENAME([$compiler])
-_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
-
-if test -n "$compiler"; then
-  :
-  _LT_CONFIG($1)
-fi
-
-GCC=$lt_save_GCC
-AC_LANG_RESTORE
-CC="$lt_save_CC"
-])# _LT_LANG_RC_CONFIG
-
-
-# LT_PROG_GCJ
-# -----------
-AC_DEFUN([LT_PROG_GCJ],
-[m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ],
-  [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ],
-    [AC_CHECK_TOOL(GCJ, gcj,)
-      test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2"
-      AC_SUBST(GCJFLAGS)])])[]dnl
-])
-
-# Old name:
-AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([LT_AC_PROG_GCJ], [])
-
-
-# LT_PROG_RC
-# ----------
-AC_DEFUN([LT_PROG_RC],
-[AC_CHECK_TOOL(RC, windres,)
-])
-
-# Old name:
-AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([LT_AC_PROG_RC], [])
-
-
-# _LT_DECL_EGREP
-# --------------
-# If we don't have a new enough Autoconf to choose the best grep
-# available, choose the one first in the user's PATH.
-m4_defun([_LT_DECL_EGREP],
-[AC_REQUIRE([AC_PROG_EGREP])dnl
-AC_REQUIRE([AC_PROG_FGREP])dnl
-test -z "$GREP" && GREP=grep
-_LT_DECL([], [GREP], [1], [A grep program that handles long lines])
-_LT_DECL([], [EGREP], [1], [An ERE matcher])
-_LT_DECL([], [FGREP], [1], [A literal string matcher])
-dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too
-AC_SUBST([GREP])
-])
-
-
-# _LT_DECL_OBJDUMP
-# --------------
-# If we don't have a new enough Autoconf to choose the best objdump
-# available, choose the one first in the user's PATH.
-m4_defun([_LT_DECL_OBJDUMP],
-[AC_CHECK_TOOL(OBJDUMP, objdump, false)
-test -z "$OBJDUMP" && OBJDUMP=objdump
-_LT_DECL([], [OBJDUMP], [1], [An object symbol dumper])
-AC_SUBST([OBJDUMP])
-])
-
-
-# _LT_DECL_SED
-# ------------
-# Check for a fully-functional sed program, that truncates
-# as few characters as possible.  Prefer GNU sed if found.
-m4_defun([_LT_DECL_SED],
-[AC_PROG_SED
-test -z "$SED" && SED=sed
-Xsed="$SED -e 1s/^X//"
-_LT_DECL([], [SED], [1], [A sed program that does not truncate output])
-_LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"],
-    [Sed that helps us avoid accidentally triggering echo(1) options like -n])
-])# _LT_DECL_SED
-
-m4_ifndef([AC_PROG_SED], [
-############################################################
-# NOTE: This macro has been submitted for inclusion into   #
-#  GNU Autoconf as AC_PROG_SED.  When it is available in   #
-#  a released version of Autoconf we should remove this    #
-#  macro and use it instead.                               #
-############################################################
-
-m4_defun([AC_PROG_SED],
-[AC_MSG_CHECKING([for a sed that does not truncate output])
-AC_CACHE_VAL(lt_cv_path_SED,
-[# Loop through the user's path and test for sed and gsed.
-# Then use that list of sed's as ones to test for truncation.
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for lt_ac_prog in sed gsed; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
-        lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
-      fi
-    done
-  done
-done
-IFS=$as_save_IFS
-lt_ac_max=0
-lt_ac_count=0
-# Add /usr/xpg4/bin/sed as it is typically found on Solaris
-# along with /bin/sed that truncates output.
-for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
-  test ! -f $lt_ac_sed && continue
-  cat /dev/null > conftest.in
-  lt_ac_count=0
-  echo $ECHO_N "0123456789$ECHO_C" >conftest.in
-  # Check for GNU sed and select it if it is found.
-  if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
-    lt_cv_path_SED=$lt_ac_sed
-    break
-  fi
-  while true; do
-    cat conftest.in conftest.in >conftest.tmp
-    mv conftest.tmp conftest.in
-    cp conftest.in conftest.nl
-    echo >>conftest.nl
-    $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
-    cmp -s conftest.out conftest.nl || break
-    # 10000 chars as input seems more than enough
-    test $lt_ac_count -gt 10 && break
-    lt_ac_count=`expr $lt_ac_count + 1`
-    if test $lt_ac_count -gt $lt_ac_max; then
-      lt_ac_max=$lt_ac_count
-      lt_cv_path_SED=$lt_ac_sed
-    fi
-  done
-done
-])
-SED=$lt_cv_path_SED
-AC_SUBST([SED])
-AC_MSG_RESULT([$SED])
-])#AC_PROG_SED
-])#m4_ifndef
-
-# Old name:
-AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([LT_AC_PROG_SED], [])
-
-
-# _LT_CHECK_SHELL_FEATURES
-# ------------------------
-# Find out whether the shell is Bourne or XSI compatible,
-# or has some other useful features.
-m4_defun([_LT_CHECK_SHELL_FEATURES],
-[AC_MSG_CHECKING([whether the shell understands some XSI constructs])
-# Try some XSI features
-xsi_shell=no
-( _lt_dummy="a/b/c"
-  test "${_lt_dummy##*/},${_lt_dummy%/*},"${_lt_dummy%"$_lt_dummy"}, \
-      = c,a/b,, \
-    && eval 'test $(( 1 + 1 )) -eq 2 \
-    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
-  && xsi_shell=yes
-AC_MSG_RESULT([$xsi_shell])
-_LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell'])
-
-AC_MSG_CHECKING([whether the shell understands "+="])
-lt_shell_append=no
-( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \
-    >/dev/null 2>&1 \
-  && lt_shell_append=yes
-AC_MSG_RESULT([$lt_shell_append])
-_LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append'])
-
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
-  lt_unset=unset
-else
-  lt_unset=false
-fi
-_LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl
-
-# test EBCDIC or ASCII
-case `echo X|tr X '\101'` in
- A) # ASCII based system
-    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
-  lt_SP2NL='tr \040 \012'
-  lt_NL2SP='tr \015\012 \040\040'
-  ;;
- *) # EBCDIC based system
-  lt_SP2NL='tr \100 \n'
-  lt_NL2SP='tr \r\n \100\100'
-  ;;
-esac
-_LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl
-_LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl
-])# _LT_CHECK_SHELL_FEATURES
-
-
-# _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
-    ;;
-  *) # 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
-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
-    ;;
-  *)
-    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
-])
Index: sm/trunk/m4/ltoptions.m4
===================================================================
--- /issm/trunk/m4/ltoptions.m4	(revision 13394)
+++ 	(revision )
@@ -1,368 +1,0 @@
-# Helper functions for option handling.                    -*- Autoconf -*-
-#
-#   Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
-#   Written by Gary V. Vaughan, 2004
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-# serial 6 ltoptions.m4
-
-# This is to help aclocal find these macros, as it can't see m4_define.
-AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])])
-
-
-# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME)
-# ------------------------------------------
-m4_define([_LT_MANGLE_OPTION],
-[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])])
-
-
-# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME)
-# ---------------------------------------
-# Set option OPTION-NAME for macro MACRO-NAME, and if there is a
-# matching handler defined, dispatch to it.  Other OPTION-NAMEs are
-# saved as a flag.
-m4_define([_LT_SET_OPTION],
-[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl
-m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]),
-        _LT_MANGLE_DEFUN([$1], [$2]),
-    [m4_warning([Unknown $1 option `$2'])])[]dnl
-])
-
-
-# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET])
-# ------------------------------------------------------------
-# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
-m4_define([_LT_IF_OPTION],
-[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])])
-
-
-# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET)
-# -------------------------------------------------------
-# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME
-# are set.
-m4_define([_LT_UNLESS_OPTIONS],
-[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
-	    [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option),
-		      [m4_define([$0_found])])])[]dnl
-m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3
-])[]dnl
-])
-
-
-# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST)
-# ----------------------------------------
-# OPTION-LIST is a space-separated list of Libtool options associated
-# with MACRO-NAME.  If any OPTION has a matching handler declared with
-# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about
-# the unknown option and exit.
-m4_defun([_LT_SET_OPTIONS],
-[# Set options
-m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
-    [_LT_SET_OPTION([$1], _LT_Option)])
-
-m4_if([$1],[LT_INIT],[
-  dnl
-  dnl Simply set some default values (i.e off) if boolean options were not
-  dnl specified:
-  _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no
-  ])
-  _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no
-  ])
-  dnl
-  dnl If no reference was made to various pairs of opposing options, then
-  dnl we run the default mode handler for the pair.  For example, if neither
-  dnl `shared' nor `disable-shared' was passed, we enable building of shared
-  dnl archives by default:
-  _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED])
-  _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC])
-  _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC])
-  _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install],
-  		   [_LT_ENABLE_FAST_INSTALL])
-  ])
-])# _LT_SET_OPTIONS
-
-
-## --------------------------------- ##
-## Macros to handle LT_INIT options. ##
-## --------------------------------- ##
-
-# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME)
-# -----------------------------------------
-m4_define([_LT_MANGLE_DEFUN],
-[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])])
-
-
-# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE)
-# -----------------------------------------------
-m4_define([LT_OPTION_DEFINE],
-[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl
-])# LT_OPTION_DEFINE
-
-
-# dlopen
-# ------
-LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes
-])
-
-AU_DEFUN([AC_LIBTOOL_DLOPEN],
-[_LT_SET_OPTION([LT_INIT], [dlopen])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you
-put the `dlopen' option into LT_INIT's first parameter.])
-])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], [])
-
-
-# win32-dll
-# ---------
-# Declare package support for building win32 dll's.
-LT_OPTION_DEFINE([LT_INIT], [win32-dll],
-[enable_win32_dll=yes
-
-case $host in
-*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-cegcc*)
-  AC_CHECK_TOOL(AS, as, false)
-  AC_CHECK_TOOL(DLLTOOL, dlltool, false)
-  AC_CHECK_TOOL(OBJDUMP, objdump, false)
-  ;;
-esac
-
-test -z "$AS" && AS=as
-_LT_DECL([], [AS],      [0], [Assembler program])dnl
-
-test -z "$DLLTOOL" && DLLTOOL=dlltool
-_LT_DECL([], [DLLTOOL], [0], [DLL creation program])dnl
-
-test -z "$OBJDUMP" && OBJDUMP=objdump
-_LT_DECL([], [OBJDUMP], [0], [Object dumper program])dnl
-])# win32-dll
-
-AU_DEFUN([AC_LIBTOOL_WIN32_DLL],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-_LT_SET_OPTION([LT_INIT], [win32-dll])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you
-put the `win32-dll' option into LT_INIT's first parameter.])
-])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], [])
-
-
-# _LT_ENABLE_SHARED([DEFAULT])
-# ----------------------------
-# implement the --enable-shared flag, and supports the `shared' and
-# `disable-shared' LT_INIT options.
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
-m4_define([_LT_ENABLE_SHARED],
-[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl
-AC_ARG_ENABLE([shared],
-    [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@],
-	[build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])],
-    [p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_shared=yes ;;
-    no) enable_shared=no ;;
-    *)
-      enable_shared=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_shared=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac],
-    [enable_shared=]_LT_ENABLE_SHARED_DEFAULT)
-
-    _LT_DECL([build_libtool_libs], [enable_shared], [0],
-	[Whether or not to build shared libraries])
-])# _LT_ENABLE_SHARED
-
-LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])])
-LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])])
-
-# Old names:
-AC_DEFUN([AC_ENABLE_SHARED],
-[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared])
-])
-
-AC_DEFUN([AC_DISABLE_SHARED],
-[_LT_SET_OPTION([LT_INIT], [disable-shared])
-])
-
-AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)])
-AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AM_ENABLE_SHARED], [])
-dnl AC_DEFUN([AM_DISABLE_SHARED], [])
-
-
-
-# _LT_ENABLE_STATIC([DEFAULT])
-# ----------------------------
-# implement the --enable-static flag, and support the `static' and
-# `disable-static' LT_INIT options.
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
-m4_define([_LT_ENABLE_STATIC],
-[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl
-AC_ARG_ENABLE([static],
-    [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@],
-	[build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])],
-    [p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_static=yes ;;
-    no) enable_static=no ;;
-    *)
-     enable_static=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_static=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac],
-    [enable_static=]_LT_ENABLE_STATIC_DEFAULT)
-
-    _LT_DECL([build_old_libs], [enable_static], [0],
-	[Whether or not to build static libraries])
-])# _LT_ENABLE_STATIC
-
-LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])])
-LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])])
-
-# Old names:
-AC_DEFUN([AC_ENABLE_STATIC],
-[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static])
-])
-
-AC_DEFUN([AC_DISABLE_STATIC],
-[_LT_SET_OPTION([LT_INIT], [disable-static])
-])
-
-AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)])
-AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AM_ENABLE_STATIC], [])
-dnl AC_DEFUN([AM_DISABLE_STATIC], [])
-
-
-
-# _LT_ENABLE_FAST_INSTALL([DEFAULT])
-# ----------------------------------
-# implement the --enable-fast-install flag, and support the `fast-install'
-# and `disable-fast-install' LT_INIT options.
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
-m4_define([_LT_ENABLE_FAST_INSTALL],
-[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl
-AC_ARG_ENABLE([fast-install],
-    [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@],
-    [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])],
-    [p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_fast_install=yes ;;
-    no) enable_fast_install=no ;;
-    *)
-      enable_fast_install=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_fast_install=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac],
-    [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT)
-
-_LT_DECL([fast_install], [enable_fast_install], [0],
-	 [Whether or not to optimize for fast installation])dnl
-])# _LT_ENABLE_FAST_INSTALL
-
-LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])])
-LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])])
-
-# Old names:
-AU_DEFUN([AC_ENABLE_FAST_INSTALL],
-[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you put
-the `fast-install' option into LT_INIT's first parameter.])
-])
-
-AU_DEFUN([AC_DISABLE_FAST_INSTALL],
-[_LT_SET_OPTION([LT_INIT], [disable-fast-install])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you put
-the `disable-fast-install' option into LT_INIT's first parameter.])
-])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], [])
-dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], [])
-
-
-# _LT_WITH_PIC([MODE])
-# --------------------
-# implement the --with-pic flag, and support the `pic-only' and `no-pic'
-# LT_INIT options.
-# MODE is either `yes' or `no'.  If omitted, it defaults to `both'.
-m4_define([_LT_WITH_PIC],
-[AC_ARG_WITH([pic],
-    [AS_HELP_STRING([--with-pic],
-	[try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
-    [pic_mode="$withval"],
-    [pic_mode=default])
-
-test -z "$pic_mode" && pic_mode=m4_default([$1], [default])
-
-_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl
-])# _LT_WITH_PIC
-
-LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])])
-LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])])
-
-# Old name:
-AU_DEFUN([AC_LIBTOOL_PICMODE],
-[_LT_SET_OPTION([LT_INIT], [pic-only])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you
-put the `pic-only' option into LT_INIT's first parameter.])
-])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_PICMODE], [])
-
-## ----------------- ##
-## LTDL_INIT Options ##
-## ----------------- ##
-
-m4_define([_LTDL_MODE], [])
-LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive],
-		 [m4_define([_LTDL_MODE], [nonrecursive])])
-LT_OPTION_DEFINE([LTDL_INIT], [recursive],
-		 [m4_define([_LTDL_MODE], [recursive])])
-LT_OPTION_DEFINE([LTDL_INIT], [subproject],
-		 [m4_define([_LTDL_MODE], [subproject])])
-
-m4_define([_LTDL_TYPE], [])
-LT_OPTION_DEFINE([LTDL_INIT], [installable],
-		 [m4_define([_LTDL_TYPE], [installable])])
-LT_OPTION_DEFINE([LTDL_INIT], [convenience],
-		 [m4_define([_LTDL_TYPE], [convenience])])
Index: sm/trunk/m4/ltsugar.m4
===================================================================
--- /issm/trunk/m4/ltsugar.m4	(revision 13394)
+++ 	(revision )
@@ -1,123 +1,0 @@
-# ltsugar.m4 -- libtool m4 base layer.                         -*-Autoconf-*-
-#
-# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
-# Written by Gary V. Vaughan, 2004
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-# serial 6 ltsugar.m4
-
-# This is to help aclocal find these macros, as it can't see m4_define.
-AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])])
-
-
-# lt_join(SEP, ARG1, [ARG2...])
-# -----------------------------
-# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their
-# associated separator.
-# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier
-# versions in m4sugar had bugs.
-m4_define([lt_join],
-[m4_if([$#], [1], [],
-       [$#], [2], [[$2]],
-       [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])])
-m4_define([_lt_join],
-[m4_if([$#$2], [2], [],
-       [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])])
-
-
-# lt_car(LIST)
-# lt_cdr(LIST)
-# ------------
-# Manipulate m4 lists.
-# These macros are necessary as long as will still need to support
-# Autoconf-2.59 which quotes differently.
-m4_define([lt_car], [[$1]])
-m4_define([lt_cdr],
-[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])],
-       [$#], 1, [],
-       [m4_dquote(m4_shift($@))])])
-m4_define([lt_unquote], $1)
-
-
-# lt_append(MACRO-NAME, STRING, [SEPARATOR])
-# ------------------------------------------
-# Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'.
-# Note that neither SEPARATOR nor STRING are expanded; they are appended
-# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked).
-# No SEPARATOR is output if MACRO-NAME was previously undefined (different
-# than defined and empty).
-#
-# This macro is needed until we can rely on Autoconf 2.62, since earlier
-# versions of m4sugar mistakenly expanded SEPARATOR but not STRING.
-m4_define([lt_append],
-[m4_define([$1],
-	   m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])])
-
-
-
-# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...])
-# ----------------------------------------------------------
-# Produce a SEP delimited list of all paired combinations of elements of
-# PREFIX-LIST with SUFFIX1 through SUFFIXn.  Each element of the list
-# has the form PREFIXmINFIXSUFFIXn.
-# Needed until we can rely on m4_combine added in Autoconf 2.62.
-m4_define([lt_combine],
-[m4_if(m4_eval([$# > 3]), [1],
-       [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl
-[[m4_foreach([_Lt_prefix], [$2],
-	     [m4_foreach([_Lt_suffix],
-		]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[,
-	[_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])])
-
-
-# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ])
-# -----------------------------------------------------------------------
-# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited
-# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ.
-m4_define([lt_if_append_uniq],
-[m4_ifdef([$1],
-	  [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1],
-		 [lt_append([$1], [$2], [$3])$4],
-		 [$5])],
-	  [lt_append([$1], [$2], [$3])$4])])
-
-
-# lt_dict_add(DICT, KEY, VALUE)
-# -----------------------------
-m4_define([lt_dict_add],
-[m4_define([$1($2)], [$3])])
-
-
-# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE)
-# --------------------------------------------
-m4_define([lt_dict_add_subkey],
-[m4_define([$1($2:$3)], [$4])])
-
-
-# lt_dict_fetch(DICT, KEY, [SUBKEY])
-# ----------------------------------
-m4_define([lt_dict_fetch],
-[m4_ifval([$3],
-	m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]),
-    m4_ifdef([$1($2)], [m4_defn([$1($2)])]))])
-
-
-# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE])
-# -----------------------------------------------------------------
-m4_define([lt_if_dict_fetch],
-[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4],
-	[$5],
-    [$6])])
-
-
-# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...])
-# --------------------------------------------------------------
-m4_define([lt_dict_filter],
-[m4_if([$5], [], [],
-  [lt_join(m4_quote(m4_default([$4], [[, ]])),
-           lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]),
-		      [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl
-])
Index: sm/trunk/m4/ltversion.m4
===================================================================
--- /issm/trunk/m4/ltversion.m4	(revision 13394)
+++ 	(revision )
@@ -1,23 +1,0 @@
-# ltversion.m4 -- version numbers			-*- Autoconf -*-
-#
-#   Copyright (C) 2004 Free Software Foundation, Inc.
-#   Written by Scott James Remnant, 2004
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-# Generated from ltversion.in.
-
-# serial 3017 ltversion.m4
-# This file is part of GNU Libtool
-
-m4_define([LT_PACKAGE_VERSION], [2.2.6b])
-m4_define([LT_PACKAGE_REVISION], [1.3017])
-
-AC_DEFUN([LTVERSION_VERSION],
-[macro_version='2.2.6b'
-macro_revision='1.3017'
-_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
-_LT_DECL(, macro_revision, 0)
-])
Index: sm/trunk/m4/lt~obsolete.m4
===================================================================
--- /issm/trunk/m4/lt~obsolete.m4	(revision 13394)
+++ 	(revision )
@@ -1,92 +1,0 @@
-# lt~obsolete.m4 -- aclocal satisfying obsolete definitions.    -*-Autoconf-*-
-#
-#   Copyright (C) 2004, 2005, 2007 Free Software Foundation, Inc.
-#   Written by Scott James Remnant, 2004.
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-# serial 4 lt~obsolete.m4
-
-# These exist entirely to fool aclocal when bootstrapping libtool.
-#
-# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN)
-# which have later been changed to m4_define as they aren't part of the
-# exported API, or moved to Autoconf or Automake where they belong.
-#
-# The trouble is, aclocal is a bit thick.  It'll see the old AC_DEFUN
-# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us
-# using a macro with the same name in our local m4/libtool.m4 it'll
-# pull the old libtool.m4 in (it doesn't see our shiny new m4_define
-# and doesn't know about Autoconf macros at all.)
-#
-# So we provide this file, which has a silly filename so it's always
-# included after everything else.  This provides aclocal with the
-# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything
-# because those macros already exist, or will be overwritten later.
-# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. 
-#
-# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here.
-# Yes, that means every name once taken will need to remain here until
-# we give up compatibility with versions before 1.7, at which point
-# we need to keep only those names which we still refer to.
-
-# This is to help aclocal find these macros, as it can't see m4_define.
-AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])])
-
-m4_ifndef([AC_LIBTOOL_LINKER_OPTION],	[AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])])
-m4_ifndef([AC_PROG_EGREP],		[AC_DEFUN([AC_PROG_EGREP])])
-m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])])
-m4_ifndef([_LT_AC_SHELL_INIT],		[AC_DEFUN([_LT_AC_SHELL_INIT])])
-m4_ifndef([_LT_AC_SYS_LIBPATH_AIX],	[AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])])
-m4_ifndef([_LT_PROG_LTMAIN],		[AC_DEFUN([_LT_PROG_LTMAIN])])
-m4_ifndef([_LT_AC_TAGVAR],		[AC_DEFUN([_LT_AC_TAGVAR])])
-m4_ifndef([AC_LTDL_ENABLE_INSTALL],	[AC_DEFUN([AC_LTDL_ENABLE_INSTALL])])
-m4_ifndef([AC_LTDL_PREOPEN],		[AC_DEFUN([AC_LTDL_PREOPEN])])
-m4_ifndef([_LT_AC_SYS_COMPILER],	[AC_DEFUN([_LT_AC_SYS_COMPILER])])
-m4_ifndef([_LT_AC_LOCK],		[AC_DEFUN([_LT_AC_LOCK])])
-m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE],	[AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])])
-m4_ifndef([_LT_AC_TRY_DLOPEN_SELF],	[AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])])
-m4_ifndef([AC_LIBTOOL_PROG_CC_C_O],	[AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])])
-m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])])
-m4_ifndef([AC_LIBTOOL_OBJDIR],		[AC_DEFUN([AC_LIBTOOL_OBJDIR])])
-m4_ifndef([AC_LTDL_OBJDIR],		[AC_DEFUN([AC_LTDL_OBJDIR])])
-m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])])
-m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP],	[AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])])
-m4_ifndef([AC_PATH_MAGIC],		[AC_DEFUN([AC_PATH_MAGIC])])
-m4_ifndef([AC_PROG_LD_GNU],		[AC_DEFUN([AC_PROG_LD_GNU])])
-m4_ifndef([AC_PROG_LD_RELOAD_FLAG],	[AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])])
-m4_ifndef([AC_DEPLIBS_CHECK_METHOD],	[AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])])
-m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])])
-m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])])
-m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])])
-m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS],	[AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])])
-m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP],	[AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])])
-m4_ifndef([LT_AC_PROG_EGREP],		[AC_DEFUN([LT_AC_PROG_EGREP])])
-m4_ifndef([LT_AC_PROG_SED],		[AC_DEFUN([LT_AC_PROG_SED])])
-m4_ifndef([_LT_CC_BASENAME],		[AC_DEFUN([_LT_CC_BASENAME])])
-m4_ifndef([_LT_COMPILER_BOILERPLATE],	[AC_DEFUN([_LT_COMPILER_BOILERPLATE])])
-m4_ifndef([_LT_LINKER_BOILERPLATE],	[AC_DEFUN([_LT_LINKER_BOILERPLATE])])
-m4_ifndef([_AC_PROG_LIBTOOL],		[AC_DEFUN([_AC_PROG_LIBTOOL])])
-m4_ifndef([AC_LIBTOOL_SETUP],		[AC_DEFUN([AC_LIBTOOL_SETUP])])
-m4_ifndef([_LT_AC_CHECK_DLFCN],		[AC_DEFUN([_LT_AC_CHECK_DLFCN])])
-m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER],	[AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])])
-m4_ifndef([_LT_AC_TAGCONFIG],		[AC_DEFUN([_LT_AC_TAGCONFIG])])
-m4_ifndef([AC_DISABLE_FAST_INSTALL],	[AC_DEFUN([AC_DISABLE_FAST_INSTALL])])
-m4_ifndef([_LT_AC_LANG_CXX],		[AC_DEFUN([_LT_AC_LANG_CXX])])
-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])])
-m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])])
-m4_ifndef([_LT_AC_LANG_CXX_CONFIG],	[AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])])
-m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])])
-m4_ifndef([_LT_AC_LANG_F77_CONFIG],	[AC_DEFUN([_LT_AC_LANG_F77_CONFIG])])
-m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])])
-m4_ifndef([_LT_AC_LANG_GCJ_CONFIG],	[AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])])
-m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])])
-m4_ifndef([_LT_AC_LANG_RC_CONFIG],	[AC_DEFUN([_LT_AC_LANG_RC_CONFIG])])
-m4_ifndef([AC_LIBTOOL_CONFIG],		[AC_DEFUN([AC_LIBTOOL_CONFIG])])
-m4_ifndef([_LT_AC_FILE_LTDLL_C],	[AC_DEFUN([_LT_AC_FILE_LTDLL_C])])
Index: /issm/trunk/scripts/DownloadExternalPackage.py
===================================================================
--- /issm/trunk/scripts/DownloadExternalPackage.py	(revision 13394)
+++ /issm/trunk/scripts/DownloadExternalPackage.py	(revision 13395)
@@ -1,37 +1,135 @@
 #!/usr/bin/env python
 # -*- coding: ISO-8859-1 -*-
+#
+# TODO: Improve upon extension recognition by checking for mismatches in found targets
+# and specified local file.
+#
 
-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];
-localFile=sys.argv[2]
+    def __init__(self, pattern):
+        HTMLParser.__init__(self)
+        self.matcher = re.compile(pattern) 
+        self.targets = []
 
-#Remove file if it already exists
-if os.path.exists(localFile):
-	print "File "+ localFile +" already exists and will not be downloaded..."
-	sys.exit()
+    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
 
-#Try to download from url
-httpfail=-1
-try:
-	print "Fetching %s" % localFile
-	urllib.urlretrieve(url,localFile)
-	httpfail=0
-except Exception, e:
-	httpfail=1
+# Separates the URL into a directory and the file or pattern based on the
+# last appearance of '/'.
+if len(sys.argv) > 1:
+    pivot = sys.argv[1].rfind("/")
+    url = (sys.argv[1])[:pivot]
+    pivot += 1
+    find = (sys.argv[1])[pivot:]
+else:
+    print "******************************************************************************************************************************"
+    print "* Invalid input!                                                                                                             *"
+    print "*                                                                                                                            *"
+    print "* Try: 'DownloadExternalPackage.py url [localFile]'                                                                          *"
+    print "*                                                                                                                            *"
+    print "* Where 'URL' is the URL with an explicit package name or the URL followed by the truncated package name. And 'localFile' is *"
+    print "* the file name (including extension) that you would like to save as.                                                        *"
+    print "*                                                                                                                            *"
+    print "* Examples:                                                                                                                  *" 
+    print "*                                                                                                                            *"
+    print "* DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-2.3.2-p3.tar.gz' 'petsc-2.3.2-p3.tar.gz' *"
+    print "*                                                                                                                            *"
+    print "*     This is the old style and the safest way to download a package.                                                        *"
+    print "*                                                                                                                            *"
+    print "* DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libtool' 'libtool.tar.gz'                      *"
+    print "*                                                                                                                            *"
+    print "*     This is the new style. For packages like 'Libtool', which we never expect to be using multiple versions, this will     *"
+    print "*     download the most recent version and save it as the generic 'libtool.tar.gz'.                                          *"
+    print "*                                                                                                                            *"
+    print "* DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gsl-1.' 'gsl-1.15.tar.gz'                      *"
+    print "*                                                                                                                            *"
+    print "*     This is the new style. This is a demonstration of how this script can be used to disambiguate a package name if there  *"
+    print "*     are more than once package matching 'gsl-'.                                                                            *"
+    print "*                                                                                                                            *"
+    print "* DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/libtool'                                       *"
+    print "*                                                                                                                            *"
+    print "*     This is the new style. This will download a package with 'libtool' as a prefix and save it as its canonical name.      *"
+    print "*                                                                                                                            *"
+    print "*                                                                                                                            *"
+    print "******************************************************************************************************************************"
 
-#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(sys.argv) > 2:
+    localFile=sys.argv[2]
+    print "Downloaded file will saved as: " + localFile
+else:
+    localFile = None
+    print "Downloaded file will saved with the same file name."
+
+
+print "Looking for " + find
+
+# As an extra precaution, if no extension is given for a particular package
+# such as '.../libtool', then ensure that files found are of appropriate
+# file extensions. 
+#
+# WARNING: The external packages directory includes executable binaries with
+# '.exe' extensions. As such, '.exe' is an acceptable suffix, but this is 
+# inherently dangerous since this script can be used to download from any
+# valid website. Furthermore, if an individual attempts a "man-in-the-middle"  
+# attack, then the user would be capable of downloading executables from 
+# an untrusted source.
+pattern = find + "[\w.-]*(\.tar\.gz|tar\.gz2|tgz|zip|exe)?"
+parser = MyHTMLParser(pattern)
+
+# Creates a 'FancyURL' which allows the script to fail gracefully by catching
+# HTTP error codes 30X and several 40X(where 'X' is a natural number).
+urlObject = FancyURLopener()
+obj = urlObject.open(url)
+parser.feed(obj.read())
+
+# If a file pattern was used to describe the file that should be downloaded,
+# then there is the potential for multiple file matches. Currently, the script
+# will detect this ambiguity and print out all the matches, while informing 
+# the user that he must refine his search.
+#
+# TODO: Prompt the user to select from a list his/her preferred target.
+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:
+    print "Found: " + parser.targets[0]
+    url += "/" + parser.targets[0]
+
+    if localFile is None:
+        if os.path.exists(parser.targets[0]): 
+            print "File " + parser.targets[0] + " already exists and will not be downloaded..."
+        else:
+            urllib.urlretrieve(url, parser.targets[0])
+            print "File saved as: " + parser.targets[0]
+    else:
+        if os.path.exists(localFile): 
+            print "File "+ localFile +" already exists and will not be downloaded..."
+        else:
+            if parser.targets[0] == localFile:
+                print "File found and destination match."
+            elif parser.matcher.match(localFile) != "None":
+                print "File found matches destination pattern."
+            else:
+                print "WARNING: the file found \'" + parser.targets[0] + "\' does not match \'" + localFile + "\'"
+                print "Ensure the downloaded version is suitable."
+
+            urllib.urlretrieve(url, localFile)
+            print "File saved as: " + localFile
+
+else:
+    print "No matches found!"
+
+obj.close()
Index: /issm/trunk/scripts/automakererun.sh
===================================================================
--- /issm/trunk/scripts/automakererun.sh	(revision 13394)
+++ /issm/trunk/scripts/automakererun.sh	(revision 13395)
@@ -9,3 +9,3 @@
 
 cd $ISSM_DIR
-autoreconf -iv -I m4
+autoreconf -iv 
Index: /issm/trunk/scripts/historyISSM.m
===================================================================
--- /issm/trunk/scripts/historyISSM.m	(revision 13394)
+++ /issm/trunk/scripts/historyISSM.m	(revision 13395)
@@ -3,9 +3,6 @@
 md.mesh.numberofelements
 md=mesh(md,'DomainOutline.exp',5000);
-md=setmask(md,'','');
 md=setflowequation(md,'macayeal','all');
-md=setflowequation(md,'pattyn','all','stokes','all');
 md=solve(md,TransientSolutionEnum);
-md=solve(md,BalancedthicknessSolutionEnum);
 md=solve(md,DiagnosticSolutionEnum);
 md=loadresultsfromcluster(md);
Index: /issm/trunk/scripts/report.sh
===================================================================
--- /issm/trunk/scripts/report.sh	(revision 13394)
+++ /issm/trunk/scripts/report.sh	(revision 13395)
@@ -2,143 +2,177 @@
 #generate html report from info.log output file
 
-#----------------------------#
-# Initialize local variables #
-#----------------------------#
+#style
+#{{{
+TITLE_STYLE='width="700px" cellpadding="10"'
+TITLE_FONT='style="color:#6495ed; font-family:Arial, Verdana, Tahoma; font-weight: bold; font-size:25px;" align="center"'
+SECTION_STYLE='width="700px" cellpadding="5"'
+SECTION_FONT='style="color:#6495ed; font-family:Arial, Verdana, Tahoma; font-size:20px; font-weight: bold;" align="left"'
+TABLE_STYLE='width="680px" rules=none bgcolor="#ffffdd" border=1 bordercolor="#000000" cellpadding="3"'
+TABLE_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:14px; font-weight: normal;" align="left"'
+MATLAB_STYLE='width="700px" rules=none'
+MATLAB_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:12px; font-weight: normal;" align="left"'
+BODY_STYLE='width="700px"'
+BODY_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:14px;"'
+BODY_FONTC=$(echo $BODY_FONT | sed -e "s/style=\"/style=\"text-align:center; /g")
+BODY_FONTL=$(echo $BODY_FONT | sed -e "s/style=\"/style=\"text-align:left; /g")
+FOOTER_STYLE='width="700px"  cellpadding="10"'
+FOOTER_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:12px; font-weight: normal;" align="center"'
+#}}}
 
 #process info.log
-TODAY=`     cat info.log | grep "today"           | awk '{printf("%s %s",$2,$3);}'`
-USER=`      cat info.log | grep "user"            | awk '{print $2}'`
-HOST_NAME=` cat info.log | grep "host"            | awk '{print $2}'`
-OS=`        cat info.log | grep "OS"              | awk '{print $2}'`
-RELEASE=`   cat info.log | grep "release"         | awk '{print $2}'`
-EL_INSTALL=`cat info.log | grep "elapsed_install" | awk '{print $2}'`
-EL_RUN=`    cat info.log | grep "elapsed_run"     | awk '{print $2}'`
-EL_TOTAL=`  cat info.log | grep "elapsed_total"   | awk '{print $2}'`
-CRASH=`     cat info.log | grep "matlab_crash:"   | awk '{print $2}'`
-
-#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.log        | grep "PETSC" | sed -e "s/>/\&gt;/g" | sed -e "s/</\&lt;/g" > petscerror.log
-NUM_TOT=`wc -l matlab.log | awk '{print $1}'`
-NUM_ERR=`cat matlab.log | grep 'ERROR'   | grep -v "PETSC" | wc -l`
-NUM_SUC=`cat matlab.log | grep 'SUCCESS' | wc -l`
-NUM_FAI=`cat matlab.log | grep 'FAILURE' | wc -l`
-
-#style
-H1_STYLE='width="1000px" cellpadding="20"'
-H1_FONT='style="color:#6495ed; font-family:Arial, Verdana, Tahoma; font-weight: bold; font-size:35px;" align="center"'
-
-H2_STYLE='width="900px" cellpadding="20"'
-H2_FONT='style="color:#6495ed; font-family:Arial, Verdana, Tahoma; font-size:28px; font-weight: bold;" align="left"'
-
-TABLE_STYLE='width="800px" rules=none bgcolor="#ffffdd" border=1 bordercolor="#000000" cellpadding="3"'
-TABLE_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:14px; font-weight: normal;" align="left"'
-
-MATLAB_STYLE='width="1000px" rules=none'
-MATLAB_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:12px; font-weight: normal;" align="left"'
-
-BODY_STYLE='width="800px"'
-BODY_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:14px;"'
-
-FOOTER_STYLE='width="800px"  cellpadding="10"'
-FOOTER_FONT='style="color:#404040; font-family:Arial, Verdana, Tahoma; font-size:12px; font-weight: normal;" align="center"'
-
-#style 2
-BODY_FONTC=`echo $BODY_FONT | sed -e "s/style=\"/style=\"text-align:center; /g"`
-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
+#{{{
+if [ ! -f info.log ]; then
+	echo "File info.log not found!" >&2   # Error message to stderr.
+	exit 1
+fi 
+NRNAME=$(      cat info.log | grep "name:"           | awk '{$1=""}1')
+TODAY=$(       cat info.log | grep "today"           | awk '{printf("%s %s",$2,$3);}')
+USER=$(        cat info.log | grep "user"            | awk '{print $2}')
+HOST_NAME=$(   cat info.log | grep "host"            | awk '{print $2}')
+OS=$(          cat info.log | grep "OS"              | awk '{print $2}')
+RELEASE=$(     cat info.log | grep "release"         | awk '{print $2}')
+EL_INSTALL=$(  cat info.log | grep "elapsed_install" | awk '{print $2}')
+EL_TOTAL=$(    cat info.log | grep "elapsed_total"   | awk '{print $2}')
+IS_MATLAB=$(   cat info.log | grep "is_matlab"       | awk '{print $2}')
+IS_PYTHON=$(   cat info.log | grep "is_python"       | awk '{print $2}')
+EL_MATLAB=$(   cat info.log | grep "elapsed_matlab"  | awk '{print $2}')
+EL_PYTHON=$(   cat info.log | grep "elapsed_python"  | awk '{print $2}')
+CRASH_MATLAB=$(cat info.log | grep "matlab_crash:"   | awk '{print $2}')
+CRASH_PYTHON=$(cat info.log | grep "python_crash:"   | awk '{print $2}')
+
+#Did installation work?
+if [ $(ls -1 $ISSM_DIR/bin | wc -l) -le 20 ]; then
 	IS_INSTALL=0
 else
 	IS_INSTALL=1
 fi
-
-#-------------------#
-# build report.html #
-#-------------------#
-
-#first: summary
-cat << END > summary.html
+#}}}
+
+#1. summary table 
+#{{{
+rm report.html
+cat << END >> report.html
 <div align="center">
-<table $H1_STYLE><tr><td $H1_FONT>ISSM Nightly run report</td></tr></table>
+<table $TITLE_STYLE><tr><td $TITLE_FONT>$NRNAME</td></tr></table>
 
 <table $TABLE_STYLE>
 <tr> 
-<td $TABLE_FONT>host: $HOST_NAME</td>
+<td $TABLE_FONT>host: $HOST_NAME ($OS)</td>
 <td $TABLE_FONT>date: $TODAY</td>
 </tr>
 <tr>
-<td $TABLE_FONT>OS: $OS</td>
 <td $TABLE_FONT>user: $USER</td>
-</tr>
-<tr>
-<td $TABLE_FONT>status: STATUS</td>
 <td $TABLE_FONT>release: $RELEASE</td>
 </tr>
 <tr>
-<td $TABLE_FONT>number of successes: $NUM_SUC/$NUM_TOT
 <td $TABLE_FONT>total elapsed time: $EL_TOTAL</td>
-</tr>
-<tr>
-<td $TABLE_FONT>number of <a href="#ERROR">errors</a>: $NUM_ERR/$NUM_TOT
-
 <td $TABLE_FONT>installation elapsed time: $EL_INSTALL</td>
 </tr>
-<tr>
-<td $TABLE_FONT>number of <a href="#FAILURE">failures</a>: $NUM_FAI/$NUM_TOT
-<td $TABLE_FONT>execution elapsed time: $EL_RUN</td>
+</table>
+<br><hr width="700px">
+END
+# }}}
+
+#stop if did not install
+#{{{
+if [ $IS_INSTALL -eq 0 ]; then
+	cat << END >> report.html
+	<table $(echo $BODY_STYLE) style="border-collapse:collapse;">
+	<tr><td $BODY_FONTC>Status: <span style="color:#ff0000">Installation failed</span></td></tr>
+	</table>
+	<table $FOOTER_STYLE><tr><td $FOOTER_FONT><a href="http://issm.jpl.nasa.gov" title="ISSM website" target="_blank">ISSM</a> nightly run report</td></tr></table>
+	</div>
+END
+exit 0
+fi
+#}}}
+
+#2. matlab report
+if [ $IS_MATLAB -eq 1 ]; then
+#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_MATLAB_TOT=$(wc -l matlab.log | awk '{print $1}')
+NUM_MATLAB_ERR=$(cat matlab.log | grep 'ERROR'   | grep -v "PETSC" | wc -l)
+NUM_MATLAB_SUC=$(cat matlab.log | grep 'SUCCESS' | wc -l)
+NUM_MATLAB_FAI=$(cat matlab.log | grep 'FAILURE' | wc -l)
+#}}}
+#write report {{{
+cat << END >> report.html
+<table $SECTION_STYLE><tr><td $SECTION_FONT>Matlab tests</td></tr></table>
+<table $(echo $BODY_STYLE) style="border-collapse:collapse;">
+$(if [ $CRASH_MATLAB -eq 0 ]; then
+echo "<tr><td $BODY_FONTL>Status: <span style=\"color:#008000\">all test desks have been run</span></td></tr>"
+else
+	echo "<tr><td $BODY_FONTL>Status: <span style=\"color:#ff0000\">Matlab crashed</span></td></tr>"
+fi)
+<tr><td $BODY_FONTL>Total execution time: $EL_MATLAB</td></tr>
+<tr><td $BODY_FONTL>Number of successes: $NUM_MATLAB_SUC/$NUM_MATLAB_TOT</td></tr>
+<tr><td $BODY_FONTL>Number of errors: $NUM_MATLAB_ERR/$NUM_MATLAB_TOT</td></tr>
+<tr><td $BODY_FONTL>Number of failures: $NUM_MATLAB_FAI/$NUM_MATLAB_TOT</td></tr>
+</table>
+END
+#}}}
+fi
+
+#2. python report
+if [ $IS_PYTHON -eq 1 ]; then
+#Process python_log.log {{{
+cat python_log.log        | egrep 'ERROR|SUCCESS|FAILURE' | grep -v "PETSC" | sed -e "s/>/\&gt;/g" | sed -e "s/</\&lt;/g" > python.log
+cat python.log        | grep -v "SUCCESS" > python_short.log
+cat python_log.log        | grep "PETSC" | sed -e "s/>/\&gt;/g" | sed -e "s/</\&lt;/g" > petscerror.log
+NUM_PYTHON_TOT=$(wc -l python.log | awk '{print $1}')
+NUM_PYTHON_ERR=$(cat python.log | grep 'ERROR'   | grep -v "PETSC" | wc -l)
+NUM_PYTHON_SUC=$(cat python.log | grep 'SUCCESS' | wc -l)
+NUM_PYTHON_FAI=$(cat python.log | grep 'FAILURE' | wc -l)
+#}}}
+#write report {{{
+cat << END >> report.html
+<table $SECTION_STYLE><tr><td $SECTION_FONT>Python tests</td></tr></table>
+<table $(echo $BODY_STYLE) style="border-collapse:collapse;">
+$(if [ $CRASH_PYTHON -eq 0 ]; then
+	echo "<tr><td $BODY_FONTL>Status: <span style=\"color:#008000\">all test desks have been run</span></td></tr>"
+else
+	echo "<tr><td $BODY_FONTL>Status: <span style=\"color:#ff0000\">Python crashed</span></td></tr>"
+fi)
+<tr><td $BODY_FONTL>Total execution time: $EL_PYTHON</td></tr>
+<tr><td $BODY_FONTL>Number of successes: $NUM_PYTHON_SUC/$NUM_PYTHON_TOT</td></tr>
+<tr><td $BODY_FONTL>Number of errors: $NUM_PYTHON_ERR/$NUM_PYTHON_TOT</td></tr>
+<tr><td $BODY_FONTL>Number of failures: $NUM_PYTHON_FAI/$NUM_PYTHON_TOT</td></tr>
+</table>
+END
+#}}}
+fi
+
+#3. Matlab and python tables
+if [ $IS_MATLAB -eq 1 ]; then
+#Matlab{{{
+#display table ONLY if installation worked and there has been at leat one FAILURE or ERROR
+if [ $IS_INSTALL -eq 1 ] && [ $NUM_MATLAB_TOT -gt 1 ] && [ $NUM_MATLAB_SUC -ne $NUM_MATLAB_TOT ]
+then
+	cat << END >> report.html
+<table $SECTION_STYLE><tr><td $(echo $SECTION_FONT)>List of Matlab tests</td></tr></table>
+<table $BODY_STYLE style="border-collapse:collapse;">
+<tr> 
+<th $BODY_FONT>Result</th> 
+<th $BODY_FONT>Tolerance</th> 
+<th $BODY_FONT>Test id</th>  
+<th $BODY_FONT>Test name</th> 
+<th $BODY_FONT>Field checked</th>
 </tr>
-</table>
-<br><hr width="1000px">
-END
-
-#update status
-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
-	else
-		cat summary.html | sed -e "s/STATUS/<span style=\"color:#ff0000\">installation successful but Matlab crashed<\/span>/g" > summary2.html
-	fi
-else
-	cat summary.html | sed -e "s/STATUS/<span style=\"color:#ff0000\">installation failed<\/span>/g" > summary2.html
-fi
-mv summary2.html summary.html
-
-#report table
-if [ $IS_INSTALL -eq 1 ];
-then
-	cat << END > content.html
-<table $(echo $H2_STYLE)><tr><td $(echo $H2_FONT)>List of tests</td></tr></table>
-<table $(echo $BODY_STYLE) style="border-collapse:collapse;">
-<tr> 
-<th $(echo $BODY_FONT)>Result</th> 
-<th $(echo $BODY_FONT)>Tolerance</th> 
-<th $(echo $BODY_FONT)>Test id</th>  
-<th $(echo $BODY_FONT)>Test name</th> 
-<th $(echo $BODY_FONT)>Field checked</th>
-</tr>
-$(cat matlab.log | while read line
+$(cat matlab_short.log | while read line
   do
 	  echo "<tr>"
-
-	  #get status
 	  STATUS=`echo $line | awk '{print $1}'`
-
 	  #FAILURE
 	  if [ "$STATUS" = "FAILURE" ]
 	  then
-
 		  FONTC=$(echo "$BODY_FONTC bgcolor=#ffff00");
 		  FONTL=$(echo "$BODY_FONTL bgcolor=#ffff00");
 		  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
 		  if [ "$STATUS" = "SUCCESS" ]
@@ -146,18 +180,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
 	  )
@@ -165,13 +197,70 @@
 <br>
 END
-else
-	mktemp content.html
-fi
-
-#Matlab error report
-if [ -e matlaberror.log ]
+fi
+#}}}
+fi
+if [ $IS_PYTHON -eq 1 ]; then
+#python{{{
+#display table ONLY if installation worked and there has been at leat one FAILURE or ERROR
+if [ $IS_INSTALL -eq 1 ] && [ $NUM_PYTHON_TOT -gt 1 ] && [ $NUM_PYTHON_SUC -ne $NUM_PYTHON_TOT ]
 then
-	cat << END > matlaberror.html
-<table $H2_STYLE><tr><td $H2_FONT>Matlab errors</td></tr></table>
+	cat << END >> report.html
+	<table $(echo $SECTION_STYLE)><tr><td $(echo $SECTION_FONT)>List of Python tests</td></tr></table>
+	<table $(echo $BODY_STYLE) style="border-collapse:collapse;">
+	<tr> 
+	<th $BODY_FONT>Result</th> 
+	<th $BODY_FONT>Tolerance</th> 
+	<th $BODY_FONT>Test id</th>  
+	<th $BODY_FONT>Test name</th> 
+	<th $BODY_FONT>Field checked</th>
+	</tr>
+	$(cat matlab_short.log | while read line
+do
+	echo "<tr>"
+	STATUS=`echo $line | awk '{print $1}'`
+
+	#FAILURE
+	if [ "$STATUS" = "FAILURE" ]
+	then
+
+		FONTC=$(echo "$BODY_FONTC bgcolor=#ffff00");
+		FONTL=$(echo "$BODY_FONTL bgcolor=#ffff00");
+		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
+
+		#SUCCESS
+		if [ "$STATUS" = "SUCCESS" ]
+		then
+			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
+
+	fi
+	echo "</tr>"
+done
+)
+</table>
+<br>
+END
+fi
+#}}}
+fi
+
+#4. Error report
+if [ $IS_MATLAB -eq 1 ] && [ -s matlaberror.log ]; then
+#Matlab {{{
+cat << END >> report.html
+<table $SECTION_STYLE><tr><td $SECTION_FONT>Matlab errors</td></tr></table>
 <table $MATLAB_STYLE><tr><td $MATLAB_FONT>
 <pre style="
@@ -184,13 +273,10 @@
 </td></tr></table>
 END
-else
-	mktemp matlaberror.html
-fi
-
-#Matlab error report
-if test -s petscerror.log
-then
-	cat << END > petscerror.html
-<table $H2_STYLE><tr><td $H2_FONT>PETSc errors</td></tr></table>
+#}}}
+fi
+if [ -s petscerror.log ]; then
+	#PETSc{{{
+cat << END >> report.html
+<table $SECTION_STYLE><tr><td $SECTION_FONT>PETSc errors</td></tr></table>
 <table $MATLAB_STYLE><tr><td $MATLAB_FONT>
 <pre style="
@@ -203,16 +289,13 @@
 </td></tr></table>
 END
-else
-	mktemp petscerror.html
-fi
-
-#last footer
-cat << END > footer.html
+#}}}
+fi
+
+#last: footer
+#{{{
+cat << END >> report.html
 <br>
 <table $FOOTER_STYLE><tr><td $FOOTER_FONT><a href="http://issm.jpl.nasa.gov" title="ISSM website" target="_blank">ISSM</a> nightly run report</td></tr></table>
 </div>
 END
-
-#concatenate files
-cat summary.html content.html matlaberror.html petscerror.html footer.html > report.html
-rm  summary.html content.html footer.html matlaberror.html petscerror.html matlab.log
+#}}}
Index: /issm/trunk/src/Makefile.am
===================================================================
--- /issm/trunk/src/Makefile.am	(revision 13394)
+++ /issm/trunk/src/Makefile.am	(revision 13395)
@@ -1,2 +1,2 @@
-EXTRA_DIST =  perl  pro 
-SUBDIRS = c modules m  py
+EXTRA_DIST =  perl pro py
+SUBDIRS = c modules m
Index: /issm/trunk/src/ad/todo
===================================================================
--- /issm/trunk/src/ad/todo	(revision 13394)
+++ /issm/trunk/src/ad/todo	(revision 13395)
@@ -43,2 +43,16 @@
 
 Replace memcpy, realloc with x layers.  Replace all calls to malloc and free in the code.
+
+
+
+Questions: 
+set of active IssmDouble variables different from set of independent variables activated with <<=? 
+same thing dependent variables? 
+
+
+
+Bullet points: 
+- nightly run on with adolc compiled, running from test2000 on.  once a day.
+- run valgrind on new adolc or old adolc. send a text on how to run it. 
+- make gdb wrapper.
+- think about ModelProcessor setup. need to keep track, before we partition, on cpu 0, of the independent declarations. 
Index: /issm/trunk/src/c/Container/DataSet.cpp
===================================================================
--- /issm/trunk/src/c/Container/DataSet.cpp	(revision 13394)
+++ /issm/trunk/src/c/Container/DataSet.cpp	(revision 13395)
@@ -18,5 +18,5 @@
 
 #include "./DataSet.h"
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
@@ -133,5 +133,5 @@
 	vector<Object*>::iterator object;
 
-	if(this==NULL)_error2_("trying to echo a NULL dataset");
+	if(this==NULL)_error_("trying to echo a NULL dataset");
 
 	_pprintLine_("DataSet echo: " << objects.size() << " objects");
@@ -150,5 +150,5 @@
 	vector<Object*>::iterator object;
 
-	if(this==NULL)_error2_("trying to echo a NULL dataset");
+	if(this==NULL)_error_("trying to echo a NULL dataset");
 
 	_pprintLine_("DataSet echo: " << objects.size() << " objects");
@@ -194,9 +194,9 @@
 
 	_assert_(this);
-	if(!sorted)_error2_("trying to binary search on a non-sorted dataset!");
+	if(!sorted)_error_("trying to binary search on a non-sorted dataset!");
 
 	/*Carry out a binary search on the sorted_ids: */
 	if(!binary_search(&id_offset,eid, sorted_ids,objects.size())){
-		_error2_("could not find object with id " << eid << " in DataSet " << EnumToStringx(enum_type));
+		_error_("could not find object with id " << eid << " in DataSet " << EnumToStringx(enum_type));
 	}
 
@@ -259,6 +259,6 @@
 	/*Only sort if we are not already sorted: */
 	if(!sorted){
-		_error2_("not implemented yet!");
-	}
-}
-/*}}}*/
+		_error_("not implemented yet!");
+	}
+}
+/*}}}*/
Index: /issm/trunk/src/c/Container/DataSet.h
===================================================================
--- /issm/trunk/src/c/Container/DataSet.h	(revision 13394)
+++ /issm/trunk/src/c/Container/DataSet.h	(revision 13395)
@@ -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;
Index: /issm/trunk/src/c/Container/Elements.cpp
===================================================================
--- /issm/trunk/src/c/Container/Elements.cpp	(revision 13394)
+++ /issm/trunk/src/c/Container/Elements.cpp	(revision 13395)
@@ -166,4 +166,6 @@
 void Elements::ToResults(Results* results,Parameters* parameters){
 
+	int i;
+	
 	extern int my_rank;
 	extern int num_procs;
@@ -175,5 +177,5 @@
 	IssmDouble *resultstimes = NULL;
 	IssmDouble *vector_serial= NULL;
-	Vector*     vector       = NULL;
+	Vector<IssmDouble>*     vector       = NULL;
 	bool   io_gather;
 	bool   results_as_patches;
@@ -203,5 +205,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) _error2_("Cannot write results because there is no element??");
+			if(this->Size()==0) _error_("Cannot write results because there is no element??");
 			Element* element=(Element*)this->GetObjectByOffset(0);
 			element->ListResultsInfo(&resultsenums,&resultssizes,&resultstimes,&resultssteps,&numberofresults);
@@ -232,6 +234,6 @@
 			if(resultssizes[i]==P1Enum)      vectorsize=numberofvertices;
 			else if(resultssizes[i]==P0Enum) vectorsize=numberofelements;
-			else _error2_("Unkown result size: " << EnumToStringx(resultssizes[i]));
-			vector=new Vector(vectorsize);
+			else _error_("Unkown result size: " << EnumToStringx(resultssizes[i]));
+			vector=new Vector<IssmDouble>(vectorsize);
 
 			for(int j=0;j<this->Size();j++){
@@ -245,5 +247,12 @@
 			if(my_rank==0){
 				/*No need to add this vector for all cpus*/
-				results->AddObject(new DoubleVecExternalResult(results->Size()+1,resultsenums[i],vector_serial,vectorsize,resultssteps[i],resultstimes[i]));
+				#ifdef _HAVE_ADOLC_
+				IssmPDouble* vector_serial_passive=xNew<IssmPDouble>(vectorsize);
+				for(int k=0;k<vectorsize;k++)vector_serial_passive[k]=reCast<IssmPDouble>(vector_serial[k]);
+				results->AddObject(new GenericExternalResult<double*>(results->Size()+1,resultsenums[i],vector_serial_passive,vectorsize,1,resultssteps[i],resultstimes[i]));
+				xDelete<IssmPDouble>(vector_serial_passive);
+				#else
+				results->AddObject(new GenericExternalResult<double*>(results->Size()+1,resultsenums[i],vector_serial,vectorsize,1,resultssteps[i],resultstimes[i]));
+				#endif
 			}
 
@@ -262,7 +271,14 @@
 		/*create result object and add to results dataset:*/
 		if (patch->maxvertices && patch->maxnodes){
-			results->AddObject(new IntExternalResult(results->Size()+1,PatchVerticesEnum,patch->maxvertices,1,0));
-			results->AddObject(new IntExternalResult(results->Size()+1,PatchNodesEnum,   patch->maxnodes,1,0));
-			results->AddObject(new DoubleMatExternalResult(results->Size()+1,PatchEnum,  patch->values,patch->numrows,patch->numcols,1,0));
+			results->AddObject(new GenericExternalResult<int>(results->Size()+1,PatchVerticesEnum,patch->maxvertices,1,0));
+			results->AddObject(new GenericExternalResult<int>(results->Size()+1,PatchNodesEnum,   patch->maxnodes,1,0));
+			#ifdef _HAVE_ADOLC_
+			IssmPDouble* values_passive=xNew<IssmPDouble>(patch->numrows*patch->numcols);
+			for(int k=0;k<(patch->numrows*patch->numcols);k++)values_passive[k]=reCast<IssmPDouble>(patch->values[k]);
+			results->AddObject(new GenericExternalResult<double*>(results->Size()+1,PatchEnum,  values_passive,patch->numrows,patch->numcols,1,0));
+			xDelete<IssmPDouble>(values_passive);
+			#else
+			results->AddObject(new GenericExternalResult<double*>(results->Size()+1,PatchEnum,  patch->values,patch->numrows,patch->numcols,1,0));
+			#endif
 		}
 	}
Index: /issm/trunk/src/c/Container/Inputs.cpp
===================================================================
--- /issm/trunk/src/c/Container/Inputs.cpp	(revision 13394)
+++ /issm/trunk/src/c/Container/Inputs.cpp	(revision 13395)
@@ -57,5 +57,5 @@
 		/*we could not find an input with the correct enum type. No defaults values were provided, 
 		 * error out: */
-		_error2_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 	}
 
@@ -85,5 +85,5 @@
 		/*we could not find an input with the correct enum type. No defaults values were provided, 
 		 * error out: */
-		_error2_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 	}
 
@@ -113,5 +113,5 @@
 		/*we could not find an input with the correct enum type. No defaults values were provided, 
 		 * error out: */
-		_error2_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 	}
 
@@ -141,5 +141,5 @@
 		/*we could not find an input with the correct enum type. No defaults values were provided, 
 		 * error out: */
-		_error2_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
+		_error_("could not find input with enum type " << enum_type << " (" << EnumToStringx(enum_type) << ")");
 	}
 
@@ -213,5 +213,5 @@
 
 	/*some checks: */
-	if(!constrain_input) _error2_("input " << EnumToStringx(constrain_enum) << " could not be found!");
+	if(!constrain_input) _error_("input " << EnumToStringx(constrain_enum) << " could not be found!");
 
 	/*Apply ContrainMin: */
@@ -254,5 +254,5 @@
 	}
 	else{
-		_error2_("Input " << EnumToStringx(enumtype) << " not found");
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
 	}
 
@@ -275,5 +275,5 @@
 	}
 	else{
-		_error2_("Input " << EnumToStringx(enumtype) << " not found");
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
 	}
 
@@ -296,5 +296,5 @@
 	}
 	else{
-		_error2_("Input " << EnumToStringx(enumtype) << " not found");
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
 	}
 
@@ -317,5 +317,5 @@
 	}
 	else{
-		_error2_("Input " << EnumToStringx(enumtype) << " not found");
+		_error_("Input " << EnumToStringx(enumtype) << " not found");
 	}
 
@@ -369,5 +369,5 @@
 	/*Make a copy of the original input: */
 	original=(Input*)this->GetInput(original_enum);
-	if(!original)_error2_("could not find input with enum: " << EnumToStringx(original_enum)); 
+	if(!original)_error_("could not find input with enum: " << EnumToStringx(original_enum)); 
 	copy=(Input*)original->copy();
 
@@ -416,6 +416,6 @@
 
 	/*some checks: */
-	if(!xinput) _error2_("input " << EnumToStringx(MeshXEnum) << " could not be found!");
-	if(!yinput) _error2_("input " << EnumToStringx(MeshYEnum) << " could not be found!");
+	if(!xinput) _error_("input " << EnumToStringx(MeshXEnum) << " could not be found!");
+	if(!yinput) _error_("input " << EnumToStringx(MeshYEnum) << " could not be found!");
 
 	/*Apply AXPY: */
Index: /issm/trunk/src/c/Container/Observations.cpp
===================================================================
--- /issm/trunk/src/c/Container/Observations.cpp	(revision 13394)
+++ /issm/trunk/src/c/Container/Observations.cpp	(revision 13395)
@@ -19,4 +19,6 @@
 #include "./Observations.h"
 #include "../shared/shared.h"
+#include "../Container/Container.h"
+#include "../classes/classes.h"
 #include "../include/include.h"
 #include "../modules/modules.h"
@@ -34,13 +36,12 @@
 }
 /*}}}*/
-/*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){
+/*FUNCTION Observations::Observations(IssmPDouble* observations_list,IssmPDouble* x,IssmPDouble* y,int n,Options* options){{{*/
+Observations::Observations(IssmPDouble* observations_list,IssmPDouble* x,IssmPDouble* y,int n,Options* options){
 
 	/*Intermediaries*/
 	int          i,j,maxdepth,level,counter,index;
 	int          xi,yi;
-	IssmDouble       xmin,xmax,ymin,ymax;
-	IssmDouble       offset,minlength,minspacing,mintrimming,maxtrimming;
-	int         *indices     = NULL;
+	IssmPDouble  xmin,xmax,ymin,ymax;
+	IssmPDouble  offset,minlength,minspacing,mintrimming,maxtrimming;
 	Observation *observation = NULL;
 
@@ -59,15 +60,15 @@
 	options->Get(&maxtrimming,"maxtrimming",+1.e+21);
 	options->Get(&minspacing,"minspacing",0.01);
-	if(minspacing<=0) _error2_("minspacing must > 0");
+	if(minspacing<=0) _error_("minspacing must > 0");
 
 	/*Get Minimum box size*/
 	if(options->GetOption("boxlength")){
 		options->Get(&minlength,"boxlength");
-		if(minlength<=0)_error2_("boxlength should be a positive number");
-		maxdepth=int(log(max(xmax-xmin,ymax-ymin)/minlength +1)/log(2.0));
+		if(minlength<=0)_error_("boxlength should be a positive number");
+		maxdepth=reCast<int,IssmPDouble>(log(max(xmax-xmin,ymax-ymin)/minlength +1)/log(2.0));
 	}
 	else{
 		maxdepth = 30;
-		minlength=max(xmax-xmin,ymax-ymin)/IssmDouble((1L<<maxdepth)-1);
+		minlength=max(xmax-xmin,ymax-ymin)/IssmPDouble((1L<<maxdepth)-1);
 	}
 
@@ -117,10 +118,10 @@
 /*Methods*/
 /*FUNCTION Observations::ClosestObservation{{{*/
-void Observations::ClosestObservation(IssmDouble *px,IssmDouble *py,IssmDouble *pobs,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius){
+void Observations::ClosestObservation(IssmPDouble *px,IssmPDouble *py,IssmPDouble *pobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius){
 
 	/*Output and Intermediaries*/
 	bool         stop;
 	int          nobs,i,index;
-	IssmDouble       h2,hmin2,radius2;
+	IssmPDouble  h2,hmin2,radius2;
 	int         *indices      = NULL;
 	Observation *observation  = NULL;
@@ -165,17 +166,17 @@
 
 }/*}}}*/
-/*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){
+/*FUNCTION Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int maxdata){{{*/
+void Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int maxdata){
 
 	/*Output and Intermediaries*/
 	bool         stop;
 	int          nobs,tempnobs,i,j,k,n,counter;
-	IssmDouble       h2,radius2;
+	IssmPDouble  h2,radius2;
 	int         *indices      = NULL;
 	int         *tempindices  = NULL;
-	IssmDouble      *dists        = NULL;
-	IssmDouble      *x            = NULL;
-	IssmDouble      *y            = NULL;
-	IssmDouble      *obs          = NULL;
+	IssmPDouble *dists        = NULL;
+	IssmPDouble *x            = NULL;
+	IssmPDouble *y            = NULL;
+	IssmPDouble *obs          = NULL;
 	Observation *observation  = NULL;
 
@@ -190,5 +191,5 @@
 	if(tempnobs){
 		indices = xNew<int>(tempnobs);
-		dists   = xNew<IssmDouble>(tempnobs);
+		dists   = xNew<IssmPDouble>(tempnobs);
 	}
 	nobs = 0;
@@ -225,12 +226,12 @@
 		}
 	}  
-	xDelete<IssmDouble>(dists);
+	xDelete<IssmPDouble>(dists);
 	xDelete<int>(tempindices);
 
 	if(nobs){
 		/*Allocate vectors*/
-		x   = xNew<IssmDouble>(nobs);
-		y   = xNew<IssmDouble>(nobs);
-		obs = xNew<IssmDouble>(nobs);
+		x   = xNew<IssmPDouble>(nobs);
+		y   = xNew<IssmPDouble>(nobs);
+		obs = xNew<IssmPDouble>(nobs);
 
 		/*Loop over all observations and fill in x, y and obs*/
@@ -248,12 +249,12 @@
 	*pnobs=nobs;
 }/*}}}*/
-/*FUNCTION Observations::ObservationList(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs){{{*/
-void Observations::ObservationList(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs){
+/*FUNCTION Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs){{{*/
+void Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs){
 
 	/*Output and Intermediaries*/
 	int          nobs;
-	IssmDouble      *x            = NULL;
-	IssmDouble      *y            = NULL;
-	IssmDouble      *obs          = NULL;
+	IssmPDouble *x            = NULL;
+	IssmPDouble *y            = NULL;
+	IssmPDouble *obs          = NULL;
 	Observation *observation  = NULL;
 
@@ -261,7 +262,7 @@
 
 	if(nobs){
-		x   = xNew<IssmDouble>(nobs);
-		y   = xNew<IssmDouble>(nobs);
-		obs = xNew<IssmDouble>(nobs);
+		x   = xNew<IssmPDouble>(nobs);
+		y   = xNew<IssmPDouble>(nobs);
+		obs = xNew<IssmPDouble>(nobs);
 		for(int i=0;i<this->Size();i++){
 			observation=(Observation*)this->GetObjectByOffset(i);
@@ -277,13 +278,13 @@
 }/*}}}*/
 /*FUNCTION Observations::InterpolationIDW{{{*/
-void Observations::InterpolationIDW(IssmDouble *pprediction,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int mindata,int maxdata,IssmDouble power){
+void Observations::InterpolationIDW(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata,IssmPDouble power){
 
 	/*Intermediaries*/
-	int    i,n_obs;
-	IssmDouble prediction;
-	IssmDouble numerator,denominator,h,weight;
-	IssmDouble *x   = NULL;
-	IssmDouble *y   = NULL;
-	IssmDouble *obs = NULL;
+	int         i,n_obs;
+	IssmPDouble prediction;
+	IssmPDouble numerator,denominator,h,weight;
+	IssmPDouble *x   = NULL;
+	IssmPDouble *y   = NULL;
+	IssmPDouble *obs = NULL;
 
 	/*Some checks*/
@@ -321,24 +322,24 @@
 	/*clean-up*/
 	*pprediction = prediction;
-	xDelete<IssmDouble>(x);
-	xDelete<IssmDouble>(y);
-	xDelete<IssmDouble>(obs);
+	xDelete<IssmPDouble>(x);
+	xDelete<IssmPDouble>(y);
+	xDelete<IssmPDouble>(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){
+void Observations::InterpolationKriging(IssmPDouble *pprediction,IssmPDouble *perror,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int mindata,int maxdata,Variogram* variogram){
 
 	/*Intermediaries*/
 	int           i,j,n_obs;
-	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;
+	IssmPDouble   prediction,error;
+	IssmPDouble   numerator,denominator,ratio;
+	IssmPDouble  *x            = NULL;
+	IssmPDouble  *y            = NULL;
+	IssmPDouble  *obs          = NULL;
+	IssmPDouble  *Gamma        = NULL;
+	IssmPDouble  *GinvG0       = NULL;
+	IssmPDouble  *Ginv1        = NULL;
+	IssmPDouble  *GinvZ        = NULL;
+	IssmPDouble  *gamma0       = NULL;
+	IssmPDouble  *ones         = NULL;
 
 	/*Some checks*/
@@ -360,7 +361,7 @@
 
 	/*Allocate intermediary matrix and vectors*/
-	Gamma  = xNew<IssmDouble>(n_obs*n_obs);
-	gamma0 = xNew<IssmDouble>(n_obs);
-	ones   = xNew<IssmDouble>(n_obs);
+	Gamma  = xNew<IssmPDouble>(n_obs*n_obs);
+	gamma0 = xNew<IssmPDouble>(n_obs);
+	ones   = xNew<IssmPDouble>(n_obs);
 
 	/*First: Create semivariogram matrix for observations*/
@@ -380,9 +381,9 @@
 	/*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
+	SolverxSeq(&GinvG0,Gamma,gamma0,n_obs); // Gamma^-1 gamma0
+	SolverxSeq(&Ginv1, Gamma,ones,n_obs);   // Gamma^-1 ones
+	SolverxSeq(&GinvZ, Gamma,obs,n_obs);    // Gamma^-1 Z
 #else
-	_error2_("GSL is required");
+	_error_("GSL is required");
 #endif
 
@@ -401,20 +402,20 @@
 	*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);
+	xDelete<IssmPDouble>(x);
+	xDelete<IssmPDouble>(y);
+	xDelete<IssmPDouble>(obs);
+	xDelete<IssmPDouble>(Gamma);
+	xDelete<IssmPDouble>(gamma0);
+	xDelete<IssmPDouble>(ones);
+	xDelete<IssmPDouble>(GinvG0);
+	xDelete<IssmPDouble>(Ginv1);
+	xDelete<IssmPDouble>(GinvZ);
 
 }/*}}}*/
 /*FUNCTION Observations::InterpolationNearestNeighbor{{{*/
-void Observations::InterpolationNearestNeighbor(IssmDouble *pprediction,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius){
+void Observations::InterpolationNearestNeighbor(IssmPDouble *pprediction,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius){
 
 	/*Intermediaries*/
-	IssmDouble        x,y,obs;
+	IssmPDouble x,y,obs;
 
 	/*Get clostest observation*/
@@ -425,5 +426,5 @@
 }/*}}}*/
 /*FUNCTION Observations::QuadtreeColoring{{{*/
-void Observations::QuadtreeColoring(IssmDouble* A,IssmDouble *x,IssmDouble *y,int n){
+void Observations::QuadtreeColoring(IssmPDouble* A,IssmPDouble *x,IssmPDouble *y,int n){
 
 	int xi,yi,level;
@@ -432,18 +433,18 @@
 		this->quadtree->IntergerCoordinates(&xi,&yi,x[i],y[i]);
 		this->quadtree->QuadtreeDepth(&level,xi,yi);
-		A[i]=(IssmDouble)level;
+		A[i]=(IssmPDouble)level;
 	}
 
 }/*}}}*/
 /*FUNCTION Observations::Variomap{{{*/
-void Observations::Variomap(IssmDouble* gamma,IssmDouble *x,int n){
+void Observations::Variomap(IssmPDouble* gamma,IssmPDouble *x,int n){
 
 	/*Output and Intermediaries*/
 	int          i,j,k;
-	IssmDouble       distance;
+	IssmPDouble  distance;
 	Observation *observation1 = NULL;
 	Observation *observation2 = NULL;
 
-	IssmDouble *counter = xNew<IssmDouble>(n);
+	IssmPDouble *counter = xNew<IssmPDouble>(n);
 	for(j=0;j<n;j++) counter[j] = 0.0;
 	for(j=0;j<n;j++) gamma[j]   = 0.0;
@@ -474,4 +475,4 @@
 
 	/*Assign output pointer*/
-	xDelete<IssmDouble>(counter);
-}/*}}}*/
+	xDelete<IssmPDouble>(counter);
+}/*}}}*/
Index: /issm/trunk/src/c/Container/Observations.h
===================================================================
--- /issm/trunk/src/c/Container/Observations.h	(revision 13394)
+++ /issm/trunk/src/c/Container/Observations.h	(revision 13395)
@@ -7,4 +7,5 @@
 
 #include "../include/include.h"
+#include "../classes/objects/Options/GenericOption.h"
 
 class Quadtree;
Index: /issm/trunk/src/c/Container/Options.cpp
===================================================================
--- /issm/trunk/src/c/Container/Options.cpp	(revision 13394)
+++ /issm/trunk/src/c/Container/Options.cpp	(revision 13395)
@@ -19,4 +19,5 @@
 #include "../io/io.h"
 #include "../include/include.h"
+#include "../classes/classes.h"
 #include "../shared/shared.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
@@ -40,4 +41,6 @@
 int  Options::AddOption(Option* in_option){
 
+	char* name=NULL;
+	
 	vector<Object*>::iterator object;
 	Option* option=NULL;
@@ -47,8 +50,10 @@
 
 	/*Also, check the 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 \"]\"");
+	name=in_option->Name();
+
+	if(!name) _error_("input option has an empty name");
+	if(strchr(name,'.')) _error_("Option \"" << name << "\" has a protected character \".\"");
+	if(strchr(name,'[')) _error_("Option \"" << name << "\" has a protected character \"[\"");
+	if(strchr(name,']')) _error_("Option \"" << name << "\" has a protected character \"]\"");
 
 	/*Finally, check that no option of the same name already exists in the dataset*/
@@ -56,6 +61,6 @@
 
 		option=(Option*)(*object); 
-		if (!strcmp(option->name,in_option->name)){
-			_error2_("Options \"" << in_option->name << "\" found multiple times");
+		if (!strcmp(option->Name(),name)){
+			_error_("Options \"" << name << "\" found multiple times");
 			break;
 		}
@@ -66,230 +71,4 @@
 
 	return 1;
-}
-/*}}}*/
-/*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;
-	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(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){
-
-	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(bool* pvalue, char* name,bool default_value){{{*/
-void Options::Get(bool* pvalue,const char* name,bool 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(char** pvalue, char* name){{{*/
-void Options::Get(char** pvalue,const char* name){
-
-	vector<Object*>::iterator object;
-	Option* option=NULL;
-	char* outstring=NULL;
-	int   stringsize;
-
-	/*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(char** pvalue, char* name,char* default_value){{{*/
-void Options::Get(char** pvalue,const char* name,const char* default_value){
-
-	vector<Object*>::iterator object;
-	Option* option=NULL;
-	char* outstring=NULL;
-	int   stringsize;
-
-	/*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{
-		stringsize=strlen(default_value)+1;
-		outstring=xNew<char>(stringsize);
-		xMemCpy<char>(outstring,default_value,stringsize);
-		*pvalue=outstring;
-	}
-
-}
-/*}}}*/
-/*FUNCTION Options::Get(char*** ppvalue,int* numel,char* name){{{*/
-void Options::Get(char*** ppvalue,int* numel,const char* name){
-
-	vector<Object*>::iterator object;
-	Option* option=NULL;
-	Option* option2=NULL;
-	Options* options=NULL;
-	int   i;
-
-	/*Get option*/
-	option=GetOption(name);
-
-	/*If the pointer is not NULL, the option has been found*/
-	if(option){
-		/*If the object is a Cell, copy the strings from its options dataset*/ 
-		if(option->ObjectEnum()==OptionCellEnum){
-			if (option->NumEl()) {
-				*ppvalue=xNew<char*>(option->NumEl());
-				if (numel) *numel=option->NumEl();
-				option->Get(&options);
-				for (i=0; i<option->NumEl(); i++) {
-					option2=((Option *)options->GetObjectByOffset(i));
-					if(option2->ObjectEnum()==OptionCharEnum)
-						option2->Get(&((*ppvalue)[i]));
-					else
-						((*ppvalue)[i])=NULL;
-				}
-			}
-		}
-		/*If the object is a Char, copy the strings from its concatenation*/ 
-		else if(option->ObjectEnum()==OptionCharEnum){
-			option->Get(ppvalue,numel);
-		}
-		/*Else: not supported*/
-		else{
-			_error2_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
-		}
-	}
-	/*Else, the Option does not exist, no default provided*/
-	else{
-		*ppvalue=NULL;
-		if (numel) *numel=0;
-	}
-
-}
-/*}}}*/
-/*FUNCTION Options::Get(IssmDouble** pvalue,int* numel,const char* name){{{*/
-void Options::Get(IssmDouble** pvalue,int* numel,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,numel);
-	}
-	/*Else, the Option does not exist, no default provided*/
-	else{
-		_error2_("option of name \"" << name << "\" not found, and no default value has been provided");
-	}
 }
 /*}}}*/
@@ -304,8 +83,8 @@
 
 		option=(Option*)(*object); 
-		if (!strncmp(name,option->name,strlen(option->name))){
+		if (!strncmp(name,option->Name(),strlen(option->Name()))){
 
 			/*OK, now do we have a complete name? If not, it is a cell or a structure, we need to go further*/
-			if(!strcmp(name,option->name)){
+			if(!strcmp(name,option->Name())){
 				return option;
 			}
@@ -313,16 +92,18 @@
 				/*If the object is a Cell, recursive call to its options*/ 
 				if(option->ObjectEnum()==OptionCellEnum){
-					return ((OptionCell*)option)->values->GetOption(name);
+					GenericOption<Options*>* celloption=(GenericOption<Options*>*)option;
+					return celloption->value->GetOption(name);
 				}
 				/*If the object is a Struct loop over its size and recursive call*/
 				else if(option->ObjectEnum()==OptionStructEnum){
-					for(int i=0;i<option->numel;i++){
-						_assert_(((OptionStruct*)option)->values[i]);
-						return ((OptionStruct*)option)->values[i]->GetOption(name);
+					for(int i=0;i<option->NumEl();i++){
+						GenericOption<Options**>* structoption=(GenericOption<Options**>*)option;
+						_assert_(structoption->value[i]);
+						return structoption->value[i]->GetOption(name);
 					}
 				}
 				/*Else: not supported*/
 				else{
-					_error2_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
+					_error_("Cannot recover field \"" << name << "\" for an option of type " << EnumToStringx(option->ObjectEnum()));
 				}
 			}
Index: /issm/trunk/src/c/Container/Options.h
===================================================================
--- /issm/trunk/src/c/Container/Options.h	(revision 13394)
+++ /issm/trunk/src/c/Container/Options.h	(revision 13395)
@@ -5,4 +5,6 @@
 #ifndef _CONTAINER_OPTIONS_H_
 #define _CONTAINER_OPTIONS_H_
+
+#include "../classes/objects/Options/GenericOption.h"
 
 /*forward declarations */
@@ -20,15 +22,105 @@
 		int  AddOption(Option* in_oobject);
 		Option* GetOption(const char* name);
-		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);
-		void Get(char**   pvalue,const char* name);
-		void Get(char**   pvalue,const char* name,const char* default_value);
-		void Get(char***  pvalue,int* numel,const char* name);
-		void Get(IssmDouble** pvalue,int* numel,const char* name);
+		
+		
+		template <class OptionType> void Get(OptionType* pvalue,const char* name){ /*{{{*/
+
+			vector<Object*>::iterator object;
+			GenericOption<OptionType>* genericoption=NULL;
+
+			/*Get option*/
+			genericoption=(GenericOption<OptionType>*)GetOption(name);
+
+			/*If the pointer is not NULL, the option has been found*/
+			if(genericoption){
+				genericoption->Get(pvalue);
+			}
+			/*Else, the Option does not exist, no default provided*/
+			else{
+				_error_("option of name \"" << name << "\" not found, and no default value has been provided");
+			}
+		}
+		/*}}}*/
+		template <class OptionType> void Get(OptionType* pvalue,int* pnumel, const char* name){ /*{{{*/
+
+			vector<Object*>::iterator object;
+			GenericOption<OptionType>* genericoption=NULL;
+
+			/*Get option*/
+			genericoption=(GenericOption<OptionType>*)GetOption(name);
+
+			/*If the pointer is not NULL, the option has been found*/
+			if(genericoption){
+				genericoption->Get(pvalue);
+				*pnumel=genericoption->NumEl();
+			}
+			/*Else, the Option does not exist, no default provided*/
+			else{
+				_error_("option of name \"" << name << "\" not found, and no default value has been provided");
+			}
+		}
+		/*}}}*/
+		template <class OptionType> void Get(OptionType* pvalue,const char* name,OptionType default_value){ /*{{{*/
+
+			vector<Object*>::iterator object;
+			GenericOption<OptionType>* genericoption=NULL;
+
+			/*Get option*/
+			genericoption=(GenericOption<OptionType>*)GetOption(name);
+
+			/*If the pointer is not NULL, the option has been found*/
+			if(genericoption){
+				genericoption->Get(pvalue);
+			}
+			else{
+				*pvalue=default_value;
+			}
+		}
+		/*}}}*/
+		template <class OptionType> void Get(OptionType* pvalue,int* pnumel, const char* name,OptionType default_value){ /*{{{*/
+
+			vector<Object*>::iterator object;
+			GenericOption<OptionType>* genericoption=NULL;
+
+			/*Get option*/
+			genericoption=(GenericOption<OptionType>*)GetOption(name);
+
+			/*If the pointer is not NULL, the option has been found*/
+			if(genericoption){
+				genericoption->Get(pvalue);
+				*pnumel=genericoption->NumEl();
+			}
+			else{
+				*pvalue=default_value;
+			}
+		}
+		/*}}}*/
+
 };
 
 #endif //ifndef _INPUTS_H_
+
+template <> inline void Options::Get(char** pvalue,const char* name,char* default_value){ /*{{{*/
+
+	vector<Object*>::iterator object;
+	GenericOption<char*>* genericoption=NULL;
+
+	/*Get option*/
+	genericoption=(GenericOption<char*>*)GetOption(name);
+
+	/*If the pointer is not NULL, the option has been found*/
+	if(genericoption){
+		genericoption->Get(pvalue);
+	}
+	else{
+		/*Make a copy*/
+		char* outstring=NULL;
+		int   stringsize;
+
+		stringsize=strlen(default_value)+1;
+		outstring=xNew<char>(stringsize);
+		xMemCpy<char>(outstring,default_value,stringsize);
+		*pvalue=outstring;
+	}
+}
+/*}}}*/
Index: /issm/trunk/src/c/Container/Parameters.cpp
===================================================================
--- /issm/trunk/src/c/Container/Parameters.cpp	(revision 13394)
+++ /issm/trunk/src/c/Container/Parameters.cpp	(revision 13395)
@@ -65,5 +65,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 }
 /*}}}*/
@@ -82,5 +82,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 }
 /*}}}*/
@@ -99,5 +99,22 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(IssmDouble* pscalar, int enum_type,IssmDouble time){{{*/
+void Parameters::FindParam(IssmDouble* pscalar, int enum_type,IssmDouble time){ _assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=(Param*)(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pscalar,time);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 }
 /*}}}*/
@@ -116,5 +133,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -134,5 +151,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -152,5 +169,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -170,5 +187,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -188,5 +205,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -206,5 +223,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -224,9 +241,9 @@
 		}
 	}
-	_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);
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(Vector<IssmDouble>** pvec,int enum_type){{{*/
+void Parameters::FindParam(Vector<IssmDouble>** pvec,int enum_type){ _assert_(this);
 	
 	vector<Object*>::iterator object;
@@ -241,10 +258,10 @@
 		}
 	}
-	_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);
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(Matrix<IssmDouble>** pmat,int enum_type){{{*/
+void Parameters::FindParam(Matrix<IssmDouble>** pmat,int enum_type){ _assert_(this);
 	
 	vector<Object*>::iterator object;
@@ -259,5 +276,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 
 }
@@ -277,5 +294,5 @@
 		}
 	}
-	_error2_("could not find parameter " << EnumToStringx(enum_type));
+	_error_("could not find parameter " << EnumToStringx(enum_type));
 }
 /*}}}*/
@@ -389,6 +406,6 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(Vector* vector,int enum_type);{{{*/
-void   Parameters::SetParam(Vector* vector,int enum_type){
+/*FUNCTION Parameters::SetParam(Vector<IssmDouble>* vector,int enum_type);{{{*/
+void   Parameters::SetParam(Vector<IssmDouble>* vector,int enum_type){
 
 	Param* param=NULL;
@@ -401,6 +418,6 @@
 }
 /*}}}*/
-/*FUNCTION Parameters::SetParam(Matrix* matrix,int enum_type);{{{*/
-void   Parameters::SetParam(Matrix* matrix,int enum_type){
+/*FUNCTION Parameters::SetParam(Matrix<IssmDouble>* matrix,int enum_type);{{{*/
+void   Parameters::SetParam(Matrix<IssmDouble>* matrix,int enum_type){
 
 	Param* param=NULL;
Index: /issm/trunk/src/c/Container/Parameters.h
===================================================================
--- /issm/trunk/src/c/Container/Parameters.h	(revision 13394)
+++ /issm/trunk/src/c/Container/Parameters.h	(revision 13395)
@@ -8,6 +8,6 @@
 
 /*forward declarations */
-class Matrix;
-class Vector;
+template <class doublematrix> class Matrix;
+template <class doubletype> class Vector;
 class Materials;
 class Parameters;
@@ -23,9 +23,9 @@
 	public:
 
-		/*constructors, destructors: {{{*/
+		/*constructors, destructors*/ 
 		Parameters();
 		~Parameters();
-		/*}}}*/
-		/*numerics: {{{*/
+
+		/*numerics*/
 		bool  Exist(int enum_type);
 
@@ -33,4 +33,5 @@
 		void  FindParam(int* pinteger,int enum_type);
 		void  FindParam(IssmDouble* pscalar, int enum_type);
+		void  FindParam(IssmDouble* pscalar, int enum_type,IssmDouble time);
 		void  FindParam(char** pstring,int enum_type);
 		void  FindParam(char*** pstringarray,int* pM,int enum_type);
@@ -40,6 +41,6 @@
 		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);
+		void  FindParam(Vector<IssmDouble>** pvec,int enum_type);
+		void  FindParam(Matrix<IssmDouble>** pmat,int enum_type);
 		void  FindParam(FILE** pfid,int enum_type);
 		
@@ -53,11 +54,10 @@
 		void  SetParam(int* intarray,int M,int enum_type);
 		void  SetParam(int* intarray,int M,int N,int enum_type);
-		void  SetParam(Vector* vec,int enum_type);
-		void  SetParam(Matrix* mat,int enum_type);
+		void  SetParam(Vector<IssmDouble>* vec,int enum_type);
+		void  SetParam(Matrix<IssmDouble>* mat,int enum_type);
 		void  SetParam(FILE* fid,int enum_type);
 		void  UnitConversion(int direction_enum);
 
 		Object* FindParamObject(int enum_type);
-		/*}}}*/
 
 };
Index: /issm/trunk/src/c/EnumDefinitions/EnumDefinitions.h
===================================================================
--- /issm/trunk/src/c/EnumDefinitions/EnumDefinitions.h	(revision 13394)
+++ /issm/trunk/src/c/EnumDefinitions/EnumDefinitions.h	(revision 13395)
@@ -12,7 +12,12 @@
 enum definitions{
 	/*Model fields {{{1*/
-	AutodiffForwardEnum,
 	AutodiffIsautodiffEnum, 
-	AutodiffReverseEnum,
+	AutodiffDependentsEnum,
+	AutodiffNumDependentsEnum,
+	AutodiffIndependentsEnum,
+	AutodiffNumIndependentsEnum,
+	AutodiffJacobianEnum,
+	AutodiffXpEnum,
+	AutodiffFosForwardOutputEnum,
 	BalancethicknessSpcthicknessEnum,
 	BalancethicknessStabilizationEnum,
@@ -50,4 +55,5 @@
 	FlowequationElementEquationEnum,
 	FlowequationIshutterEnum,
+	FlowequationIsl1l2Enum,
 	FlowequationIsmacayealpattynEnum,
 	FlowequationIsstokesEnum,
@@ -101,4 +107,6 @@
 	MaterialsRheologyLawEnum,
 	MaterialsRheologyNEnum,
+	MaterialsRheologyZEnum,
+	MaterialsRheologyZbarEnum,
 	MaterialsRhoIceEnum,
 	MaterialsRhoWaterEnum,
@@ -149,4 +157,10 @@
 	SettingsResultsAsPatchesEnum,
 	SettingsWaitonlockEnum,
+	SurfaceforcingsDelta18oEnum,
+	SurfaceforcingsDelta18oSurfaceEnum,
+	SurfaceforcingsIsdelta18oEnum,
+	SurfaceforcingsPrecipitationsPresentdayEnum,
+	SurfaceforcingsTemperaturesPresentdayEnum,
+	SurfaceforcingsTemperaturesLgmEnum,
 	DebugProfilingEnum,
 	ProfilingCurrentMemEnum,
@@ -230,9 +244,10 @@
 	/*Approximations {{{1*/
 	ApproximationEnum,
+	NoneApproximationEnum,
 	HutterApproximationEnum,
 	MacAyealApproximationEnum,
 	MacAyealPattynApproximationEnum,
 	MacAyealStokesApproximationEnum,
-	NoneApproximationEnum,
+	L1L2ApproximationEnum,
 	PattynApproximationEnum,
 	PattynStokesApproximationEnum,
@@ -249,4 +264,6 @@
 	/*}}}*/
 	/*Objects {{{1*/
+	GenericParamEnum,
+	AdolcParamEnum,
 	BoolInputEnum,
 	BoolParamEnum,
@@ -270,11 +287,14 @@
 	IntParamEnum,
 	IntVecParamEnum,
+	TransientParamEnum,
 	MacAyeal2dIceFrontEnum,
 	MacAyeal3dIceFrontEnum,
 	MaticeEnum,
+	MatdamageiceEnum,
 	MatparEnum,
 	NodeEnum,
 	NumericalfluxEnum,
 	ParamEnum,
+	L1L2IceFrontEnum,
 	PattynIceFrontEnum,
 	PengridEnum,
@@ -353,4 +373,6 @@
 	TemperatureOldEnum,
 	TemperaturePicardEnum,
+	TemperatureSurfaceEnum,
+	TemperatureBasalEnum,
 	ThicknessAbsMisfitEnum,
 	TypeEnum,
@@ -374,4 +396,6 @@
 	EnthalpyPicardEnum,
 	ThicknessAbsGradientEnum,
+	ThicknessAlongGradientEnum,
+	ThicknessAcrossGradientEnum,
 	StepResponsesEnum,
 	IntMatParamEnum,
@@ -394,5 +418,4 @@
 	StressTensoryzEnum,
 	StressTensorzzEnum,
-	IceVolumeEnum,
 	/*}}}*/
 	/*Element Interpolations{{{1*/
@@ -434,4 +457,6 @@
 	MaxVzEnum,
 	MaxAbsVzEnum,
+	IceVolumeEnum,
+	TotalSmbEnum,
 	/*}}}*/
 	/*Convergence{{{1*/
@@ -487,4 +512,5 @@
 	/*Options{{{1*/
 	OptionEnum,
+	GenericOptionEnum,
 	OptionCellEnum,
 	OptionCharEnum,
Index: /issm/trunk/src/c/EnumDefinitions/Synchronize.sh
===================================================================
--- /issm/trunk/src/c/EnumDefinitions/Synchronize.sh	(revision 13394)
+++ /issm/trunk/src/c/EnumDefinitions/Synchronize.sh	(revision 13395)
@@ -98,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*/
-	_error2_("Enum " << name << " not found");
+	_error_("Enum " << name << " not found");
 }
 END
@@ -107,4 +107,6 @@
 #Add header to pythonenum file{{{
 cat <<END > $ISSM_DIR/src/m/enum/EnumDefinitions.py
+from StringToEnum import StringToEnum
+
 """
 
@@ -166,5 +168,5 @@
 	"""
 
-	return StringToEnum('$NAME')
+	return StringToEnum('$NAME')[0]
 
 END
Index: /issm/trunk/src/c/Makefile.am
===================================================================
--- /issm/trunk/src/c/Makefile.am	(revision 13394)
+++ /issm/trunk/src/c/Makefile.am	(revision 13395)
@@ -1,3 +1,3 @@
-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@
+AM_CPPFLAGS = @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)
@@ -5,11 +5,21 @@
 #Library declaration {{{
 lib_LIBRARIES = libISSMCore.a libISSMOverload.a
+
+if SHAREDLIBS
+lib_LTLIBRARIES = libISSMCore.la libISSMOverload.la libISSM.la
+endif
 if PYTHON
 lib_LIBRARIES += libISSMPython.a 
 endif
 if MATLAB
+if SHAREDLIBS
+lib_LTLIBRARIES += libISSMMatlab.la
+endif
 lib_LIBRARIES += libISSMMatlab.a 
 endif
 if MODULES
+if SHAREDLIBS
+lib_LTLIBRARIES += libISSMModules.la
+endif
 lib_LIBRARIES += libISSMModules.a 
 endif
@@ -24,130 +34,122 @@
 					./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/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/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/GenericExternalResult.h\
+					./classes/objects/Elements/Tria.h\
+					./classes/objects/Elements/Tria.cpp\
+					./classes/objects/Elements/TriaHook.h\
+					./classes/objects/Elements/TriaHook.cpp\
+					./classes/objects/Elements/TriaRef.h\
+					./classes/objects/Elements/TriaRef.cpp\
+					./classes/objects/Inputs/Input.h\
+					./classes/objects/Inputs/InputLocal.h\
+					./classes/objects/Inputs/TriaP1Input.h\
+					./classes/objects/Inputs/TriaP1Input.cpp\
+					./classes/objects/Inputs/BoolInput.h\
+					./classes/objects/Inputs/BoolInput.cpp\
+					./classes/objects/Inputs/IntInput.h\
+					./classes/objects/Inputs/IntInput.cpp\
+					./classes/objects/Inputs/DoubleInput.h\
+					./classes/objects/Inputs/DoubleInput.cpp\
+					./classes/objects/Inputs/DatasetInput.h\
+					./classes/objects/Inputs/DatasetInput.cpp\
+					./classes/objects/Materials/Matice.h\
+					./classes/objects/Materials/Matice.cpp\
+					./classes/objects/Materials/Matdamageice.h\
+					./classes/objects/Materials/Matdamageice.cpp\
+					./classes/objects/Materials/Matpar.h\
+					./classes/objects/Materials/Matpar.cpp\
+					./classes/objects/Constraints/Constraint.h\
+					./classes/objects/Constraints/SpcStatic.cpp\
+					./classes/objects/Constraints/SpcStatic.h\
+					./classes/objects/Constraints/SpcDynamic.cpp\
+					./classes/objects/Constraints/SpcDynamic.h\
+					./classes/objects/Loads/Penpair.cpp\
+					./classes/objects/Loads/Penpair.h\
+					./classes/objects/Loads/Pengrid.cpp\
+					./classes/objects/Loads/Pengrid.h\
+					./classes/objects/Loads/Icefront.cpp\
+					./classes/objects/Loads/Icefront.h\
+					./classes/objects/Loads/Numericalflux.cpp\
+					./classes/objects/Loads/Numericalflux.h\
+					./classes/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/Vector.h\
+					./classes/objects/Params/Param.h\
+					./classes/objects/Params/GenericParam.h\
+					./classes/objects/Params/BoolParam.cpp\
+					./classes/objects/Params/BoolParam.h\
+					./classes/objects/Params/IntParam.cpp\
+					./classes/objects/Params/IntParam.h\
+					./classes/objects/Params/IntVecParam.cpp\
+					./classes/objects/Params/IntVecParam.h\
+					./classes/objects/Params/IntMatParam.cpp\
+					./classes/objects/Params/IntMatParam.h\
+					./classes/objects/Params/DoubleParam.cpp\
+					./classes/objects/Params/DoubleParam.h\
+					./classes/objects/Params/FileParam.cpp\
+					./classes/objects/Params/FileParam.h\
+					./classes/objects/Params/StringArrayParam.cpp\
+					./classes/objects/Params/StringArrayParam.h\
+					./classes/objects/Params/DoubleMatParam.cpp\
+					./classes/objects/Params/DoubleMatParam.h\
+					./classes/objects/Params/DoubleTransientMatParam.cpp\
+					./classes/objects/Params/DoubleTransientMatParam.h\
+					./classes/objects/Params/DoubleMatArrayParam.cpp\
+					./classes/objects/Params/DoubleMatArrayParam.h\
+					./classes/objects/Params/DoubleVecParam.cpp\
+					./classes/objects/Params/DoubleVecParam.h\
+					./classes/objects/Params/StringParam.cpp\
+					./classes/objects/Params/StringParam.h\
+					./classes/objects/Params/MatrixParam.h\
+					./classes/objects/Params/MatrixParam.cpp\
+					./classes/objects/Params/VectorParam.h\
+					./classes/objects/Params/VectorParam.cpp\
+					./classes/objects/Params/TransientParam.h\
+					./classes/objects/Params/TransientParam.cpp\
 					./Container/Container.h\
 					./Container/Constraints.h\
@@ -180,4 +182,5 @@
 					./shared/Matrix/matrix.h\
 					./shared/Matrix/MatrixUtils.cpp\
+					./shared/Numerics/adolc_edf.h\
 					./shared/Numerics/numerics.h\
 					./shared/Numerics/Verbosity.h\
@@ -189,4 +192,5 @@
 					./shared/Numerics/isnan.h\
 					./shared/Numerics/isnan.cpp\
+					./shared/Numerics/cubic.cpp\
 					./shared/Numerics/extrema.cpp\
 					./shared/Numerics/XZvectorsToCoordinateSystem.cpp\
@@ -205,5 +209,7 @@
 					./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\
@@ -216,7 +222,5 @@
 					./toolkits/issm/issmtoolkit.h\
 					./toolkits/issm/SeqVec.h\
-					./toolkits/issm/SeqVec.cpp\
 					./toolkits/issm/SeqMat.h\
-					./toolkits/issm/SeqMat.cpp\
 					./toolkits/triangle/triangleincludes.h\
 					./toolkitsenums.h\
@@ -237,4 +241,5 @@
 					./modules/ModelProcessorx/CreateDataSets.cpp\
 					./modules/ModelProcessorx/CreateParameters.cpp\
+					./modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp\
 					./modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp\
 					./modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp\
@@ -288,9 +293,10 @@
 					./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\
-					./modules/MeshPartitionx/MeshPartitionx.cpp\
 					./modules/MeshPartitionx/MeshPartitionx.h\
 					./modules/Reducevectorgtofx/Reducevectorgtofx.cpp\
@@ -313,4 +319,8 @@
 					./modules/RequestedOutputsx/RequestedOutputsx.h\
 					./modules/RequestedOutputsx/RequestedOutputsx.cpp\
+					./modules/RequestedDependentsx/RequestedDependentsx.h\
+					./modules/RequestedDependentsx/RequestedDependentsx.cpp\
+					./modules/AutodiffDriversx/AutodiffDriversx.h\
+					./modules/AutodiffDriversx/AutodiffDriversx.cpp\
 					./modules/ResetConstraintsx/ResetConstraintsx.h\
 					./modules/ResetConstraintsx/ResetConstraintsx.cpp\
@@ -319,4 +329,5 @@
 					./modules/Solverx/Solverx.cpp\
 					./modules/Solverx/Solverx.h\
+					./modules/Solverx/SolverxSeq.cpp\
 					./modules/VecMergex/VecMergex.cpp\
 					./modules/VecMergex/VecMergex.h\
@@ -336,17 +347,13 @@
 					./solvers/solver_nonlinear.cpp\
 					./solvers/solver_newton.cpp\
-					./objects/Options/Option.cpp\
-					./objects/Options/Option.h\
-					./objects/Options/OptionDouble.cpp\
-					./objects/Options/OptionDouble.h\
-					./objects/Options/OptionChar.cpp\
-					./objects/Options/OptionChar.h\
-					./objects/Options/OptionUtilities.cpp\
-					./objects/Options/OptionUtilities.h
+					./classes/objects/Options/Option.h\
+					./classes/objects/Options/GenericOption.h\
+					./classes/objects/Options/OptionUtilities.cpp\
+					./classes/objects/Options/OptionUtilities.h
 
 #}}}
 #DAKOTA sources  {{{
-dakota_sources = ./objects/DakotaPlugin.h\
-					  ./objects/DakotaPlugin.cpp\
+dakota_sources = ./classes/dakota/DakotaPlugin.h\
+					  ./classes/dakota/DakotaPlugin.cpp\
 					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h\
 					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp\
@@ -365,7 +372,5 @@
 					  ./modules/Dakotax/SpawnCore.cpp\
 					  ./modules/Dakotax/DescriptorIndex.cpp\
-					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp\
 					  ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp\
-					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h\
 					  ./modules/Dakotax/SpawnCoreParallel.cpp
 #}}}
@@ -442,8 +447,12 @@
 					  ./modules/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp\
 					  ./modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h\
+					  ./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp\
+					  ./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h\
+					  ./modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp\
+					  ./modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h\
 					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp\
 					  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h\
-					  ./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 \
@@ -519,4 +528,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\
@@ -543,72 +554,73 @@
 #}}}
 #Rifts sources  {{{
-rifts_sources = ./objects/Loads/Riftfront.cpp\
-				    ./objects/Loads/Riftfront.h\
+rifts_sources = ./classes/objects/Loads/Riftfront.cpp\
+				    ./classes/objects/Loads/Riftfront.h\
 				    ./modules/ConstraintsStatex/RiftConstraintsState.cpp
 #}}}
 #3D sources  {{{
-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
+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 =  ./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\
+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\
@@ -630,17 +642,17 @@
 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
@@ -649,17 +661,17 @@
 pkriging_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/pKrigingx.cpp\
 						./modules/Krigingx/Krigingx.h
@@ -679,58 +691,58 @@
 			     ./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
+			     ./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  {{{
@@ -763,4 +775,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\
@@ -768,7 +785,4 @@
 					./modules/Solverx/DofTypesToIndexSet.cpp
 
-#}}}
-#Gsl sources  {{{
-gsl_sources= ./modules/Solverx/SolverxGsl.cpp
 #}}}
 #Mpi sources  {{{
@@ -810,26 +824,10 @@
 #}}}
 #Matlab and Petsc sources  {{{
-matlabpetsc_sources= ./matlab/io/MatlabMatrixToPetscMatrix.cpp\
-					 ./matlab/io/MatlabVectorToPetscVector.cpp
-	
+matlabpetsc_sources= ./matlab/io/MatlabMatrixToPetscMat.cpp\
+					 ./matlab/io/MatlabVectorToPetscVec.cpp
+
 #}}}
 #Modules sources{{{
-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\
+module_sources= ./shared/Threads/issm_threads.h\
 			./shared/Threads/LaunchThread.cpp\
 			./shared/Threads/PartitionRange.cpp\
@@ -837,5 +835,4 @@
 			./shared/Exp/IsInPoly.cpp\
 			./shared/Exp/IsInPolySerial.cpp\
-			./shared/Exp/DomainOutlineRead.cpp\
 			./shared/Exp/DomainOutlineWrite.cpp\
 			./shared/TriMesh/trimesh.h\
@@ -918,8 +915,4 @@
 endif
 
-if GSL
-issm_sources  +=  $(gsl_sources)
-endif
-
 if TRANSIENT
 issm_sources  +=  $(transient_sources)
@@ -998,10 +991,28 @@
 libISSMCore_a_CXXFLAGS = $(ALLCXXFLAGS)
 
+if SHAREDLIBS
+libISSM_la_SOURCES = solutions/issm.cpp
+libISSM_la_LIBADD = libISSMCore.la libISSMOverload.la
+
+libISSMCore_la_SOURCES  = $(issm_sources)
+libISSMCore_la_LIBADD = $(PETSCLIB) $(TAOLIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(ADOLCLIB)
+
+libISSMOverload_la_SOURCES = ./shared/String/stricmp.c
+endif
+
 if MODULES
 libISSMModules_a_SOURCES = $(module_sources)
 libISSMModules_a_SOURCES += $(bamg_sources)
+if KRIGING
 libISSMModules_a_SOURCES += $(kriging_sources)
+endif
+if KML
 libISSMModules_a_SOURCES += $(kml_sources)
+endif
 libISSMModules_a_CXXFLAGS = $(ALLCXXFLAGS)
+libISSMModules_a_LIBADD = ./libISSMCore.a
+if SHAREDLIBS
+libISSMModules_la_SOURCES = $(libISSMModules_a_SOURCES)
+endif
 endif
 
@@ -1014,6 +1025,14 @@
 libISSMMatlab_a_SOURCES = $(matlab_sources)
 libISSMMatlab_a_CXXFLAGS= $(ALLCXXFLAGS)
-endif
-
+if SHAREDLIBS
+libISSMMatlab_la_SOURCES = $(libISSMMatlab_a_SOURCES)
+endif
+endif
+
+if VERSION
+AM_LDFLAGS =
+else
+AM_LDFLAGS = -avoid-version
+endif
 #}}}
 #Overload library, to overload any non-standard symbols. {{{
Index: /issm/trunk/src/c/classes/DofIndexing.cpp
===================================================================
--- /issm/trunk/src/c/classes/DofIndexing.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/DofIndexing.cpp	(revision 13395)
@@ -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 _error_("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/trunk/src/c/classes/DofIndexing.h
===================================================================
--- /issm/trunk/src/c/classes/DofIndexing.h	(revision 13395)
+++ /issm/trunk/src/c/classes/DofIndexing.h	(revision 13395)
@@ -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/trunk/src/c/classes/FemModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/FemModel.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/FemModel.cpp	(revision 13395)
@@ -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* rootpath, 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,rootpath,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 _error_("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/trunk/src/c/classes/FemModel.h
===================================================================
--- /issm/trunk/src/c/classes/FemModel.h	(revision 13395)
+++ /issm/trunk/src/c/classes/FemModel.h	(revision 13395)
@@ -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* rootpath, 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/trunk/src/c/classes/Hook.cpp
===================================================================
--- /issm/trunk/src/c/classes/Hook.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/Hook.cpp	(revision 13395)
@@ -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]) _error_("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) _error_("trying to delivery a single hook object when hook holds " << this->num << " objects" << "\n");
+
+	/*check NULL: */
+	if (this->objects==NULL) _error_("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) _error_("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) _error_("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/trunk/src/c/classes/Hook.h
===================================================================
--- /issm/trunk/src/c/classes/Hook.h	(revision 13395)
+++ /issm/trunk/src/c/classes/Hook.h	(revision 13395)
@@ -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/trunk/src/c/classes/IoModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/IoModel.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/IoModel.cpp	(revision 13395)
@@ -0,0 +1,1375 @@
+/*! \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->independents=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 array detecting whether data[i] is an independent AD mode variable: */
+	this->independents=xNew<bool>(MaximumNumberOfEnums);
+	for(int i=0;i<MaximumNumberOfEnums;i++) this->independents[i]=false;
+	
+	/*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->independents);
+	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){
+			_error_("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_("");
+				_error_("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) _error_("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(int num,...){{{*/
+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);
+		
+		/*do not erase independent variables for the AD mode computations!: */
+		if (!this->independents[dataenum]) xDelete<IssmDouble>(this->data[dataenum]);
+	}
+	va_end(ap);
+} /*}}}*/
+/*FUNCTION IoModel::DeleteData(IssmDouble* {{{*/
+void  IoModel::DeleteData(IssmDouble* vector, int dataenum){
+
+	/*do not erase independent variables for the AD mode computations!: */
+	if(vector)if (!this->independents[dataenum]) xDelete<IssmDouble>(vector);
+
+} /*}}}*/
+/*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) _error_("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) _error_("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) _error_("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) _error_("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)_error_(" 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: 
+						_error_("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: 
+					_error_("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)_error_("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) _error_("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)_error_("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) _error_("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)_error_("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)_error_("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)_error_("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) _error_("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)_error_(" 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))_error_("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) _error_("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) _error_("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) _error_("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))_error_("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) _error_("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) _error_("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) _error_("could not read matrix ");
+		}
+		#ifdef _HAVE_MPI_
+		MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+		#endif
+
+		_assert_(this->independents);
+		if (this->independents[data_enum]){
+			/*this data has already been checked out! So cancel all that we've done here, and return 
+			 * the data[data_enum] directly: */
+			*pmatrix=this->data[data_enum];
+		}
+		else{
+			*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)_error_("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) _error_("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) _error_("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)_error_(" 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)_error_("expecting a IssmDouble mat array for enum " << EnumToStringx(data_enum));
+	
+	/*Now fetch: */
+	if(my_rank==0){  
+		if(fread(&numrecords,sizeof(int),1,fid)!=1) _error_("could not read number of records in matrix array ");
+	}
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&numrecords,1,MPI_INT,0,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) _error_("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) _error_("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) _error_("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;
+	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
+					GenericOption<IssmDouble>* option;
+					IssmDouble value;
+					FetchData(&value,index+1);
+					option = new GenericOption<IssmDouble>();
+					option->value = value;
+					option->name  = name;
+					option->numel = 1;
+					option->ndims = 1;
+					option->size  = NULL;
+					/*Assign output pointers: */
+					*poption=option;
+					break;
+				}
+		case 4: {//char
+					GenericOption<char*>* option;
+					char* value = NULL;
+					FetchData(&value,index+1);
+					option = new GenericOption<char*>();
+					option->value = value;
+					option->name  = name;
+					option->numel = 1;
+					option->ndims = 1;
+					option->size  = NULL;
+					*poption=option;
+					break;
+				}
+		default:
+			  _error_("Option of format " << code << " not supported yet");
+	}
+
+}
+/*}}}*/
+/*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);
+		
+		if (this->independents[dataenum]){
+			/*this data has already been checked out! Continue: */
+			continue;
+		}
+
+		/*Some checks in debugging mode*/
+		/*{{{*/
+		#ifdef _ISSM_DEBUG_
+		_assert_(dataenum<MaximumNumberOfEnums);
+		if(this->data[dataenum]){
+			_error_("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: /*{{{*/
+			_error_("data code " << code << " not supported yet!");
+			break;
+			/*}}}*/
+	}
+	/*Free ressources. Pay attention to not freeing an AD mode independent variable though!:*/
+	if (!this->independents[vector_enum] && !this->independents[default_vector_enum]) 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)_error_("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;
+}
+/*}}}*/
+/*FUNCTION IoModel::DeclareIndependents{{{*/
+void IoModel::DeclareIndependents(void){
+
+	bool autodiff=false;
+	int  dummy;
+	int i;
+	int  num_independents;
+	int* independents=NULL;
+
+	#ifdef _HAVE_ADOLC_
+	/*recover independent enums: */
+	this->Constant(&num_independents,AutodiffNumIndependentsEnum);
+	if(num_independents){
+		this->FetchData(&independents,&dummy,&dummy,AutodiffIndependentsEnum);
+
+		/*now go fetch the independent variables for each independent enum: */
+		for(i=0;i<num_independents;i++){
+			this->FetchIndependent(independents[i]);
+		}
+		xDelete<int>(independents);
+	}
+	#else
+	/*if we asked for AD computations, we have a problem!: */
+	this->Constant(&autodiff,AutodiffIsautodiffEnum);
+	if(autodiff)_error_("Cannot carry out AD mode computations without support of ADOLC compiled in!");
+	#endif
+
+}
+/*}}}*/
+/*FUNCTION IoModel::FetchIndependent{{{*/
+void IoModel::FetchIndependent(int independent_enum){
+
+	#ifdef _HAVE_ADOLC_ //cannot come here unless you are running AD mode, from DeclaredIndependents:
+	extern int my_rank;
+	extern int num_procs;
+
+	/*output: */
+	int M,N;
+	IssmPDouble* buffer=NULL; //a buffer to read the data from disk
+	IssmDouble* matrix=NULL; //our independent variable
+	int code=0;
+	int vector_type=0;
+	
+	/*Set file pointer to beginning of the data: */
+	fid=this->SetFilePointerToData(&code,&vector_type,independent_enum);
+	if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(independent_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) _error_("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) _error_("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){
+		buffer=xNew<IssmPDouble>(M*N);
+		matrix=xNew<IssmDouble>(M*N);
+
+		/*Read matrix on node 0, then broadcast: */
+		if(my_rank==0){  
+			if(fread(buffer,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
+			
+			/*Now, before we even broadcast this to other nodes, declare the whole matrix as a independent variable!: */
+			for (int i=0;i<M*N;++i) matrix[i]<<=buffer[i];  /*we use the <<= ADOLC overloaded operator to declare the independency*/
+		}
+		#ifdef _HAVE_MPI_
+		MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+		#endif
+		
+		xDelete<IssmPDouble>(buffer);
+	}
+	else _error_("cannot declare the independent variable " << EnumToStringx(independent_enum) <<  "if it's empty!");
+
+	/*Ok, we are almost done. Matrix is now a independent matrix. We don't want this matrix to be fetched again in the 
+	 *future, which would effectively write over the independency in the ADOLC tape! So we are going to keep track of this 
+	 independent matrix inthe iomodel->data[independent_enum] data slot: */
+	this->data[independent_enum]=matrix;
+	this->independents[independent_enum]=true;
+ 	#endif
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/IoModel.h
===================================================================
--- /issm/trunk/src/c/classes/IoModel.h	(revision 13395)
+++ /issm/trunk/src/c/classes/IoModel.h	(revision 13395)
@@ -0,0 +1,75 @@
+/* \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: 
+		Parameters  *constants;   //this dataset holds all IssmDouble, int, bool and char *parameters read in from the input file.*
+	
+	public:
+		IssmDouble **data;        //this dataset holds temporary data, memory intensive.
+		
+		/*This data needs to stay memory resident at all time, even if it's memory intensive: */
+		FILE *fid;         //pointer to input file
+		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
+		
+		/*for AD mode: to keep track of our independent variables we fetch:*/
+		bool* independents;
+
+		/*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        DeleteData(IssmDouble* vector, int dataenum);
+		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);
+		void        DeclareIndependents(void);
+		void        FetchIndependent(int dependent_enum);
+};
+
+#endif  /* _IOMODEL_H */
Index: /issm/trunk/src/c/classes/OptArgs.h
===================================================================
--- /issm/trunk/src/c/classes/OptArgs.h	(revision 13395)
+++ /issm/trunk/src/c/classes/OptArgs.h	(revision 13395)
@@ -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/trunk/src/c/classes/OptPars.h
===================================================================
--- /issm/trunk/src/c/classes/OptPars.h	(revision 13395)
+++ /issm/trunk/src/c/classes/OptPars.h	(revision 13395)
@@ -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/trunk/src/c/classes/Patch.cpp
===================================================================
--- /issm/trunk/src/c/classes/Patch.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/Patch.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/Patch.h
===================================================================
--- /issm/trunk/src/c/classes/Patch.h	(revision 13395)
+++ /issm/trunk/src/c/classes/Patch.h	(revision 13395)
@@ -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/trunk/src/c/classes/Update.h
===================================================================
--- /issm/trunk/src/c/classes/Update.h	(revision 13395)
+++ /issm/trunk/src/c/classes/Update.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/AdjacentTriangle.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/AdjacentTriangle.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/AdjacentTriangle.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/AdjacentTriangle.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/AdjacentTriangle.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/AdjacentTriangle.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/BamgGeom.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgGeom.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/BamgGeom.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/BamgGeom.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgGeom.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/BamgGeom.h	(revision 13395)
@@ -0,0 +1,31 @@
+/*!\file:  BamgGeom.h
+ */ 
+
+#ifndef _BAMGGEOM_H_
+#define _BAMGGEOM_H_
+
+class BamgGeom{
+
+	public:
+		int     VerticesSize[2];
+		double* Vertices;
+		int     EdgesSize[2];
+		double* Edges;
+		int     TangentAtEdgesSize[2];
+		double* TangentAtEdges;
+		int     CornersSize[2];
+		double* Corners;
+		int     RequiredVerticesSize[2];
+		double* RequiredVertices;
+		int     RequiredEdgesSize[2];
+		double* RequiredEdges;
+		int     CrackedEdgesSize[2];
+		double* CrackedEdges;
+		int     SubDomainsSize[2];
+		double* SubDomains;
+
+		BamgGeom();
+		~BamgGeom();
+};
+
+#endif
Index: /issm/trunk/src/c/classes/bamg/BamgMesh.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgMesh.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/BamgMesh.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/BamgMesh.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgMesh.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/BamgMesh.h	(revision 13395)
@@ -0,0 +1,52 @@
+/*!\file:  BamgMesh.h
+ */ 
+
+#ifndef _BAMGMESH_H_
+#define _BAMGMESH_H_
+
+class BamgMesh{
+
+	public:
+
+		int     VerticesSize[2];
+		double* Vertices;
+		int     EdgesSize[2];
+		double* Edges;
+		int     TrianglesSize[2];
+		double* Triangles;
+		int     QuadrilateralsSize[2];
+		double* Quadrilaterals;
+
+		int     VerticesOnGeomVertexSize[2];
+		double* VerticesOnGeomVertex;
+		int     VerticesOnGeomEdgeSize[2];
+		double* VerticesOnGeomEdge;
+		int     EdgesOnGeomEdgeSize[2];
+		double* EdgesOnGeomEdge;
+
+		int     SubDomainsSize[2];
+		double* SubDomains;
+		int     SubDomainsFromGeomSize[2];
+		double* SubDomainsFromGeom;
+		int     CrackedVerticesSize[2];
+		double* CrackedVertices;
+		int     CrackedEdgesSize[2];
+		double* CrackedEdges;
+
+		/*Output for ISSM*/
+		int     IssmEdgesSize[2];
+		double* IssmEdges;
+		int     IssmSegmentsSize[2];
+		double* IssmSegments;
+		int     ElementConnectivitySize[2];
+		double* ElementConnectivity;
+		int     NodalConnectivitySize[2];
+		double* NodalConnectivity;
+		int     NodalElementConnectivitySize[2];
+		double* NodalElementConnectivity;
+
+		BamgMesh();
+		~BamgMesh();
+};
+
+#endif
Index: /issm/trunk/src/c/classes/bamg/BamgOpts.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgOpts.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/BamgOpts.cpp	(revision 13395)
@@ -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) _error_("'anisomax' option should be >=1");
+	if (this->coeff==0) _error_("'coeff' should be positive");
+	if (this->errg<0) _error_("'errg' option should be >0");
+	if (this->gradation<1) _error_("'gradation' option should be >=1");
+	if (this->Hessiantype!=0  && this->Hessiantype!=1) _error_("'Hessiantype' supported options are 0 and 1");
+	if (this->maxnbv<3) _error_("'maxnbv' option should be >3");
+	if (this->maxsubdiv<=1) _error_("'maxsubdiv' should be >1");
+	if (this->Metrictype!=0   && this->Metrictype!=1 && this->Metrictype!=2) _error_("'Metrictype' supported options are 0, 1 and 2");
+	if (this->nbjacobi<=0) _error_("'nbjacobi' option should be >0");
+	if (this->nbsmooth<=0) _error_("'nbsmooth' option should be >0");
+
+	if (this->Crack!=0  && this->Crack!=1) _error_("'Crack' supported options are 0 and 1");
+	if (this->KeepVertices!=0 && this->KeepVertices!=1) _error_("'KeepVertices' supported options are 0 and 1");
+	if (this->geometricalmetric!=0  && this->geometricalmetric!=1) _error_("'geometricalmetric' supported options are 0 and 1");
+
+	if (this->hmin<=0) _error_("'hmin' option should be >0");
+	if (this->hmax<=0 || this->hmax<this->hmin) _error_("'hmax' option should be between 0 and hmin=" << this->hmin);
+	if (this->hminVertices && this->hminVerticesSize[1]!=1) _error_("'hminVertices' should be a column");
+	if (this->hmaxVertices && this->hmaxVerticesSize[1]!=1) _error_("'hmaxVertices' should be a column");
+	if (this->hVertices && this->hVerticesSize[1]!=1) _error_("'hVertices' should be a column");
+	if (this->metric && (this->metricSize[1]!=1 && this->metricSize[1]!=3)) _error_("'metric' should have either 1 (iso) or 3 (aniso) columns.");
+	if (this->field){
+		if (this->errSize[0]!=1 || this->errSize[1]!=this->fieldSize[1]) _error_("'err' should be of size " << 1 << " x " << this->fieldSize[1]);
+		for (i=0;i<this->fieldSize[1];i++) {if (this->err[i]<=0) _error_("'err' option should be >0");};
+	}
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/bamg/BamgOpts.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgOpts.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/BamgOpts.h	(revision 13395)
@@ -0,0 +1,57 @@
+/*!\file:  BamgOpts.h
+ * \brief place holder for optimization function arguments
+ */ 
+
+#ifndef _BAMGOPTS_H_
+#define _BAMGOPTS_H_
+
+class BamgOpts{
+
+	public:
+
+		/*Parameters*/
+		double  anisomax;
+		double  cutoff;
+		double  coeff;
+		double  errg;
+		double  gradation;
+		int     Hessiantype;
+		double  MaxCornerAngle;
+		int     maxnbv;
+		double  maxsubdiv;
+		int     Metrictype;
+		int     nbjacobi;
+		int     nbsmooth;
+		double  omega;
+		double  power;
+		int     verbose;
+
+		/*Flags*/
+		int     Crack;
+		int     geometricalmetric;
+		int     KeepVertices;
+		int     splitcorners;
+
+		/*Metric related*/
+		double  hmin;
+		double  hmax;
+		int     hminVerticesSize[2];
+		double* hminVertices;
+		int     hmaxVerticesSize[2];
+		double* hmaxVertices;
+		int     hVerticesSize[2];
+		double* hVertices;
+		int     metricSize[2];
+		double* metric;
+		int     fieldSize[2];
+		double* field;
+		int     errSize[2];
+		double* err;
+
+		BamgOpts();
+		~BamgOpts();
+
+		void Check(void);
+
+};
+#endif
Index: /issm/trunk/src/c/classes/bamg/BamgQuadtree.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgQuadtree.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/BamgQuadtree.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/BamgQuadtree.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgQuadtree.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/BamgQuadtree.h	(revision 13395)
@@ -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()       {_error_("not implemented yet"); };
+					void    DeepEcho()   {_error_("not implemented yet"); };
+					int     Id()         {_error_("not implemented yet"); };
+					int     MyRank()     {_error_("not implemented yet"); };
+					int     ObjectEnum() {_error_("not implemented yet"); };
+					Object *copy()       {_error_("not implemented yet"); };
+			};
+
+			/*BamgQuadtree private Fields*/
+			DataSet* boxcontainer;
+
+		public:
+
+			/*BamgQuadtree public Fields*/
+			BamgQuadtreeBox* root;
+			long         NbBamgQuadtreeBox;
+			long         NbVertices;
+
+			BamgQuadtree();
+			BamgQuadtree(Mesh *t,long nbv=-1);
+			~BamgQuadtree();
+
+			BamgVertex      *NearestVertex(Icoor1 i,Icoor1 j);
+			BamgVertex      *NearestVertexWithNormal(Icoor1  i,Icoor1 j);
+			BamgQuadtreeBox *NewBamgQuadtreeBox(void);
+			BamgVertex      *ToClose(BamgVertex &,double ,Icoor1,Icoor1);
+			void             Add(BamgVertex &w);
+	};
+}
+#endif
Index: /issm/trunk/src/c/classes/bamg/BamgVertex.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgVertex.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/BamgVertex.cpp	(revision 13395)
@@ -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{
+			_error_("Metrictype " << Metrictype << " not supported yet (use 0,1 or 2(default))");
+		}
+
+		//initialize metric Miv with ci*H
+		Metric Miv(Hxx*ci,Hyx*ci,Hyy*ci);
+
+		//Get eigen values and vectors of Miv
+		EigenMetric Vp(Miv);
+
+		//move eigen valuse to their absolute values
+		Vp.Abs();
+
+		//Apply a power if requested by user
+		if(power!=1.0) Vp.pow(power);
+
+		//modify eigen values according to hmin and hmax
+		Vp.Maxh(hmax);
+		Vp.Minh(hmin);
+
+		//Bound anisotropy by 1/(anisomax)^2
+		Vp.BoundAniso2(1/(anisomax*anisomax));
+
+		//rebuild Metric from Vp
+		Metric MVp(Vp);
+
+		//Apply Metric to vertex
+		m.IntersectWith(MVp);
+
+	}
+	/*}}}*/
+	/*FUNCTION BamgVertex::Optim {{{*/
+	long BamgVertex::Optim(int i,int koption){ 
+		long ret=0;
+		if ( t && (IndexInTriangle >= 0 ) && (IndexInTriangle <3) ){
+			ret = t->Optim(IndexInTriangle,koption);
+			if(!i){
+				t =0; // for no future optime 
+				IndexInTriangle= 0;
+			}
+		}
+		return ret;
+	}
+	/*}}}*/
+	/*FUNCTION BamgVertex::Smoothing{{{*/
+	double  BamgVertex::Smoothing(Mesh &Th,const Mesh &BTh,Triangle* &tstart ,double omega){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Smoothing)*/
+
+		register BamgVertex* s=this;
+		BamgVertex &vP = *s,vPsave=vP;
+
+		register Triangle* tbegin= t , *tria = t , *ttc;
+
+		register int k=0,kk=0,j = EdgesVertexTriangle[IndexInTriangle][0],jc;
+		R2 P(s->r),PNew(0,0);
+		do {
+			k++; 
+
+			if (!tria->Hidden(j)){
+				BamgVertex &vQ = (*tria)[VerticesOfTriangularEdge[j][0]]; 
+
+				R2 Q = vQ,QP(P-Q);
+				double lQP = LengthInterpole(vP,vQ,QP);
+				PNew += Q+QP/Max(lQP,1e-20);
+				kk ++;
+			}
+			ttc =  tria->TriangleAdj(j);
+			jc = NextEdge[tria->NuEdgeTriangleAdj(j)];
+			tria = ttc;
+			j = NextEdge[jc];
+			if (k>=2000){
+				_error_("k>=2000 (Maximum number of iterations reached)");
+			}
+		} while ( tbegin != tria); 
+		if (kk<4) return 0;
+		PNew = PNew/(double)kk;
+		R2 Xmove((PNew-P)*omega);
+		PNew = P+Xmove;
+		double delta=Norme2_2(Xmove); 
+
+		Icoor2 deta[3];
+		I2 IBTh  = BTh.R2ToI2(PNew);
+
+		tstart=BTh.TriangleFindFromCoord(IBTh,deta,tstart);  
+
+		if (tstart->det <0){ // outside
+			double ba,bb;
+			AdjacentTriangle edge= CloseBoundaryEdge(IBTh,tstart,ba,bb) ;
+			tstart = edge;
+			vP.m= Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1));
+		}
+		else { // inside
+			double   aa[3];
+			double s = deta[0]+deta[1]+deta[2];
+			aa[0]=deta[0]/s;
+			aa[1]=deta[1]/s;
+			aa[2]=deta[2]/s;
+			vP.m = Metric(aa,(*tstart)[0],(*tstart)[1],(*tstart)[2]);
+		}
+
+		// recompute the det of the triangle
+		vP.r = PNew;
+
+		vP.i = Th.R2ToI2(PNew);
+
+		BamgVertex vPnew = vP;
+
+		int ok=1;
+		int loop=1;
+		k=0;
+		while (ok){
+			ok =0;
+			do {
+				k++; 
+				double detold = tria->det;
+				tria->det =  bamg::det( (*tria)[0],(*tria)[1]  ,(*tria)[2]);
+				if (loop) {
+					BamgVertex *v0,*v1,*v2,*v3;
+					if (tria->det<0) ok =1;			       
+					else if (tria->Quadrangle(v0,v1,v2,v3))
+					  {
+						vP = vPsave;
+						double qold =QuadQuality(*v0,*v1,*v2,*v3);
+						vP = vPnew;
+						double qnew =QuadQuality(*v0,*v1,*v2,*v3);
+						if (qnew<qold) ok = 1;
+					  }
+					else if ( (double)tria->det < detold/2 ) ok=1;
+
+				}
+				tria->SetUnMarkUnSwap(0);
+				tria->SetUnMarkUnSwap(1);
+				tria->SetUnMarkUnSwap(2);
+				ttc =  tria->TriangleAdj(j);
+				jc = NextEdge[tria->NuEdgeTriangleAdj(j)];
+				tria = ttc;
+				j = NextEdge[jc];
+				if (k>=2000){
+					_error_("k>=2000");
+				}
+			}while ( tbegin != tria); 
+
+			if (ok && loop) vP=vPsave; // no move 
+			loop=0;
+		}
+		return delta;
+	}
+	/*}}}*/
+
+	/*Intermediary*/
+	/*FUNCTION QuadQuality{{{*/
+	double QuadQuality(const BamgVertex & a,const BamgVertex &b,const BamgVertex &c,const BamgVertex &d) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshQuad.cpp/QuadQuality)*/
+
+		// calcul de 4 angles --
+		R2 A((R2)a),B((R2)b),C((R2)c),D((R2)d);
+		R2 AB(B-A),BC(C-B),CD(D-C),DA(A-D);
+		//  Move(A),Line(B),Line(C),Line(D),Line(A);
+		const Metric & Ma  = a;
+		const Metric & Mb  = b;
+		const Metric & Mc  = c;
+		const Metric & Md  = d;
+
+		double lAB=Norme2(AB);
+		double lBC=Norme2(BC);
+		double lCD=Norme2(CD);
+		double lDA=Norme2(DA);
+		AB /= lAB;  BC /= lBC;  CD /= lCD;  DA /= lDA;
+		// version aniso 
+		double cosDAB= Ma(DA,AB)/(Ma(DA)*Ma(AB)),sinDAB= Det(DA,AB);
+		double cosABC= Mb(AB,BC)/(Mb(AB)*Mb(BC)),sinABC= Det(AB,BC);
+		double cosBCD= Mc(BC,CD)/(Mc(BC)*Mc(CD)),sinBCD= Det(BC,CD);
+		double cosCDA= Md(CD,DA)/(Md(CD)*Md(DA)),sinCDA= Det(CD,DA);
+		double sinmin=Min(Min(sinDAB,sinABC),Min(sinBCD,sinCDA));
+		if (sinmin<=0) return sinmin;
+		return 1.0-Max(Max(Abs(cosDAB),Abs(cosABC)),Max(Abs(cosBCD),Abs(cosCDA)));
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/classes/bamg/BamgVertex.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgVertex.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/BamgVertex.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/CrackedEdge.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/CrackedEdge.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/CrackedEdge.cpp	(revision 13395)
@@ -0,0 +1,33 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "CrackedEdge.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION CrackedEdge() {{{*/
+	CrackedEdge::CrackedEdge() {
+		a=NULL;
+		b=NULL;
+		E=NULL;
+		e1=NULL;
+		e2=NULL;
+		indexa[0]=-1;
+		indexa[1]=-1;
+		indexa[2]=-1;
+		indexb[0]=-1;
+		indexb[1]=-1;
+		indexb[2]=-1;
+		length=0;
+		normal.x=0;
+		normal.y=0;
+
+	}
+	/*}}}*/
+
+	/*Methods*/
+
+} 
Index: /issm/trunk/src/c/classes/bamg/CrackedEdge.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/CrackedEdge.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/CrackedEdge.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/Curve.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/Curve.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Curve.cpp	(revision 13395)
@@ -0,0 +1,37 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Curve.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION Curve::Curve(){{{*/
+	Curve::Curve(){
+		FirstEdge=NULL;
+		LastEdge=NULL;
+		FirstVertexIndex=0;
+		LastVertexIndex=0;
+	} 
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION Curve::Reverse {{{*/
+	void Curve::Reverse() {
+		/*reverse the direction of the curve */
+		Exchange(FirstEdge,LastEdge);
+		Exchange(FirstVertexIndex,LastVertexIndex);
+	}
+	/*}}}*/
+	/*FUNCTION Curve::Set {{{*/
+	void Curve::Set(const Curve & rec,const Geometry & Gh ,Geometry & GhNew){
+		*this = rec;
+		FirstEdge = GhNew.edges + Gh.GetId(FirstEdge);    
+		LastEdge = GhNew.edges + Gh.GetId(LastEdge); 
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/classes/bamg/Curve.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/Curve.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Curve.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/Direction.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/Direction.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Direction.cpp	(revision 13395)
@@ -0,0 +1,36 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "Direction.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION Direction() {{{*/
+	Direction::Direction():
+		dir(MaxICoor){
+
+	}/*}}}*/
+	/*FUNCTION Direction(Icoor1 i,Icoor1 j) {{{*/
+	Direction::Direction(Icoor1 i,Icoor1 j) {
+		Icoor2 n2 = 2*(Abs(i)+Abs(j));  
+		Icoor2 r  = MaxICoor* (Icoor2) i;
+		Icoor1 r1 = (Icoor1) (2*(r/ n2)); // odd number 
+		dir = (j>0) ? r1 : r1+1;          // odd-> j>0 even-> j<0
+	}/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION Direction::direction{{{*/
+	int Direction::direction(Icoor1 i,Icoor1 j) {
+		int r =1; 
+		if (dir!= MaxICoor) {
+			Icoor2 x(dir/2),y1(MaxICoor/2-Abs(x)),y(dir%2?-y1:y1);
+			r = (x*i + y*j) >=0;
+		}
+		return r;
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/classes/bamg/Direction.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/Direction.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Direction.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/DoubleAndInt.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/DoubleAndInt.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/DoubleAndInt.h	(revision 13395)
@@ -0,0 +1,19 @@
+#ifndef _DOUBLEANDINT_H_
+#define _DOUBLEANDINT_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	class DoubleAndInt {
+		//class used by Mesh::MakeQuadrangles
+
+		public:
+			double q;
+			long i3j;
+
+			//Operators
+			int operator<(DoubleAndInt a){return q > a.q;}
+	};
+}
+#endif
Index: /issm/trunk/src/c/classes/bamg/Edge.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/Edge.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Edge.cpp	(revision 13395)
@@ -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)){ _error_("Intersection bug"); }
+		_assert_(adj[0]==&e || adj[1]==&e);
+
+		return adj[0]==&e?0:1;
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/classes/bamg/Edge.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/Edge.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Edge.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/EigenMetric.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/EigenMetric.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/EigenMetric.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/GeomEdge.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/GeomEdge.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/GeomEdge.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/GeomEdge.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/GeomEdge.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/GeomEdge.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/GeomSubDomain.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/GeomSubDomain.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/GeomSubDomain.cpp	(revision 13395)
@@ -0,0 +1,20 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "GeomSubDomain.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+
+	/*Methods*/
+	/*FUNCTION GeomSubDomain::Set {{{*/
+	void GeomSubDomain::Set(const GeomSubDomain & rec,const Geometry & Gh ,const Geometry & GhNew){
+		*this = rec;
+		edge = Gh.GetId(edge) + GhNew.edges;
+	}/*}}}*/
+
+} 
Index: /issm/trunk/src/c/classes/bamg/GeomSubDomain.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/GeomSubDomain.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/GeomSubDomain.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/GeomVertex.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/GeomVertex.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/GeomVertex.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/GeomVertex.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/GeomVertex.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/GeomVertex.h	(revision 13395)
@@ -0,0 +1,30 @@
+#ifndef _GEOMETRICALVERTEX_H_
+#define _GEOMETRICALVERTEX_H_
+
+#include "./include.h"
+#include "BamgVertex.h"
+
+namespace bamg {
+
+	class Geometry;
+
+	class GeomVertex : public BamgVertex { 
+
+		public:
+			friend class Geometry;
+
+			int type;
+
+			//Constructors
+			GeomVertex():type(0){};
+
+			//Methods
+			int  Corner() const;
+			int  Required()const;
+			void SetCorner();
+			void SetRequired();
+
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/classes/bamg/Geometry.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/Geometry.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Geometry.cpp	(revision 13395)
@@ -0,0 +1,973 @@
+#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) _error_("the domain provided does not contain any vertex");
+		if (bamggeom->Edges==NULL) _error_("the domain provided does not contain any edge");
+
+		//Vertices
+		if (bamggeom->Vertices){
+			if(verbose>5) _printLine_("      processing Vertices");
+			if (bamggeom->VerticesSize[1]!=3) _error_("Vertices should have 3 columns");
+			vertices = new GeomVertex[nbv];
+			for (i=0;i<nbv;i++) {
+				vertices[i].r.x=(double)bamggeom->Vertices[i*3+0];
+				vertices[i].r.y=(double)bamggeom->Vertices[i*3+1];
+				vertices[i].ReferenceNumber=(long)bamggeom->Vertices[i*3+2];
+				vertices[i].DirOfSearch=NoDirOfSearch;
+				vertices[i].color =0;
+				vertices[i].type=0;
+			}
+			/*find domain extrema (pmin,pmax) that will define the square box used for by the quadtree*/
+			pmin =  vertices[0].r;
+			pmax =  vertices[0].r;
+			for (i=0;i<nbv;i++) {
+				pmin.x = Min(pmin.x,vertices[i].r.x);
+				pmin.y = Min(pmin.y,vertices[i].r.y);
+				pmax.x = Max(pmax.x,vertices[i].r.x);
+				pmax.y = Max(pmax.y,vertices[i].r.y);
+			}
+			/*Offset pmin and pmax to avoid round-off errors*/
+			R2 offset = (pmax-pmin)*0.05;
+			pmin -= offset;
+			pmax += offset;
+			/*coefIcoor is the coefficient used for integer coordinates:
+			 *                       (x-pmin.x)
+			 * Icoor x = (2^30 -1) ------------ 
+			 *                          D
+			 * where D is the longest side of the domain (direction x or y)
+			 * so that (x-pmin.x)/D is in ]0 1[
+			 *
+			 * coefIcoor = (2^30 -1)/D
+			 */
+			coefIcoor=(MaxICoor)/(Max(pmax.x-pmin.x,pmax.y-pmin.y));
+			if(coefIcoor<=0) _error_("coefIcoor should be positive");
+		}
+		else{
+			_error_("No BamgVertex provided");
+		}
+
+		//Edges
+		if (bamggeom->Edges){
+			R2      zerovector(0,0);
+			double* verticeslength=NULL;
+
+			if(verbose>5) _printLine_("      processing Edges");
+			if (bamggeom->EdgesSize[1]!=3) _error_("Edges should have 3 columns");
+			edges = new GeomEdge[nbe];
+
+			//initialize verticeslength (sum of the lengths of the edges holding vertex)
+			verticeslength = new double[nbv];
+			for(i=0;i<nbv;i++) verticeslength[i]=0;
+
+			/*Loop over the edges*/
+			for (i=0;i<nbe;i++){
+
+				i1=(int)bamggeom->Edges[i*3+0]-1; //-1 for C indexing
+				i2=(int)bamggeom->Edges[i*3+1]-1; //-1 for C indexing
+				edges[i].v[0]= vertices + i1;     //pointer toward vertex i1 (=&vertices[i1])
+				edges[i].v[1]= vertices + i2;     //pointer toward vertex i2
+				edges[i].ReferenceNumber=(long)bamggeom->Edges[i*3+2];
+
+				//get length of edge
+				R2     x12=vertices[i2].r-vertices[i1].r;
+				double l12=sqrt((x12,x12));
+				Hmin=Min(Hmin,l12);
+
+				//initialize other fields
+				edges[i].tg[0]=zerovector;
+				edges[i].tg[1]=zerovector;
+				edges[i].AdjVertexIndex[0] = edges[i].AdjVertexIndex[1] = -1;
+				edges[i].Adj[0] = edges[i].Adj[1] = NULL;
+				edges[i].type = 0;
+
+				//Cracked?
+				if (edges[i].ReferenceNumber!=1) edges[i].SetCracked();
+
+				//prepare metric
+				vertices[i1].color++;
+				vertices[i2].color++;
+				verticeslength[i1] += l12;
+				verticeslength[i2] += l12;
+			}
+
+			// definition the default of the given mesh size 
+			for (i=0;i<nbv;i++) {
+				if (vertices[i].color > 0) 
+				 vertices[i].m=Metric(verticeslength[i] /(double) vertices[i].color);
+				else 
+				 vertices[i].m=Metric(Hmin);
+			}
+			delete [] verticeslength;
+			
+		}
+		else{
+			_error_("No edges provided");
+		}
+
+		//hVertices
+		if(bamgopts->hVertices && bamgopts->hVerticesSize[0]==nbv){
+			if(verbose>5) _printLine_("      processing hVertices");
+			for (i=0;i< nbv;i++){
+				if (!xIsNan<IssmPDouble>(bamgopts->hVertices[i])){
+					vertices[i].m=Metric((double)bamgopts->hVertices[i]);
+				}
+			}
+		}
+
+		//MetricVertices
+		if(bamgopts->metric && bamgopts->metric[0]==nbv){
+			if(verbose>5) _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) _error_("TangentAtEdges should have 4 columns");
+			int n,i,j,k;
+			R2 tg;
+
+			n=bamggeom->TangentAtEdgesSize[0];
+			for (k=0;k<n;k++) {
+				i=(int)bamggeom->TangentAtEdges[k*4+0]-1; //for C indexing
+				j=(int)bamggeom->TangentAtEdges[k*4+1]-1; //for C indexing
+				tg.x=bamggeom->TangentAtEdges[k*4+2];
+				tg.y=bamggeom->TangentAtEdges[k*4+3];
+				if (i<0 || i>=nbe) _error_("TangentAtEdges first index exceeds matrix dimension");
+				if (j!=0 && j!=1)  _error_("TangentAtEdges second index should be 1 or 2 only");
+				edges[i].tg[j] = tg;
+			}
+		}
+
+		//Corners
+		if(bamggeom->Corners){
+			if(verbose>5) _printString_("      processing Corners");
+			if (bamggeom->CornersSize[1]!=1) _error_("Corners should have 1 column");
+			n=bamggeom->CornersSize[0];
+			for (i=0;i<n;i++) {     
+				j=(int)bamggeom->Corners[i]-1; //for C indexing
+				if (j>nbv-1 || j<0) _error_("Bad corner definition: should in [0 " << nbv << "]");
+				/*Required => at the same time SetRequired and SetCorner*/
+				vertices[j].SetCorner();
+				vertices[j].SetRequired();
+			}
+		}
+
+		//RequiredVertices
+		if(bamggeom->RequiredVertices){
+			if(verbose>5) _printLine_("      processing RequiredVertices");
+			if (bamggeom->RequiredVerticesSize[1]!=1) _error_("RequiredVertices should have 1 column");
+			n=bamggeom->RequiredVerticesSize[0];
+			for (i=0;i<n;i++) {     
+				j=(int)bamggeom->RequiredVertices[i]-1; //for C indexing
+				if (j>nbv-1 || j<0) _error_("Bad RequiredVerticess  definition: should in [0 " << nbv << "]");
+				vertices[j].SetRequired();
+			}
+		}
+
+		//RequiredEdges
+		if(bamggeom->RequiredEdges){
+			if(verbose>5) _printLine_("      processing RequiredEdges");
+			if (bamggeom->RequiredEdgesSize[1]!=1) _error_("RequiredEdges should have 1 column");
+			n=bamggeom->RequiredEdgesSize[0];
+			for (i=0;i<n;i++) {     
+				j=(int)bamggeom->RequiredEdges[i]-1; //for C indexing
+				if (j>nbe-1 || j<0) _error_("Bad RequiredEdges definition: should in [0 " << nbe << "]");
+				edges[j].SetRequired();  
+			}
+		}
+
+		//SubDomain
+		if(bamggeom->SubDomains){
+			if(verbose>5) _printLine_("      processing SubDomains");
+			if (bamggeom->SubDomainsSize[1]!=4) _error_("SubDomains should have 4 columns");
+			nbsubdomains=bamggeom->SubDomainsSize[0];
+			subdomains = new GeomSubDomain[nbsubdomains];
+			for (i=0;i<nbsubdomains;i++){
+				i0=(int)bamggeom->SubDomains[i*4+0];
+				i1=(int)bamggeom->SubDomains[i*4+1];
+				i2=(int)bamggeom->SubDomains[i*4+2];
+				i3=(int)bamggeom->SubDomains[i*4+3];
+				if (i0!=2) _error_("Bad Subdomain definition: first number should be 2 (for Edges)");
+				if (i1>nbe || i1<=0) _error_("Bad Subdomain definition: second number should in [1 " << nbe << "] (edge number)");
+				subdomains[i].edge=edges + (i1-1);
+				subdomains[i].direction = (int) i2;
+				subdomains[i].ReferenceNumber = i3;
+			}
+		}
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::WriteGeometry{{{*/
+	void Geometry::WriteGeometry(BamgGeom* bamggeom, BamgOpts* bamgopts){
+
+		int verbose;
+		int nbreq=0;
+		int nbreqv=0;
+		int nbtan=0;
+		int nbcracked=0;
+		int i,count;
+
+		/*Get options*/
+		verbose=bamgopts->verbose;
+
+		/*Vertices*/
+		if(verbose>5) _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);
+				_printLine_("Coords: ["<<v->r.x<<" "<<v->r.y<<"] ["<<vertices[i].r.x<<" "<<vertices[i].r.y<<"]");
+
+				delete [] next_p;
+				delete [] head_v;
+				delete [] eangle;
+				_error_("two points of the geometry are very closed to each other (see reference numbers above)");
+			}
+
+			/*Add vertices[i] to the quadtree*/
+			quadtree.Add(vertices[i]);
+		}
+
+		/* Here we use a powerful chaining algorithm
+		 *
+		 * 1. What is a chaining algorithm?
+		 *
+		 * If F is a function that goes from i in [0 n] to j in [0 m]
+		 * and we want to compute the reciprocal function F-1 of F
+		 * (what are the antecedents of a given j in Im(F) )
+		 * We use 2 lists:
+		 *    head_F[j] that holds the head of lists
+		 *    next_F[i] that holds the list of elements that have the same image
+		 *
+		 * Example:
+		 *    i1, i2, ..., ip in [0,n] are all antecedents of a given j in [0 m]
+		 *    head_F[j] = ip
+		 *    next_F[ip]= ip-1
+		 *    ....
+		 *    next_F[i2]= i1
+		 *    next_F[i1]= -1  //end of the list
+		 *
+		 * Algorithm:
+		 *    for(j=0;j<m;j++)  head_F[j] = -1 //initialization
+		 *    for(i=0;i<n;i++){
+		 *       j=F[i];
+		 *       next_F[i]= head_F[j];
+		 *       head_F[j]=i;
+		 *    }
+		 * 
+		 *    Then, we can go through all the elements that have for image j:
+		 *    for(i=head_F[j]; i!=-1; i=next_F[i])
+		 *    initialization of i by i=head_F[j]
+		 *    stop the loop when i=-1 (end of the chain)
+		 *    iterate using i=next_F[i] (next element that have for image j)
+		 * 
+		 * 2. How to use this algorithm here?
+		 * 
+		 * Here F is a function that associates two vertices v0 and v1 for a given edge E
+		 * We want to build the reciprocal function: what are the edges that contains
+		 * a vertex v?
+		 * To do so, we use the same chaining algorithm but there is a difficulty
+		 * coming from the fact that for F we have a couple of vertices and not one 
+		 * vertex.
+		 * To overcome this difficulty, we use a global indexing exactly like in 
+		 * C/C++ so that
+		 * a member of a 2-column-table can be described by one index p=i*2+j
+		 * i=(int)p/2 line number of p
+		 * j=p%2      column number of p
+		 *
+		 * Algorithm:
+		 *    for(i=0;i<nbv;i++)  head_v[i] = -1 //initialization
+		 *    for(i=0;i<nbe;i++){
+		 *       for(j=0;j<2;j++){
+		 *          p=2*i+j;
+		 *          v=edges(i,j);
+		 *          next_p[p]= head_v[v];
+		 *          head_v[v]=p;
+		 *       }
+		 *    }
+		 */
+
+		//initialize head_v as -1
+		for (i=0;i<nbv;i++) head_v[i]=-1;
+		k=0;
+		for (i=0;i<nbe;i++) {
+			//compute vector of edge i that goes from vertex 0 to vertex 1
+			R2 v10=edges[i].v[1]->r - edges[i].v[0]->r;
+			double lv10=Norme2(v10);
+			//check that its length is not 0
+			if(lv10==0){
+				delete [] next_p;
+				delete [] head_v;
+				delete [] eangle;
+				_error_("Length of edge " << i << " is 0");
+			}
+			//compute angle in [-Pi Pi]
+			eangle[i] = atan2(v10.y,v10.x);
+			//build chains head_v and next_p
+			for (j=0;j<2;j++){
+				long v=GetId(edges[i].v[j]);
+				next_p[k]=head_v[v];
+				head_v[v]=k++; //post increment: head_v[v]=k; and then k=k+1;
+			}
+		}
+
+		//sort head_v by order of increasing edges angle
+		for (i=0;i<nbv;i++) {
+			int exch=1,ord=0;      
+
+			//exchange vertices position in head_v and next_p till tey are sorted
+			while (exch){
+				long *p=head_v+i;               
+				long *po=p;                     
+				long  n=*p;                     
+				register float angleold=-1000 ; // angle = - infinity
+				ord=0; exch=0;
+
+				// loop over the edges that contain the vertex i (till -1)
+				while (n >=0){
+					ord++;
+					long  i1=n/2;       // i1 = floor (n/2)      -> Edge number
+					long  j1=n%2;       // j1 = 1 if n is odd    -> Vertex index for this edge (0 or 1)
+					long* pn=next_p+n;
+
+					//Next vertex index
+					n=*pn;                       
+
+					//compute angle between horizontal axis and v0->v1
+					float angle = j1 ? OppositeAngle(eangle[i1]):  eangle[i1]; 
+
+					//exchange if the current edge angle is smaller than the previous one
+					if (angleold > angle){
+						exch=1;
+						*pn=*po;  // next_p[n] = n + 1
+						*po=*p;   // 
+						*p=n;     // next_p[n+1] = n
+						po=pn;    // po now point toward pn (invert next and current)
+					}
+
+					//else, continue going to the next edge position
+					else{                        //  to have : po -> p -> pn
+						angleold=angle; // update maximum angle
+						po=p;           // po now point toward p  (current position)
+						p=pn;           // p  now point toward pn (next position)
+					}
+				}
+			}
+
+			// angular test on current vertex to guess whether it is a corner (ord = number of edges holding i)
+			if(ord==2) { 
+				long  n1 = head_v[i];
+				long  n2 = next_p[n1];
+				long  i1 = n1/2, i2 = n2/2; // edge number
+				long  j1 = n1%2, j2 = n2%2; // vertex in the edge 
+				float angle1=  j1 ? OppositeAngle(eangle[i1]) : eangle[i1];
+				float angle2= !j2 ? OppositeAngle(eangle[i2]) : eangle[i2];
+				float da12 = Abs(angle2-angle1);
+				if (( da12 >= MaxCornerAngle ) && (da12 <= 2*Pi -MaxCornerAngle)) {
+					vertices[i].SetCorner() ; 
+				}
+				// if the edge type/referencenumber a changing then is SetRequired();
+				if (edges[i1].type != edges[i2].type || edges[i1].Required()){
+					vertices[i].SetRequired();
+				}
+				if (edges[i1].ReferenceNumber != edges[i2].ReferenceNumber) {
+					vertices[i].SetRequired();
+				}
+			}
+			if(ord != 2) {
+				vertices[i].SetCorner();
+			}
+
+			/*close the list around the vertex to have a circular loop*/
+			long no=-1, ne = head_v[i];
+			while (ne >=0) ne = next_p[no=ne];        
+			if(no>=0) next_p[no] = head_v[i];
+		}
+
+		/*Check that the list makes sense (we have all the time the same vertex)
+		 * and build adjacent edges*/
+		k =0;
+		for (i=0;i<nbe;i++){
+			for (j=0;j<2;j++){
+
+				long n1 = next_p[k++]; 
+				long i1 = n1/2 ,j1=n1%2;
+
+				if( edges[i1].v[j1] != edges[i].v[j]) _error_("Problem while processing edges: check the edge list");
+
+				edges[i1].Adj[j1] = edges + i;
+				edges[i1].AdjVertexIndex[j1] = j;
+			}
+		}
+
+		/* generation of  all the tangents*/
+		for (i=0;i<nbe;i++) {
+			R2    AB =edges[i].v[1]->r -edges[i].v[0]->r;// AB = vertex0 -> vertex1
+			double lAB=Norme2(AB);                       // Get length of AB
+			double ltg2[2]={0.0};                        // initialize tangent
+
+			//loop over the 2 vertices of the edge
+			for (j=0;j<2;j++) {
+				R2     tg =edges[i].tg[j];
+				double ltg=Norme2(tg);
+
+				//by default, tangent=[0 0]
+				if(ltg==0){
+					//if the current vertex of the edge is not a corner
+					if(!edges[i].v[j]->Corner()){
+						/*The tangent is set as the vector between the
+						 * previous and next vertices connected to current vertex
+						 * normed by the edge length*/
+						tg = edges[i].v[1-j]->r - edges[i].Adj[j]->v[1-edges[i].AdjVertexIndex[j]]->r;
+						ltg= Norme2(tg);
+						tg = tg *(lAB/ltg);
+						ltg= lAB;
+					}
+					//else:  a Corner no tangent => nothing to do    
+				}
+				else{
+					//tangent has already been computed
+					tg = tg*(lAB/ltg),ltg=lAB;
+				}
+
+				ltg2[j] = ltg;
+
+				if ((tg,AB)<0) tg = -tg;
+
+				edges[i].tg[j]=tg;
+			}
+			if (ltg2[0]!=0) edges[i].SetTgA();
+			if (ltg2[1]!=0) edges[i].SetTgB();
+		} 
+
+		/* generation of  all curves (from corner to corner)*/
+		/*We proceed in 2 steps: first allocate, second build*/
+		for (int step=0;step<2;step++){
+
+			//unmark all edges
+			for (i=0;i<nbe;i++) edges[i].SetUnMark();
+			long  nb_marked_edges=0;
+
+			//initialize number of curves
+			nbcurves = 0;
+
+			for (int level=0;level<2 && nb_marked_edges!=nbe;level++){
+				for (i=0;i<nbe;i++){
+
+					GeomEdge & ei=edges[i];   
+					for(j=0;j<2;j++){
+						/*If current edge ei is unmarked and (level=1 or vertex i is required (corner)):
+						 * we do have the first edge of a new curve*/
+						if (!ei.Mark() && (level || ei[j].Required())) { 
+							int k0=j,k1;
+							GeomEdge   *e=&ei;
+							GeomVertex *a=(*e)(k0); // begin 
+							if(curves){
+								curves[nbcurves].FirstEdge=e;
+								curves[nbcurves].FirstVertexIndex=k0;
+							}
+							int nee=0;
+							for(;;){ 
+								nee++;
+								k1 = 1-k0; // next vertex of the edge 
+								e->SetMark();
+								nb_marked_edges++;
+								e->CurveNumber=nbcurves;
+								GeomVertex *b=(*e)(k1);
+
+								//break if we have reached the other end of the curve
+								if (a==b || b->Required()){
+									if(curves){
+										curves[nbcurves].LastEdge=e;
+										curves[nbcurves].LastVertexIndex=k1;
+									}
+									break;
+								}
+								//else: go to next edge (adjacent)
+								else{
+									k0 = e->AdjVertexIndex[k1];//  vertex in next edge
+									e  = e->Adj[k1]; // next edge
+								}
+							}
+							nbcurves++;
+							if(level) a->SetRequired();
+						}
+					}
+				} 
+			}
+			_assert_(nb_marked_edges && nbe);
+			//allocate if first step
+			if(step==0) curves=new Curve[nbcurves];
+		} 
+
+		/*clean up*/
+		delete [] next_p;
+		delete [] head_v;
+		delete [] eangle;
+
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::ProjectOnCurve {{{*/
+	GeomEdge* Geometry::ProjectOnCurve(const Edge &e,double s,BamgVertex &V,VertexOnGeom &GV) const {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/ProjectOnCurve)*/
+		/*Add a vertex on an existing geometrical edge according to the metrics of the two vertices constituting the edge*/
+
+		double save_s=s;
+		int NbTry=0;
+
+retry:
+
+		s=save_s;
+		GeomEdge* on=e.GeomEdgeHook;
+		if (!on){
+			_error_("ProjectOnCurve error message: edge provided should be on geometry");
+		}
+		if (!e[0].GeomEdgeHook ||  !e[1].GeomEdgeHook){
+			_error_("ProjectOnCurve error message: at least one of the vertex of the edge provided is not on geometry");
+		}
+
+		//Get the two vertices of the edge
+		const BamgVertex &v0=e[0];
+		const BamgVertex &v1=e[1];
+
+		//Get position of V0, V1 and vector v0->v1
+		R2 V0=v0,V1=v1,V01=V1-V0;
+
+		//Get geometrical vertices corresponding to v0 and v1
+		VertexOnGeom  vg0=*v0.GeomEdgeHook,  vg1=*v1.GeomEdgeHook;
+
+		//build two pointers towrad current geometrical edge
+		GeomEdge *eg0=on, *eg1=on;
+
+		//Get edge direction and swap v0 and v1 if necessary
+		R2 Ag=(R2)(*on)[0],Bg=(R2)(*on)[1],AB=Bg-Ag; 
+		int OppositeSens = (V01,AB)<0;
+		int direction0=0,direction1=1;
+		if (OppositeSens) s=1-s,Exchange(vg0,vg1),Exchange(V0,V1);
+
+		//Compute metric of new vertex as a linear interpolation of the two others
+		V.m=Metric(1.0-s,v0,s,v1);
+
+		const int mxe=100;
+		GeomEdge* ge[mxe+1];
+		int     directionge[mxe+1];
+		double  lge[mxe+1];
+		int bge=mxe/2,tge=bge;
+		ge[bge] = e.GeomEdgeHook;
+		directionge[bge]=1;
+
+		while (eg0!=(GeomEdge*)vg0 && (*eg0)(direction0)!=(GeomVertex*)vg0){ 
+			if (bge<=0) {
+				if(NbTry) {
+					_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)");
+					_error_("see above");
+				}
+				NbTry++;
+				goto retry;
+			}
+			GeomEdge* tmpge = eg0;
+			ge[--bge] =eg0 = eg0->Adj[direction0];
+			_assert_(bge>=0 && bge<=mxe);
+			direction0 = 1-( directionge[bge] = tmpge->AdjVertexIndex[direction0]);
+		}
+		while (eg1 != (GeomEdge*) vg1  &&  (*eg1)(direction1) != (GeomVertex*) vg1) { 
+			if(tge>=mxe ) { 
+				_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)");
+				_error_("see above");
+			}
+			GeomEdge* tmpge = eg1;
+			ge[++tge] =eg1 = eg1->Adj[direction1];
+			directionge[tge]= direction1 = 1-tmpge->AdjVertexIndex[direction1];
+			_assert_(tge>=0 && tge<=mxe);
+		}
+
+
+		if ((*eg0)(direction0)==(GeomVertex*)vg0)
+		 vg0=VertexOnGeom(*(BamgVertex*) vg0,*eg0,direction0); //vg0 = absisce
+
+		if ((*eg1)(direction1)==(GeomVertex*)vg1)
+		 vg1=VertexOnGeom(*(BamgVertex*) vg1,*eg1,direction1);
+
+		double sg;
+		if (eg0 == eg1) { 
+			register double s0=vg0,s1=vg1;
+			sg =  s0*(1.0-s) +  s*s1;
+			on=eg0;
+		}
+		else {
+			R2 AA=V0,BB;
+			double s0,s1;
+			int i=bge;
+			double ll=0;
+			for(i=bge;i<tge;i++){
+				_assert_(i>=0 && i<=mxe);
+				BB =  (*ge[i])[directionge[i]];
+				lge[i]=ll += Norme2(AA-BB);
+				AA=BB ;}
+				lge[tge]=ll+=Norme2(AA-V1); 
+				// search the geometrical edge
+				_assert_(s<=1.0);
+				double ls= s*ll;
+				on =0;
+				s0 = vg0;
+				s1= directionge[bge];
+				double l0=0,l1;
+				i=bge;
+				while (  (l1=lge[i]) < ls ) {
+					_assert_(i>=0 && i<=mxe);
+					i++,s0=1-(s1=directionge[i]),l0=l1;
+				}
+				on=ge[i];
+				if (i==tge) 
+				 s1=vg1;
+
+				s  =(ls-l0)/(l1-l0);
+				sg =s0*(1.0-s)+s*s1;    
+		} 
+		_assert_(on);
+		V.r= on->F(sg);
+		GV=VertexOnGeom(V,*on,sg);
+		return on;
+	}
+	/*}}}*/
+	/*FUNCTION Geometry::R2ToI2{{{*/
+	I2 Geometry::R2ToI2(const R2 & P) const {
+		/*coefIcoor is the coefficient used for integer coordinates:
+		 *                       (x-pmin.x)
+		 * Icoor x = (2^30 -1) ------------ 
+		 *                          D
+		 * where D is the longest side of the domain (direction x or y)
+		 * so that (x-pmin.x)/D is in ]0 1[
+		 *
+		 * coefIcoor = (2^30 -1)/D
+		 */
+		return  I2( (Icoor1) (coefIcoor*(P.x-pmin.x)) ,(Icoor1) (coefIcoor*(P.y-pmin.y)) );
+	}/*}}}*/
+	/*FUNCTION Geometry::UnMarkEdges{{{*/
+	void Geometry::UnMarkEdges() {
+		for (int i=0;i<nbe;i++) edges[i].SetUnMark();
+	}/*}}}*/
+} 
Index: /issm/trunk/src/c/classes/bamg/Geometry.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/Geometry.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Geometry.h	(revision 13395)
@@ -0,0 +1,68 @@
+#ifndef _GEOMETRY_H_
+#define _GEOMETRY_H_
+
+#include "./include.h"
+#include "./BamgGeom.h"
+#include "./BamgOpts.h"
+#include "./GeomVertex.h"
+#include "./GeomEdge.h"
+#include "./Curve.h"
+
+namespace bamg {
+
+	class Triangle;
+	class BamgQuadtree;
+	class GeomSubDomain;
+	class Edge;
+
+	class Geometry { 
+
+		public:
+
+			long           NbRef;                 // counter of ref on the this class if 0 we can delete
+			long           nbv;                   // number of vertices
+			long           nbe;                   // number of edges
+			long           nbsubdomains;
+			long           nbcurves;
+			GeomVertex    *vertices;
+			GeomEdge      *edges;
+			BamgQuadtree  *quadtree;
+			GeomSubDomain *subdomains;
+			Curve         *curves;
+			R2             pmin,pmax;             // domain extrema coordinates
+			double         coefIcoor;             // coef to integer Icoor1;
+			double         MaxCornerAngle;
+
+			//Constructor/Destructors
+			~Geometry(); 
+			Geometry();
+			Geometry(const Geometry & Gh);
+			Geometry(BamgGeom* bamggeom, BamgOpts* bamgopts);
+
+			//Operators
+			const GeomVertex &operator[](long i) const { return vertices[i]; };
+			GeomVertex       &operator[](long i) { return vertices[i];       };
+			const GeomEdge   &operator()(long i) const { return edges[i];    };
+			GeomEdge         &operator()(long  i) { return edges[i];         };
+
+			//Methods
+			void             Echo();
+			I2               R2ToI2(const R2 &P) const;
+			double           MinimalHmin();
+			double           MaximalHmax();
+			void             ReadGeometry(BamgGeom *bamggeom, BamgOpts*bamgopts);
+			void             Init(void);
+			void             PostRead();
+			long             GetId(const GeomVertex &t) const;
+			long             GetId(const GeomVertex *t) const;
+			long             GetId(const GeomEdge &t) const;
+			long             GetId(const GeomEdge *t) const;
+			long             GetId(const Curve *c) const;
+			void             UnMarkEdges();
+			GeomEdge *ProjectOnCurve(const Edge &,double,BamgVertex &,VertexOnGeom &) const;
+			GeomEdge *Containing(const R2 P, GeomEdge *start) const;
+			void             WriteGeometry(BamgGeom *bamggeom, BamgOpts*bamgopts);
+	};
+	
+}
+#endif
Index: /issm/trunk/src/c/classes/bamg/ListofIntersectionTriangles.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/ListofIntersectionTriangles.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/ListofIntersectionTriangles.cpp	(revision 13395)
@@ -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){
+			_error_("Size<=0");
+		}
+
+		Metric Mx,My;
+		int ii,jj;
+		R2 x,y,xy;
+
+		SegInterpolation* SegI=lSegsI;
+		SegI=lSegsI;
+		lSegsI[NbSeg].last=Size;
+		int EndSeg=Size;
+
+		y = lIntTria[0].x;
+		double sxy, s = 0;
+		lIntTria[0].s =0;
+		SegI->lBegin=s;
+
+		for (jj=0,ii=1;ii<Size;jj=ii++) {  
+			// seg jj,ii
+			x  = y;
+			y  = lIntTria[ii].x;
+			xy = y-x;
+			Mx = lIntTria[ii].m;
+			My = lIntTria[jj].m;
+			sxy= LengthInterpole(Mx,My,xy);
+			s += sxy;
+			lIntTria[ii].s = s;
+			if (ii == EndSeg){
+				SegI->lEnd=s;
+				SegI++;
+				EndSeg=SegI->last;
+				SegI->lBegin=s;
+			}
+		}
+		len = s;
+		SegI->lEnd=s;
+
+		return s;
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::NewItem(Triangle * tt,double d0,double d1,double d2) {{{*/
+	int  ListofIntersectionTriangles::NewItem(Triangle * tt,double d0,double d1,double d2) { 
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewItem)*/
+
+		register int n;
+		R2 x(0,0);
+		if ( d0) x =      (*tt)[0].r * d0;
+		if ( d1) x = x +  (*tt)[1].r * d1;
+		if ( d2) x = x +  (*tt)[2].r * d2;
+		// newer add same point 
+		if(!Size ||  Norme2_2(lIntTria[Size-1].x-x)) {
+			if (Size==MaxSize) ReShape();
+			lIntTria[Size].t=tt;
+			lIntTria[Size].bary[0]=d0;
+			lIntTria[Size].bary[1]=d1;
+			lIntTria[Size].bary[2]=d2;
+			lIntTria[Size].x = x;
+			Metric m0,m1,m2;
+			register BamgVertex * v;
+			if ((v=(*tt)(0))) m0    = v->m;
+			if ((v=(*tt)(1))) m1    = v->m;
+			if ((v=(*tt)(2))) m2    = v->m;
+			lIntTria[Size].m =  Metric(lIntTria[Size].bary,m0,m1,m2);
+			n=Size++;}
+		else n=Size-1;
+		return n;
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::NewItem(R2 A,const Metric & mm){{{*/
+	int ListofIntersectionTriangles::NewItem(R2 A,const Metric & mm) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewItem)*/
+
+		register int n;
+		if(!Size ||  Norme2_2(lIntTria[Size-1].x-A)) {
+			if (Size==MaxSize) ReShape();
+			lIntTria[Size].t=0;
+			lIntTria[Size].x=A;
+			lIntTria[Size].m=mm;
+			n=Size++;
+		}
+		else  n=Size-1;
+		return  n; 
+	}
+	/*}}}*/
+	/*FUNCTION ListofIntersectionTriangles::NewPoints{{{*/
+	long ListofIntersectionTriangles::NewPoints(BamgVertex* vertices,long &nbv,long maxnbv){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/NewPoints)*/
+
+		//If length<1.5, do nothing
+		double s=Length();
+		if (s<1.5) return 0;
+
+		const long nbvold=nbv;
+		int ii = 1 ;
+		R2 y,x;
+		Metric My,Mx ;
+		double sx =0,sy;
+		int nbi=Max(2,(int) (s+0.5));
+		double sint=s/nbi;
+		double si  =sint;
+
+		int EndSeg=Size;
+		SegInterpolation* SegI=NULL;
+		if (NbSeg) SegI=lSegsI,EndSeg=SegI->last;
+
+		for (int k=1;k<nbi;k++){
+			while ((ii < Size) && ( lIntTria[ii].s <= si )){
+				if (ii++ == EndSeg){
+					SegI++;
+					EndSeg=SegI->last;
+				}
+			}
+
+			int ii1=ii-1;
+			x  =lIntTria[ii1].x;
+			sx =lIntTria[ii1].s;
+			Metric Mx=lIntTria[ii1].m;
+			y  =lIntTria[ii].x;
+			sy =lIntTria[ii].s;
+			Metric My=lIntTria[ii].m;
+			double lxy = sy-sx;
+			double cy = abscisseInterpole(Mx,My,y-x,(si-sx)/lxy);
+
+			R2 C;
+			double cx = 1-cy;
+			C = SegI ? SegI->F(si): x * cx + y *cy;
+			//C.Echo();
+			//x.Echo();
+			//y.Echo();
+			//_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){
+					_error_("k<0");
+				}
+				ocut = OppositeEdge[k];
+				i=VerticesOfTriangularEdge[ocut][0];
+				j=VerticesOfTriangularEdge[ocut][1];
+				vi=(*t)[i];
+				vj=(*t)[j];
+				deti = bamg::det(a,b,vi);
+				detj = bamg::det(a,b,vj);
+				if (deti>0) // go to  i direction on gamma
+				 ocut = PreviousEdge[ocut];      
+				else if (detj<=0) // go to j direction on gamma
+				 ocut = NextEdge[ocut];         
+				AdjacentTriangle tadj =t->Adj(ocut);
+				t = tadj;
+				iedge= tadj; 
+				if (t == tbegin) { // 
+					double ba,bb;
+					long int verbose=2;
+					AdjacentTriangle edge=CloseBoundaryEdge(a,t,ba,bb);
+					BamgVertex & v0 = *edge.EdgeVertex(0), & v1 = *edge.EdgeVertex(1);
+					NewItem(A,Metric(ba,v0,bb,v1));
+					return;
+				}
+			} //  end while (t->det <0)
+			// theoriticaly we have: deti =<0 and detj>0
+
+			// computation of barycentric coor
+			// test if the point b is on size on t
+			// we revert vi,vj because vi,vj is def in Adj triangle
+			if ( det(vi,vj,b)>=0) {
+				t=tbegin;
+				double ba,bb;
+				AdjacentTriangle edge=CloseBoundaryEdge(b,t,ba,bb);
+				NewItem(B,Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1)));
+				return;
+			}
+			else
+			  {
+				k = OppositeVertex[iedge];
+				i=VerticesOfTriangularEdge[iedge][0];
+				j=VerticesOfTriangularEdge[iedge][1];
+				double dij = detj-deti;
+				if (i+j+k != 0 + 1 +2){
+					_error_("i+j+k != 0 + 1 +2");
+				}
+				ba[j] =  detj/dij;
+				ba[i] = -deti/dij;
+				ba[k] = 0;
+				ilast=NewItem(t,ba[0],ba[1],ba[2]); }
+		}  //  outside departure
+
+
+
+		// recherche the intersection of [a,b] with Bh Mesh.
+		// we know  a triangle ta contening the vertex a
+		// we have 2 case for intersection [a,b] with a edge [A,B] of Bh
+		// 1) the intersection point is in ]A,B[
+		// 2)                        is A or B
+		// first version --- 
+		for (;;) {
+			//    t->Draw();
+			if (iedge < 0) {
+				i0 =0;i1=1;i2=2;
+				dt[0] =bamg::det(a,b,(*t)[0]);
+				dt[1] =bamg::det(a,b,(*t)[1]);
+				dt[2] =bamg::det(a,b,(*t)[2]);}
+			else {
+				i2 = iedge;
+				i0 = NextEdge[i2];
+				i1 = NextEdge[i0]; 
+				dt[VerticesOfTriangularEdge[iedge][0]] = detj;// we revert i,j because
+				dt[VerticesOfTriangularEdge[iedge][1]] = deti;// we take the Triangle by the other side
+				dt[iedge] = det(a,b,(*t)[OppositeVertex[iedge]]);}
+
+				// so we have just to see the transition from - to + of the det0..2 on edge of t
+				// because we are going from a to b
+				if       ((dt[i=VerticesOfTriangularEdge[i0][0]] <  0) &&
+							( dt[j=VerticesOfTriangularEdge[i0][1]] > 0))
+				 ocut =i0;
+				else  if ((dt[i=VerticesOfTriangularEdge[i1][0]] <  0) &&
+							(dt[j=VerticesOfTriangularEdge[i1][1]] >  0))
+				 ocut =i1;
+				else  if ((dt[i=VerticesOfTriangularEdge[i2][0]] <  0) && 
+							(dt[j=VerticesOfTriangularEdge[i2][1]] >  0))
+				 ocut =i2;
+				else if   ((dt[i=VerticesOfTriangularEdge[i0][0]] == 0) &&
+							( dt[j=VerticesOfTriangularEdge[i0][1]] >  0))
+				 ocut =i0;
+				else  if ((dt[i=VerticesOfTriangularEdge[i1][0]] == 0) &&
+							(dt[j=VerticesOfTriangularEdge[i1][1]] >  0))
+				 ocut =i1;
+				else  if ((dt[i=VerticesOfTriangularEdge[i2][0]] == 0) && 
+							(dt[j=VerticesOfTriangularEdge[i2][1]] >  0))
+				 ocut =i2;
+				else if   ((dt[i=VerticesOfTriangularEdge[i0][0]] <  0) &&
+							( dt[j=VerticesOfTriangularEdge[i0][1]] == 0))
+				 ocut =i0;
+				else  if ((dt[i=VerticesOfTriangularEdge[i1][0]] <  0) &&
+							(dt[j=VerticesOfTriangularEdge[i1][1]] == 0))
+				 ocut =i1;
+				else  if ((dt[i=VerticesOfTriangularEdge[i2][0]] <  0) && 
+							(dt[j=VerticesOfTriangularEdge[i2][1]] == 0))
+				 ocut =i2;
+				else { //  On a edge (2 zero)
+					k =0;
+					if (dt[0]) ocut=0,k++; 
+					if (dt[1]) ocut=1,k++; 
+					if (dt[2]) ocut=2,k++;
+					if(k == 1) {
+						if (dt[ocut] >0) // triangle upper AB
+						 ocut = NextEdge[ocut];
+						i= VerticesOfTriangularEdge[ocut][0];
+						j= VerticesOfTriangularEdge[ocut][1];
+					}
+					else {
+						_error_("Bug Split Edge");
+					}
+				}
+
+				k = OppositeVertex[ocut];
+
+				Icoor2 detbij = bamg::det((*t)[i],(*t)[j],b);
+
+
+				if (detbij >= 0) { //we find the triangle contening b
+					dt[0]=bamg::det((*t)[1],(*t)[2],b);
+					dt[1]=bamg::det((*t)[2],(*t)[0],b);
+					dt[2]=bamg::det((*t)[0],(*t)[1],b);
+					double dd = t->det;
+					NewItem(t,dt[0]/dd,dt[1]/dd,dt[2]/dd);      
+					return ;}
+				else { // next triangle by  adjacent by edge ocut 
+					deti = dt[i];
+					detj = dt[j];
+					double dij = detj-deti;
+					ba[i] =  detj/dij;
+					ba[j] = -deti/dij;
+					ba[3-i-j ] = 0;
+					ilast=NewItem(t, ba[0],ba[1],ba[2]);      
+
+					AdjacentTriangle ta =t->Adj(ocut);
+					t = ta;
+					iedge= ta; 
+					if (t->det <= 0)  {
+						double ba,bb;
+						AdjacentTriangle edge=CloseBoundaryEdge(b,t,ba,bb);
+						NewItem(B,Metric(ba,*edge.EdgeVertex(0),bb,*edge.EdgeVertex(1)));
+						return;
+					}
+				}// we  go outside of omega 
+		} // for(;;)
+	}
+	/*}}}*/
+
+}
Index: /issm/trunk/src/c/classes/bamg/ListofIntersectionTriangles.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/ListofIntersectionTriangles.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/ListofIntersectionTriangles.h	(revision 13395)
@@ -0,0 +1,73 @@
+#ifndef _LISTOFINTERSECTIONTRIANGLES_H_
+#define _LISTOFINTERSECTIONTRIANGLES_H_
+
+#include "./include.h"
+
+namespace bamg {
+
+	class Triangle;
+
+	class ListofIntersectionTriangles {
+
+		class IntersectionTriangles {
+
+			public: 
+				Triangle *t;
+				double    bary[3];   // use if t != 0
+				R2        x;
+				Metric    m;
+				double    s;         // curvilinear coordinate
+				double    sp;        // length of the previous segment in m
+				double    sn;        // length of the next segment in m
+		};
+
+		class SegInterpolation {
+
+			public:
+				GeomEdge *e;
+				double           sBegin  ,sEnd; // abscisse of the seg on edge parameter
+				double           lBegin  ,lEnd; // length abscisse set in ListofIntersectionTriangles::Length
+				int              last;          // last index in ListofIntersectionTriangles for this Sub seg of edge
+
+				//Methods
+				R2 F(double s){ 
+					double c01=lEnd-lBegin, c0=(lEnd-s)/c01, c1=(s-lBegin)/c01;
+					if (lBegin>s || s>lEnd){
+						_error_("lBegin>s || s>lEnd");
+					}
+					return e->F(sBegin*c0+sEnd*c1);
+				}
+		};
+
+		public:
+
+			int                    MaxSize;
+			int                    Size;
+			double                 len;
+			int                    state;
+			IntersectionTriangles *lIntTria;
+			int                    NbSeg;
+			int                    MaxNbSeg;
+			SegInterpolation      *lSegsI;
+
+			//Constructors/Destructors
+			ListofIntersectionTriangles(int n=256,int m=16);
+			~ListofIntersectionTriangles();
+
+			//Operators
+			IntersectionTriangles & operator[](int i) {return lIntTria[i];}
+			operator int&() {return Size;}
+
+			//Methods
+			void   Init();
+			int    NewItem(Triangle *tt,double d0,double d1,double d2);
+			int    NewItem(R2 ,const Metric &);
+			void   SplitEdge(const Mesh &,const R2 &,const R2 &,int nbegin=0);
+			double Length();
+			long   NewPoints(BamgVertex *,long &nbv,long maxnbv);
+			void   NewSubSeg(GeomEdge *e,double s0,double s1);
+			void   ReShape();
+	};
+
+}
+#endif
Index: /issm/trunk/src/c/classes/bamg/Mesh.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/Mesh.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Mesh.cpp	(revision 13395)
@@ -0,0 +1,5856 @@
+#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;
+			  _error_("imaxnbv != nbv");
+		  }
+		  for (i=0;i<Tho.nbt;i++)
+			if(  reft[i] >=0 && flag[i]) 
+			  {
+				const Triangle & t = Tho.triangles[i];
+				int i0 = Tho.GetId(t[0]);
+				int i1 = Tho.GetId(t[1]);
+				int i2 = Tho.GetId(t[2]);
+				if (i0<0 || i1<0 || i2<0){
+					delete [] refv;
+					_error_("i0<0 || i1<0 || i2< 0");
+				}
+				if (i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv){
+					_error_("i0>=Tho.nbv || i1>=Tho.nbv || i2>=Tho.nbv");
+				}
+				triangles[nbt] = Triangle(this,kk[i0],kk[i1],kk[i2]);
+				triangles[nbt].color = Tho.subdomains[reft[i]].ReferenceNumber; 
+				nbt++;           
+			  }
+		  if (kt!=nbt){
+			  _error_("kt!=nbt");
+		  }
+		  if (nbt==0 && nbv==0) {
+			  _error_("All triangles have been removed");
+		  }
+		  delete [] kk;
+		  delete [] reft;
+		  delete [] refv;
+		  //double cutoffradian = 10.0/180.0*Pi;
+		  BuildGeometryFromMesh(bamgopts);
+		  Gh.PostRead(); 
+		  SetIntCoor();
+		  ReconstructExistingMesh();
+
+		  if (!nbsubdomains){
+			  _error_("nbsubdomains==0");
+		  }
+		  if (!subdomains[0].head || !subdomains[0].head->link){
+			  _error_("!subdomains[0].head || !subdomains[0].head->link");
+		  }
+
+	  }
+	/*}}}*/
+	/*FUNCTION Mesh::Mesh(Mesh & Th,Geometry * pGh,Mesh * pBth,long maxnbv_in) COPY{{{*/
+	Mesh::Mesh(Mesh & Th,Geometry * pGh,Mesh * pBth,long maxnbv_in)
+	  : Gh(*(pGh?pGh:&Th.Gh)), BTh(*(pBth?pBth:this)) {
+		  /*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Triangles)*/
+		  Gh.NbRef++;
+		  maxnbv_in = Max(maxnbv_in,Th.nbv); 
+		  long i;
+		  // do all the allocation to be sure all the pointer existe
+
+		  Init(maxnbv_in);// to make the allocation 
+		  // copy of triangles
+		  nbv = Th.nbv;
+		  nbt = Th.nbt;
+		  nbe = Th.nbe;
+		  nbsubdomains = Th.nbsubdomains;
+		  nbtout = Th.nbtout;
+		  nbq =  Th.nbq ;
+		  NbVerticesOnGeomVertex = Th.NbVerticesOnGeomVertex;
+		  if(NbVerticesOnGeomVertex)
+			VerticesOnGeomVertex = new VertexOnGeom[NbVerticesOnGeomVertex];
+		  NbVerticesOnGeomEdge = Th.NbVerticesOnGeomEdge;
+		  if (NbVerticesOnGeomEdge)
+			VerticesOnGeomEdge = new VertexOnGeom[NbVerticesOnGeomEdge] ;
+		  if (& BTh == & Th.BTh){ // same background 
+			  BTh.NbRef++;
+			  NbVertexOnBThVertex = Th.NbVertexOnBThVertex;
+			  if(NbVertexOnBThVertex)
+				VertexOnBThVertex = new VertexOnVertex[NbVertexOnBThVertex];
+			  NbVertexOnBThEdge = Th.NbVertexOnBThEdge;
+			  if(NbVertexOnBThEdge)
+				VertexOnBThEdge = new VertexOnEdge[NbVertexOnBThEdge];
+			 }
+		  else { // no add on background mesh 
+			  BTh.NbRef++;
+			  NbVertexOnBThVertex=0;
+			  VertexOnBThVertex=0;
+			  NbVertexOnBThEdge=0;
+			  VertexOnBThEdge=0;
+			 }
+
+
+		  if(nbe)
+			edges = new Edge[nbe];
+		  if(nbsubdomains)
+			subdomains = new SubDomain[nbsubdomains];
+		  pmin = Th.pmin;
+		  pmax = Th.pmax;
+		  coefIcoor = Th.coefIcoor;
+		  for(i=0;i<nbt;i++)
+			triangles[i].Set(Th.triangles[i],Th,*this);
+		  for(i=0;i<nbe;i++)
+			edges[i].Set(Th,i,*this);
+		  for(i=0;i<nbv;i++)
+			vertices[i].Set(Th.vertices[i],Th,*this);
+		  for(i=0;i<nbsubdomains;i++)  
+			subdomains[i].Set(Th,i,*this);
+		  for (i=0;i<NbVerticesOnGeomVertex;i++)
+			VerticesOnGeomVertex[i].Set(Th.VerticesOnGeomVertex[i],Th,*this);
+		  for (i=0;i<NbVerticesOnGeomEdge;i++)
+			VerticesOnGeomEdge[i].Set(Th.VerticesOnGeomEdge[i],Th,*this);
+		  quadtree=0;
+
+	  }
+	/*}}}*/
+	/*FUNCTION Mesh::Mesh(long maxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices){{{*/
+	Mesh::Mesh(long imaxnbv,Mesh & BT,BamgOpts* bamgopts,int keepBackVertices) :Gh(BT.Gh),BTh(BT) {
+		this->Init(imaxnbv);
+		TriangulateFromGeom1(bamgopts,keepBackVertices);
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::Mesh(long maxnbv,Geometry & G,BamgOpts* bamgopts){{{*/
+	Mesh::Mesh(long imaxnbv,Geometry & G,BamgOpts* bamgopts):Gh(G),BTh(*this){
+		Init(imaxnbv);
+		TriangulateFromGeom0(bamgopts);
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::~Mesh(){{{*/
+	Mesh::~Mesh() {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Triangles)*/
+
+		//if (vertices)             delete [] vertices;
+		if (edges)                delete [] edges;
+		if (triangles)            delete [] triangles;
+		if (quadtree)             delete    quadtree;
+		//if (orderedvertices)                delete [] orderedvertices;
+		if (subdomains)           delete []  subdomains;
+		if (VerticesOnGeomEdge)   delete [] VerticesOnGeomEdge;
+		if (VerticesOnGeomVertex) delete [] VerticesOnGeomVertex;
+		if (VertexOnBThVertex)    delete [] VertexOnBThVertex;
+		if (VertexOnBThEdge)      delete [] VertexOnBThEdge;
+
+		if (&Gh) {
+			if (Gh.NbRef>0) Gh.NbRef--;
+			else if (Gh.NbRef==0) delete &Gh;
+		}
+		if (&BTh && (&BTh != this)) {
+			if (BTh.NbRef>0) BTh.NbRef--;
+			else if (BTh.NbRef==0) delete &BTh;
+		}
+		Init(0); // set all to zero 
+	}
+	/*}}}*/
+
+	/*IO*/
+	/*FUNCTION Mesh::ReadMesh(int* index,double* x,double* y,int nods,int nels){{{*/
+	void Mesh::ReadMesh(int* index,double* x,double* y,int nods,int nels){
+
+		double Hmin = HUGE_VAL;// the infinie value 
+		long i1,i2,i3;
+		long i,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) _error_("Orphan found in mesh, see ids above");
+
+		/*Clean up*/
+		xDelete<bool>(nodeflags);
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts){{{*/
+	void Mesh::ReadMesh(BamgMesh* bamgmesh, BamgOpts* bamgopts){
+
+		int    verbose;
+		double Hmin = HUGE_VAL;    // the infinie value
+		long   i1,i2,i3;
+		long   i,j;
+		Metric M1(1);
+
+		verbose=bamgopts->verbose;
+
+		nbv=bamgmesh->VerticesSize[0];
+		maxnbv=nbv;
+		nbt=bamgmesh->TrianglesSize[0];
+
+		//Vertices
+		if(bamgmesh->Vertices){
+			if(verbose>5) _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) _error_("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) _error_("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)) {
+					_error_("ReadMesh error: EdgesOnGeomEdge edge provided (line " << i1+1 << ": [" << i+1 << " " << j+1 << "]) is incorrect (must be positive, [0<i<nbe=" << nbe << " 0<j<Gh.nbe=" << Gh.nbe << "]");
+				}
+				edges[i].GeomEdgeHook=Gh.edges+j;
+			}
+		}
+
+		//SubDomain
+		if(bamgmesh->SubDomains){
+			long i3,head,direction;
+			if(verbose>5) _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) _error_("Bad Subdomain definition: first number should be 3");
+				if (head<0 || head>=nbt) _error_("Bad Subdomain definition: head should in [1 " << nbt << "] (triangle number)");
+				subdomains[i].head = triangles+head;
+			}
+		}
+
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::WriteMesh {{{*/
+	void Mesh::WriteMesh(BamgMesh* bamgmesh,BamgOpts* bamgopts){
+
+		/*Intermediary*/
+		int i,j,k,num,i1,i2;
+		long n;
+		int* head_1=NULL;
+		int* next_1=NULL;
+		int* connectivitysize_1=NULL;
+		int  connectivitymax_1=0;
+
+		/*Get options*/
+		int verbose=bamgopts->verbose;
+
+		/*Build reft that holds the number the subdomain number of each triangle, and the real numbering of the elements*/
+		long* reft = new long[nbt];
+		long* numt = new long[nbt];
+		long nbInT = TriangleReferenceList(reft);
+		TriangleIntNumbering(numt);
+
+		/*Chaining algorithm used to generate connectivity tables and other outputs*/
+
+		//Memory Allocation
+		head_1=xNew<int>(nbv);
+		next_1=xNew<int>(3*nbt);
+		connectivitysize_1=xNew<int>(nbv);
+
+		//Initialization
+		for (i=0;i<nbv;i++) head_1[i]=-1;
+		for (i=0;i<nbv;i++) connectivitysize_1[i]=0;
+		k=0;
+		//Chains generation
+		for (i=0;i<nbt;i++) {
+			//Do not take into account outside triangles (reft<0)
+			if (reft[i]>=0){
+				for (j=0;j<3;j++){
+					int v=GetId(triangles[i][j]); //jth vertex of the ith triangle
+					if (k>3*nbt-1 || k<0) _error_("k = " << k << ", nbt = " << nbt);
+					next_1[k]=head_1[v];
+					if (v>nbv-1 || v<0)   _error_("v = " << v << ", nbv = " << nbv);
+					head_1[v]=k++;
+					connectivitysize_1[v]+=1;
+				}
+			}
+		}
+		//Get maximum connectivity
+		connectivitymax_1=0;
+		for (i=0;i<nbv;i++){
+			if (connectivitysize_1[i]>connectivitymax_1) connectivitymax_1=connectivitysize_1[i];
+		}
+
+		/*OK, now build outputs*/
+
+		/*Vertices*/
+		if(verbose>5) _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){
+					_error_("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()){
+					_error_("A vertices supposed to be OnGeomEdge is actually not");
+				}
+				bamgmesh->VerticesOnGeomEdge[i*3+0]=GetId((BamgVertex*)v)+1; //back to Matlab indexing
+				bamgmesh->VerticesOnGeomEdge[i*3+1]=Gh.GetId((const GeomEdge*)v)+1; //back to Matlab indexing
+				bamgmesh->VerticesOnGeomEdge[i*3+2]=(double)v; //absisce
+			}
+		}
+
+		/*EdgesOnGeomEdge*/
+		if(verbose>5) _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) _error_("Index exceed matrix dimensions (k=" << k << " not in [0 " << 2*i1-1 << "]");
+				next_2[k]=head_2[v];
+				if (v>nbv-1 || v<0)   _error_("Index exceed matrix dimensions (v=" << v << " not in [0 " << nbv-1 << "])");
+				head_2[v]=k++;
+				connectivitysize_2[v]+=1;
+			}
+		}
+		//Get maximum connectivity
+		for (i=0;i<nbv;i++){
+			if (connectivitysize_2[i]>connectivitymax_2) connectivitymax_2=connectivitysize_2[i];
+		}
+		//Build output
+		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){
+			_error_("hmax<=0");
+		}
+
+		//errC cannot be higher than 1
+		if (errC>1) errC=1;
+
+		//Set all vertices to "on"
+		SetVertexFieldOn();
+
+		//loop over all the vertices on edges
+		for (int  i=0;i<nbe;i++){
+			for (int j=0;j<2;j++){
+
+				BamgVertex V;
+				VertexOnGeom GV;
+				Gh.ProjectOnCurve(edges[i],ss[j],V,GV);
+
+				GeomEdge* eg = GV;
+				double s = GV;
+				R2 tg;
+				double  R1= eg->R1tg(s,tg);
+				double  ht=hmax;
+				// err relative to the length of the edge
+				if (R1>1.0e-20) {  
+					ht = Min(Max(errC/R1,hmin),hmax);
+				}
+				double hn=Min(hmax,ht*anisomax);
+
+				if (ht<=0 || hn<=0){
+					_error_("ht<=0 || hn<=0");
+				}
+				EigenMetric Vp(1/(ht*ht),1/(hn*hn),tg);
+				Metric MVp(Vp);
+				edges[i][j].m.IntersectWith(MVp);
+			}
+		}
+		// the problem is for the vertex on vertex 
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::AddMetric{{{*/
+	void Mesh::AddMetric(BamgOpts* bamgopts){
+		//  Hessiantype = 0 =>  H is computed using double 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{
+			_error_("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) ){
+			_error_("inconsistent configuration (Contact ISSM developers)");
+		}
+
+		// if det3 does not exist, build it 
+		if (!det3){ 
+			//allocate
+			det3 = det3local;
+			//if no infinite vertex
+			if (infvertexindex<0 ) {
+				det3[0]=bamg::det(s ,s1,s2);
+				det3[1]=bamg::det(s0,s ,s2);
+				det3[2]=bamg::det(s0,s1,s );}
+			else { 
+				// one of &s1  &s2  &s0 is NULL
+				det3[0]= &s0 ? -1 : bamg::det(s ,s1,s2) ;
+				det3[1]= &s1 ? -1 : bamg::det(s0,s ,s2) ;
+				det3[2]= &s2 ? -1 : bamg::det(s0,s1,s ) ;
+			}
+		}
+
+		if (!det3[0]) izerodet=0,nbzerodet++;
+		if (!det3[1]) izerodet=1,nbzerodet++;
+		if (!det3[2]) izerodet=2,nbzerodet++;
+
+		//if nbzerodet>0, point s is on an egde or on a vertex 
+		if  (nbzerodet>0){ 
+			/*s is on an edge*/
+			if (nbzerodet==1) {
+				iedge = OppositeEdge[izerodet];
+				AdjacentTriangle ta = t->Adj(iedge);
+
+				/*if the point is one the boundary 
+				  add the point in outside part */
+				if (t->det>=0){ // inside triangle
+					if (((Triangle*)ta)->det<0 ) {
+						// add in outside triangle 
+						AddVertex(s,( Triangle *)ta);
+						return;
+					}
+				}
+			}
+			else{
+				_error_("Cannot add a vertex more than once. Check duplicates");
+			}
+		}
+
+		// remove de MarkUnSwap edge
+		t->SetUnMarkUnSwap(0);
+		t->SetUnMarkUnSwap(1);
+		t->SetUnMarkUnSwap(2);
+
+		tt[0]= t;
+		tt[1]= &triangles[nbt++];
+		tt[2]= &triangles[nbt++];
+
+		if (nbt>maxnbt) _error_("Not enough triangles");
+
+		*tt[1]=*tt[2]=*t;
+		tt[0]->link=tt[1];
+		tt[1]->link=tt[2]; 
+
+		(*tt[0])(OppositeVertex[0])=&s;
+		(*tt[1])(OppositeVertex[1])=&s;
+		(*tt[2])(OppositeVertex[2])=&s;
+
+		tt[0]->det=det3[0];
+		tt[1]->det=det3[1];
+		tt[2]->det=det3[2];         
+
+		//  update adj des triangles externe 
+		tt[0]->SetAdjAdj(0);
+		tt[1]->SetAdjAdj(1);
+		tt[2]->SetAdjAdj(2);
+		//  update des adj des 3 triangle interne
+		const int i0 = 0;
+		const int i1= NextEdge[i0];
+		const int i2 = PreviousEdge[i0];
+
+		tt[i0]->SetAdj2(i2,tt[i2],i0);
+		tt[i1]->SetAdj2(i0,tt[i0],i1);
+		tt[i2]->SetAdj2(i1,tt[i1],i2);
+
+		tt[0]->SetSingleVertexToTriangleConnectivity();
+		tt[1]->SetSingleVertexToTriangleConnectivity();
+		tt[2]->SetSingleVertexToTriangleConnectivity();
+
+
+		// swap if the point s is on a edge
+		if(izerodet>=0) {
+			int rswap=tt[izerodet]->swap(iedge);
+
+			if (!rswap) {
+				_error_("swap the point s is on a edge");
+			}
+		}
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::BoundAnisotropy{{{*/
+	void  Mesh::BoundAnisotropy(double anisomax,double hminaniso) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Metric.cpp/BoundAnisotropy)*/
+
+		long int verbose=0;
+		double lminaniso = 1/ (Max(hminaniso*hminaniso,1e-100));
+
+		//display info
+		if (verbose > 1)  _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 ) {
+			_error_("nbt or nbv is negative (Mesh empty?)");
+		}
+
+		//Gh is the geometry of the mesh (this), initialize MaxCornerAngle
+		if (cutoffradian>=0) Gh.MaxCornerAngle = cutoffradian;
+
+		/*Construction of the edges*/
+
+		//initialize st and edge4
+		SetOfEdges4* edge4= new SetOfEdges4(nbt*3,nbv);
+		long*        st   = new long[nbt*3];
+
+		//initialize st as -1 (chaining algorithm)
+		for (i=0;i<nbt*3;i++) st[i]=-1;
+
+		//build edge4 (chain)
+		for (i=0;i<nbe;i++){
+			edge4->SortAndAdd(GetId(edges[i][0]),GetId(edges[i][1]));
+		}
+		//check that there is no double edge
+		if (nbe !=  edge4->nb()){ 
+			delete [] st;
+			_error_("Some Double edge in the mesh, the number is " << nbe << ", nbe4=" << edge4->nb()); 
+		}
+		//keep nbe in nbeold
+		long nbeold = nbe;
+
+		//Go through the triangles and ass the edges in edge4 if they are not there yet
+		for (i=0;i<nbt;i++){
+			//3 edges per triangle
+			for  (j=0;j<3;j++) {
+				//Add Edge to edge4 (k=numberofedges in edge4)
+				long k =edge4->SortAndAdd(GetId(triangles[i][VerticesOfTriangularEdge[j][0]]), GetId(triangles[i][VerticesOfTriangularEdge[j][1]]));
+				long invisible = triangles[i].Hidden(j);
+
+				//if st[k] has not been changed yet, add 3*i+j (= vertex position in the index)
+				if(st[k]==-1) st[k]=3*i+j;
+
+				//else st[k]>=0 -> the edge already exist, check
+				else if(st[k]>=0) {
+					//check that it is not an edge on boundary (should not already exist)
+					if (triangles[i].TriangleAdj(j) || triangles[st[k]/3].TriangleAdj((int) (st[k]%3))){
+						_error_("problem in Geometry reconstruction: an edge on boundary is duplicated (double element?)");
+					}
+					//OK, the element is not on boundary, is belongs to 2 triangles -> build Adjacent triangles list
+					triangles[i].SetAdj2(j,triangles + st[k] / 3,(int) (st[k]%3));
+					if (invisible)  triangles[i].SetHidden(j);
+					// if k < nbe mark the edge as on Boundary (Locked)
+					if (k<nbe) {
+						triangles[i].SetLocked(j);
+					}
+					//set st[k] as negative so that the edge should not be called again
+					st[k]=-2-st[k]; 
+				}
+				//else (see 3 lines above), the edge has been called more than twice: return error
+				else {
+					_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))));
+					_error_("An edge belongs to more than 2 triangles");
+				}	
+			}
+		}
+
+		//delete edge4
+		long nbedges = edge4->nb(); // the total number of edges 
+		delete edge4; edge4=NULL;
+
+		//display info
+		if(verbose>5) {
+			_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){
+				_error_("problem in edge construction process: k!=nbe (should not happen)");
+			}
+			//delete edgessave
+			if (edgessave) delete [] edgessave;
+		}
+
+		/*Color the vertices*/
+
+		//initialize color of all vertices as 0
+		for (i=0;i<nbv;i++) vertices[i].color =0;
+
+		//go through the edges and add a color to corresponding vertices
+		//(A vertex in 4 edges will have a color 4)
+		for (i=0;i<nbe;i++){
+		 for (j=0;j<2;j++) edges[i].v[j]->color++;
+		}
+
+		//change the color: if a vertex belongs to 2 edges -1, else -2
+		for (i=0;i<nbv;i++) {
+			vertices[i].color=(vertices[i].color ==2)? -1 : -2;
+		}
+
+		/*Build edges[i].adj: adjacency of each edge (if on the same curve)*/
+		for (i=0;i<nbe;i++){
+			for (j=0;j<2;j++){ 
+				//get current vertex
+				BamgVertex* v=edges[i].v[j];
+				//get vertex color (i0)
+				long i0=v->color;
+				long j0;
+
+				//if color<0 (first time), no adjacent edge
+				if(i0<0) edges[i].adj[j]=NULL;
+
+				//if color=-1 (corner),change the vertex color as 2*i+j (position of the vertex in edges)
+				if(i0==-1) v->color=i*2+j;
+
+				//if color>=0 (i and i0 edge are adjacent by the vertex v)
+				else if (i0>=0) {
+					//get position of v in edges back
+					j0 =  i0%2; //column in edges
+					i0 =  i0/2; //line in edges
+
+					//check that we have the correct vertex
+					if (v!=edges[i0 ].v[j0]){
+						_error_("v!=edges[i0 ].v[j0]: this should not happen as the vertex belongs to this edge");
+					}
+
+					//Add adjacence
+					edges[i ].adj[j ]=edges +i0;
+					edges[i0].adj[j0]=edges +i ;
+
+					//change color to -3
+					v->color = -3;
+				}
+			}
+		}
+
+		/*Reconstruct subdomains info*/
+
+		//check that nbsubdomains is empty
+		if (nbsubdomains){
+			_error_("nbsubdomains should be 0");
+		}
+		nbsubdomains=0;
+
+		//color the subdomains
+		long* colorT= new long[nbt];
+		Triangle *tt,*t;
+
+		//initialize the color of each triangle as -1
+		for (it=0;it<nbt;it++) colorT[it]=-1;
+
+		//loop over the triangles
+		for (it=0;it<nbt;it++){
+
+			//if the triangle has not been colored yet:
+			if (colorT[it]<0){
+
+				//color = number of subdomains
+				colorT[it]=nbsubdomains;
+
+				//color all the adjacent triangles of T that share a non marked edge
+				int level =1;
+				int kolor=triangles[it].color;
+				st[0]=it; // stack 
+				st[1]=0;
+				k=1;
+				while (level>0){
+					if( (j=st[level]++)<3 ){ 
+						t = &triangles[st[level-1]];
+						tt=t->TriangleAdj((int)j);
+
+						//color the adjacent triangle
+						if ( ! t->Locked(j) && tt && (colorT[jt = GetId(tt)] == -1) && ( tt->color==kolor)) {
+							colorT[jt]=nbsubdomains;
+							st[++level]=jt;
+							st[++level]=0;
+							k++;
+						}
+					}
+					else level-=2;
+				}
+				nbsubdomains++;
+			}
+		}
+		if (verbose> 3) _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;
+			_error_("k!= nbsubdomains");
+		}
+		//delete colorT and st
+		delete [] colorT;
+		delete [] st;
+
+		/*Reconstruct Geometry Gh*/
+
+		//build colorV -1 for all vertex and 0 for the vertices belonging to edges
+		long* colorV = new long[nbv];
+		for (i=0;i<nbv;i++) colorV[i]=-1;
+		for (i=0;i<nbe;i++){
+		 for ( j=0;j<2;j++) colorV[GetId(edges[i][j])]=0;
+		}
+		//number the vertices belonging to edges
+		k=0;
+		for (i=0;i<nbv;i++){
+		 if(!colorV[i]) colorV[i]=k++;
+		}
+
+		//Build Gh
+		Gh.nbv=k;
+		Gh.nbe = nbe;
+		Gh.vertices = new GeomVertex[k];
+		Gh.edges = new GeomEdge[nbe];
+		Gh.nbsubdomains = nbsubdomains;
+		Gh.subdomains = new GeomSubDomain[nbsubdomains];
+		if (verbose>3) _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;
+			_error_("Gh.coefIcoor<=0 in infered Geometry (this should not happen)");
+		}
+
+		/*Build Gh.edges*/
+
+		//initialize len as 0
+		double * len = new double[Gh.nbv];
+		for(i=0;i<Gh.nbv;i++) len[i]=0;
+
+		//initialize edge4 again
+		edge4= new SetOfEdges4(nbe,nbv);  
+		double hmin = HUGE_VAL;
+		int kreq=0;
+		for (i=0;i<nbe;i++){
+
+			long i0 = GetId(edges[i][0]);
+			long i1 = GetId(edges[i][1]);
+			long j0 = colorV[i0];
+			long j1 = colorV[i1];
+
+			Gh.edges[i].v[0] = Gh.vertices +  j0;
+			Gh.edges[i].v[1] = Gh.vertices +  j1;
+
+			Gh.edges[i].type = 0;
+
+			Gh.edges[i].tg[0]=R2();
+			Gh.edges[i].tg[1]=R2();
+
+			bool required= edges[i].GeomEdgeHook; 
+			if(required) kreq++;
+			edges[i].GeomEdgeHook =  Gh.edges + i;
+			if(required){
+				Gh.edges[i].v[0]->SetRequired();
+				Gh.edges[i].v[1]->SetRequired();
+				Gh.edges[i].SetRequired();
+			}
+
+			R2 x12 = Gh.vertices[j0].r-Gh.vertices[j1].r;
+			double l12=Norme2(x12);        
+			hmin = Min(hmin,l12);
+
+			Gh.vertices[j1].color++;
+			Gh.vertices[j0].color++;
+
+			len[j0]+= l12;
+			len[j1] += l12;
+			hmin = Min(hmin,l12);
+			Gh.edges[i].ReferenceNumber  = edges[i].ReferenceNumber;
+
+			k = edge4->SortAndAdd(i0,i1);
+			if (k != i){
+				delete [] len;
+				delete [] colorV;
+				_error_("problem in Edge4 construction: k != i");
+			}
+		}
+
+		//Build metric for all vertices of Gh
+		for (i=0;i<Gh.nbv;i++){
+		 if (Gh.vertices[i].color > 0) 
+		  Gh.vertices[i].m=  Metric(len[i] /(double) Gh.vertices[i].color);
+		 else 
+		  Gh.vertices[i].m=  Metric(hmin);
+		}
+		//delete len
+		delete [] len;
+
+		//Build Gh.subdomains
+		for (i=0;i<nbsubdomains;i++){
+			it = GetId(subdomains[i].head);
+			j = subdomains[i].direction;
+			long i0 = GetId(triangles[it][VerticesOfTriangularEdge[j][0]]);
+			long i1 = GetId(triangles[it][VerticesOfTriangularEdge[j][1]]);
+			k = edge4->SortAndFind(i0,i1);
+			if(k>=0){
+				subdomains[i].direction = (vertices + i0 == edges[k].v[0]) ? 1 : -1;
+				subdomains[i].edge = edges+k;
+				Gh.subdomains[i].edge = Gh.edges + k;
+				Gh.subdomains[i].direction  =  subdomains[i].direction;
+				Gh.subdomains[i].ReferenceNumber =  subdomains[i].ReferenceNumber;
+			}
+			else
+			 _error_("%i should be >=0");
+		  }
+
+		delete edge4;
+		delete [] colorV;
+
+		//unset adj
+		for (i=0;i<nbt;i++){
+			for ( j=0;j<3;j++){
+				triangles[i].SetAdj2(j,0,triangles[i].GetAllflag(j));
+			}
+		}
+
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::BuildMetric0 (double 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) _error_("'field' should have " << nbv << " rows");
+
+		//initialization of some variables
+		double* ss=(double*)s;
+		double  sA,sB,sC;
+		double*  detT = new double[nbt];
+		double*  sumareas = new double[nbv];
+		double*  alpha= new double[nbt*3];
+		double*  beta = new double[nbt*3];
+		double*  dx_elem    = new double[nbt];
+		double*  dy_elem    = new double[nbt];
+		double*  dx_vertex  = new double[nbv];
+		double*  dy_vertex  = new double[nbv];
+		double*  dxdx_elem  = new double[nbt];
+		double*  dxdy_elem  = new double[nbt];
+		double*  dydy_elem  = new double[nbt];
+		double*  dxdx_vertex= new double[nbv];
+		double*  dxdy_vertex= new double[nbv];
+		double*  dydy_vertex= new double[nbv];
+
+		//display infos
+		if(verbose>1) {
+			_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) _error_("'field' should have " << nbv << " rows");
+
+		//initialization of some variables
+		long    i,k,iA,iB,iC,iv;
+		R2      O(0,0);
+		double* ss=(double*)s;
+		double  sA,sB,sC;
+		double*  detT = new double[nbt];
+		double*  Mmass= new double[nbv];
+		double*  Mmassxx= new double[nbv];
+		double*  dxdx= new double[nbv];
+		double*  dxdy= new double[nbv];
+		double*  dydy= new double[nbv];
+		double*  workT= new double[nbt];
+		double*  workV= new double[nbv];
+		int*    OnBoundary = new int[nbv];
+
+		//display infos
+		if(verbose>1) {
+			_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;
+					_error_("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) _error_("Maximum number of iteration exceeded");
+			}while ((tbegin != ta)); 
+		}
+
+		//Check EdgeFlag
+		for(i=0;i<NbCrackedEdges;i++){
+			if (Edgeflags[i]!=2){
+				_error_("A problem occured: at least one crack edge (number " << i+1 << ") does not belong to 2 elements");
+			}
+		}
+		delete [] Edgeflags;
+
+		//Reset BamgVertex to On
+		SetVertexFieldOn();
+
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::Echo{{{*/
+	void Mesh::Echo(void) {
+
+		int i;
+
+		_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) {
+				_error_("there is " << k << " triangles of mes = 0");
+			}
+
+			//Force Edges
+			AdjacentTriangle ta(0,0);
+			for (int i = 0; i < nbe; i++){
+
+				//Force edge i
+				nbswp =  ForceEdge(edges[i][0],edges[i][1],ta);
+				if (nbswp<0) k++;
+				else Nbswap += nbswp;
+
+				if (nbswp) nbfe++;
+				if ( nbswp < 0 && k < 5){
+					_error_("Missing Edge " << i << ", v0=" << GetId(edges[i][0]) << ",v1=" << GetId(edges[i][1]));
+				}
+			}
+
+			if (k!=0) {
+				_error_("There are " << k << " lost edges, the boundary might be crossing");
+			}
+			for (int j=0;j<nbv;j++){
+				Nbswap +=  vertices[j].Optim(1,0);
+			}
+			if (verbose > 3) _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;
+				_error_("The boundary is not close: all triangles are outside");
+			}
+
+			delete [] HeapArete;
+			delete [] HeapTriangle;
+
+
+			if (OutSide|| !Gh.subdomains || !Gh.nbsubdomains ) 
+			  { // No geom sub domain
+				long i;
+				if (subdomains) delete [] subdomains;
+				subdomains = new SubDomain[ NbSubDomTot];
+				nbsubdomains=  NbSubDomTot;
+				for ( i=0;i<nbsubdomains;i++) {
+					subdomains[i].head=NULL;
+					subdomains[i].ReferenceNumber=i+1;
+				}
+				long * mark = new long[nbt];
+				for (it=0;it<nbt;it++)
+				 mark[it]=triangles[it].link ? -1 : -2;
+
+				it =0;
+				k = 0;
+				while (it<nbt) {
+					if (mark[it] == -1) {
+						t1 = & triangles[it];
+						t = t1->link;
+						mark[it]=k;
+						subdomains[k].head = t1;
+						do {
+							mark[GetId(t)]=k;
+							t=t->link;
+						} while (t!=t1);
+						mark[it]=k++;}
+						//    else if(mark[it] == -2 ) triangles[it].Draw(999);
+						it++;} // end white (it<nbt)
+						if (k!=nbsubdomains){
+							delete [] mark;
+							_error_("k!=nbsubdomains");
+						}
+						if(OutSide) 
+						  {
+							//  to remove all the sub domain by parity adjacents
+							//  because in this case we have only the true boundary edge
+							// so teh boundary is manifold
+							long nbk = nbsubdomains;
+							while (nbk)
+							 for (it=0;it<nbt && nbk ;it++)
+							  for (int na=0;na<3 && nbk ;na++)
+								 {
+								  Triangle *ta = triangles[it].TriangleAdj(na);
+								  long kl = ta ? mark[GetId(ta)] : -2;
+								  long kr = mark[it];
+								  if(kr !=kl) {
+									  if (kl >=0 && subdomains[kl].ReferenceNumber <0 && kr >=0 && subdomains[kr].ReferenceNumber>=0)
+										nbk--,subdomains[kr].ReferenceNumber=subdomains[kl].ReferenceNumber-1;
+									  if (kr >=0 && subdomains[kr].ReferenceNumber <0 && kl >=0 && subdomains[kl].ReferenceNumber>=0)
+										nbk--,subdomains[kl].ReferenceNumber=subdomains[kr].ReferenceNumber-1;
+									  if(kr<0 && kl >=0 && subdomains[kl].ReferenceNumber>=0)
+										nbk--,subdomains[kl].ReferenceNumber=-1;
+									  if(kl<0 && kr >=0 && subdomains[kr].ReferenceNumber>=0)
+										nbk--,subdomains[kr].ReferenceNumber=-1;
+								  }
+								 }
+							long  j=0;
+							for ( i=0;i<nbsubdomains;i++)
+							 if((-subdomains[i].ReferenceNumber) %2) { // good 
+								 if(i != j) 
+								  Exchange(subdomains[i],subdomains[j]);
+								 j++;}
+							 else{ 
+								 t= subdomains[i].head;
+								 while (t){
+									 nbtout++;
+									 t1=t;
+									 t=t->link;
+									 t1->link=0;
+								 }//while (t)
+								}
+							if(verbose>4) _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) {
+								_error_("bad definition of SubSomain " << i);
+							}
+							long it = GetId(t);
+							if (mark[it] >=0) {
+								break;
+							}
+							if(i != inew) 
+							 Exchange(subdomains[i],subdomains[inew]);
+							inew++;
+							Triangle *tt=t;
+							long kkk=0;
+							do 
+							  {
+								kkk++;
+								if (mark[GetId(tt)]>=0){
+									_error_("mark[GetId(tt)]>=0");
+								}
+								mark[GetId(tt)]=i;
+								tt=tt->link;
+							  } while (tt!=t);
+							break;
+						}
+						ta = Previous(Adj(ta));         
+						if(t == (Triangle *) ta) {
+							_error_("bad definition of SubSomain " << i);
+						}
+					}
+				}
+
+				if (inew < nbsubdomains) {
+					if (verbose>5) _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) _error_("all the vertices are aligned");
+		}
+		// exchange i et 2 in "orderedvertices" so that
+		// the first 3 vertices are not aligned (real triangle)
+		Exchange(orderedvertices[2], orderedvertices[i]);
+
+		/*Take the first edge formed by the first two vertices and build
+		 * the initial simple mesh from this edge and 2 boundary triangles*/
+
+		BamgVertex *v0=orderedvertices[0], *v1=orderedvertices[1];
+
+		nbt = 2;
+		triangles[0](0) = NULL;//infinite vertex
+		triangles[0](1) = v0;
+		triangles[0](2) = v1;
+		triangles[1](0) = NULL;//infinite vertex
+		triangles[1](2) = v0;
+		triangles[1](1) = v1;
+
+		//Build adjacence
+		const int e0 = OppositeEdge[0];
+		const int e1 = NextEdge[e0];
+		const int e2 = PreviousEdge[e0];
+		triangles[0].SetAdj2(e0, &triangles[1] ,e0);
+		triangles[0].SetAdj2(e1, &triangles[1] ,e2);
+		triangles[0].SetAdj2(e2, &triangles[1] ,e1);
+
+		triangles[0].det = -1;  //boundary triangle: det = -1
+		triangles[1].det = -1;  //boundary triangle: det = -1
+
+		triangles[0].SetSingleVertexToTriangleConnectivity();
+		triangles[1].SetSingleVertexToTriangleConnectivity();
+
+		triangles[0].link=&triangles[1];
+		triangles[1].link=&triangles[0];
+
+		//build quadtree
+		if (!quadtree)  quadtree = new BamgQuadtree(this,0);
+		quadtree->Add(*v0);
+		quadtree->Add(*v1);
+
+		/*Now, add the vertices One by One*/
+		long NbSwap=0;
+		if (verbose>3) _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]){
+					_error_("&vj!= orderedvertices[j]");
+				}
+				if(i!=j){ 
+					Exchange(vi,vj);
+					Exchange(orderedvertices[j],orderedvertices[i]);
+				}
+				vj.ReferenceNumber=0; 
+				Triangle *tcvj=TriangleFindFromCoord(vj.i,det3);
+				if (tcvj && !tcvj->link){
+					tcvj->Echo();
+					_error_("problem inserting point in InsertNewPoints (tcvj=" << tcvj << " and tcvj->link=" << tcvj->link << ")");
+				}
+				quadtree->Add(vj);
+				AddVertex(vj,tcvj,det3);
+				NbSwap += vj.Optim(1);          
+				iv++;
+			}
+		} 
+		if (verbose>3) {
+			_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){
+			_error_("!Gh.nbe");
+		}
+		Edge **e= new (Edge* [Gh.nbe]);
+
+		long i;
+		for ( i=0;i<Gh.nbe ; i++)
+		 e[i]=NULL;
+		for ( i=0;i<nbe ; i++) 
+		  { 
+			Edge * ei = edges+i;
+			GeomEdge *GeomEdgeHook = ei->GeomEdgeHook; 
+			e[Gh.GetId(GeomEdgeHook)] = ei;    
+		  }
+		for ( i=0;i<nbe ; i++) 
+		 for (int ii=0;ii<2;ii++) { 
+			 Edge * ei = edges+i;
+			 GeomEdge *GeomEdgeHook = ei->GeomEdgeHook;
+			 int j= ii;
+			 while (!(*GeomEdgeHook)[j].Required()) { 
+				 Adj(GeomEdgeHook,j); // next geom edge
+				 j=1-j;
+				 if (e[Gh.GetId(GeomEdgeHook)])  break; // optimisation
+				 e[Gh.GetId(GeomEdgeHook)] = ei; 
+			 }
+		 }
+
+		int kk=0;
+		for ( i=0;i<Gh.nbe ; i++){
+			if (!e[i]){
+				kk++;
+				if(kk<10) _printLine_("BUG: the geometrical edge " << i << " is on no edge curve");
+			}
+		}
+		if(kk) _error_("See above");
+
+		return e;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::MakeQuadrangles{{{*/
+	void Mesh::MakeQuadrangles(double costheta){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/MakeQuadrangles)*/
+
+		long int verbose=0;
+
+		if (verbose>2) _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 ){
+					_error_("Index problem in NewPoints (i=" << i << " not in [0 " << nbt-1 << "])");
+				}
+				//change first_np_or_next_t[i]
+				first_np_or_next_t[i] = iter; 
+
+				//Loop over the edges of t
+				for(j=0;j<3;j++){
+					AdjacentTriangle tj(t,j);
+					BamgVertex &vA = *tj.EdgeVertex(0);
+					BamgVertex &vB = *tj.EdgeVertex(1);
+
+					//if t is a boundary triangle, or tj locked, continue
+					if (!t->link)     continue;
+					if (t->det <0)    continue;
+					if (t->Locked(j)) continue;
+
+					AdjacentTriangle tadjj = t->Adj(j);	  
+					Triangle* ta=tadjj;
+
+					//if the adjacent triangle is a boundary triangle, continur
+					if (ta->det<0) continue;	  
+
+					R2 A=vA;
+					R2 B=vB;
+					k=GetId(ta);
+
+					//if this edge has already been done, go to next edge of triangle
+					if(first_np_or_next_t[k]==iter) continue;
+
+					lIntTria.SplitEdge(Bh,A,B);
+					lIntTria.NewPoints(vertices,nbv,maxnbv);
+				  } // end loop for each edge 
+			  }// for triangle   
+
+			if (!InsertNewPoints(nbvold,NbTSwap)) break;
+			for (i=nbtold;i<nbt;i++) first_np_or_next_t[i]=iter;
+			Headt = nbt; // empty list 
+
+			// for all the triangle containing the vertex i
+			for (i=nbvold;i<nbv;i++){ 
+				BamgVertex*          s  = vertices + i;
+				AdjacentTriangle ta(s->t, EdgesVertexTriangle[s->IndexInTriangle][1]);
+				Triangle*        tbegin= (Triangle*) ta;
+				long kt;
+				do { 
+					kt = GetId((Triangle*) ta);
+					if (first_np_or_next_t[kt]>0){
+						first_np_or_next_t[kt]=-Headt;
+						Headt=kt;
+					}
+					if (ta.EdgeVertex(0)!=s){
+						_error_("ta.EdgeVertex(0)!=s");
+					}
+					ta = Next(Adj(ta));
+				} while ( (tbegin != (Triangle*) ta)); 
+			}
+
+		} while (nbv!=nbvold);
+
+		delete []  first_np_or_next_t;
+
+		long NbSwapf =0,NbSwp;
+
+		NbSwp = NbSwapf;
+		for (i=0;i<nbv;i++)
+		 NbSwapf += vertices[i].Optim(0);
+		NbTSwap +=  NbSwapf ;
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::ProjectOnCurve{{{*/
+	GeomEdge*   Mesh::ProjectOnCurve( Edge & BhAB, BamgVertex &  vA, BamgVertex & vB,
+				double theta,BamgVertex & R,VertexOnEdge &  BR,VertexOnGeom & GR) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshQuad.cpp/ProjectOnCurve)*/
+
+		void *pA=0,*pB=0;
+		double tA=0,tB=0;
+		R2 A=vA,B=vB;
+		BamgVertex * pvA=&vA, * pvB=&vB;
+		if (vA.IndexInTriangle == IsVertexOnVertex){
+			pA=vA.BackgroundVertexHook;
+		}
+		else if (vA.IndexInTriangle == IsVertexOnEdge){
+			pA=vA.BackgroundEdgeHook->be;
+			tA=vA.BackgroundEdgeHook->abcisse;
+		}
+		else {
+			_error_("ProjectOnCurve On BamgVertex " << BTh.GetId(vA) << " forget call to SetVertexFieldOnBTh");
+		} 
+
+		if (vB.IndexInTriangle == IsVertexOnVertex){
+			pB=vB.BackgroundVertexHook;
+		}
+		else if(vB.IndexInTriangle == IsVertexOnEdge){
+			pB=vB.BackgroundEdgeHook->be;
+			tB=vB.BackgroundEdgeHook->abcisse;
+		}
+		else {
+			_error_("ProjectOnCurve On BamgVertex " << BTh.GetId(vB) << " forget call to SetVertexFieldOnBTh");
+		} 
+		Edge * e = &BhAB;
+		if (!pA || !pB || !e){
+			_error_("!pA || !pB || !e");
+		}
+		// be carefull the back ground edge e is on same geom edge 
+		// of the initiale edge def by the 2 vertex A B;
+		//check Is a background Mesh;   
+		if (e<BTh.edges || e>=BTh.edges+BTh.nbe){
+			_error_("e<BTh.edges || e>=BTh.edges+BTh.nbe");
+		}
+		// walk on BTh edge 
+		//not finish ProjectOnCurve with BackGround Mesh);
+		// 1 first find a back ground edge contening the vertex A
+		// 2 walk n back gound boundary to find the final vertex B
+
+		if( vA.IndexInTriangle == IsVertexOnEdge) 
+		  { // find the start edge 
+			e = vA.BackgroundEdgeHook->be;	 
+
+		  } 
+		else if (vB.IndexInTriangle == IsVertexOnEdge) 
+		  {
+			theta = 1-theta;
+			Exchange(tA,tB);
+			Exchange(pA,pB);
+			Exchange(pvA,pvB);
+			Exchange(A,B);
+			e =  vB.BackgroundEdgeHook->be;
+
+		  } 
+		else{ // do the search by walking 
+			_error_("case not supported yet");
+		  }
+
+		// find the direction of walking with direction of edge and pA,PB;
+		R2 AB=B-A;
+
+		double cosE01AB = (( (R2) (*e)[1] - (R2) (*e)[0] ) , AB);
+		int kkk=0;
+		int direction = (cosE01AB>0) ? 1 : 0;
+
+		//   double l=0; // length of the edge AB
+		double abscisse = -1;
+
+		for (int step=0;step<2;step++){
+			// 2 times algo:
+			//    1 for computing the length l
+			//    2 for find the vertex 
+			int  iii;
+			BamgVertex  *v0=pvA,*v1; 
+			Edge *neee,*eee;
+			double lg =0; // length of the curve 
+			double te0;
+			// we suppose take the curve's abcisse 
+			for ( eee=e,iii=direction,te0=tA;
+						eee && ((( void*) eee) != pB) && (( void*) (v1=&((*eee)[iii]))) != pB ;
+						neee = eee->adj[iii],iii = 1-neee->Intersection(*eee),eee = neee,v0=v1,te0=1-iii ) { 
+
+				kkk=kkk+1;
+				_assert_(kkk<100);
+				_assert_(eee);
+				double lg0 = lg;
+				double dp = LengthInterpole(v0->m,v1->m,(R2) *v1 - (R2) *v0);
+				lg += dp;
+				if (step && abscisse <= lg) { // ok we find the geom edge 
+					double sss  =   (abscisse-lg0)/dp;
+					double thetab = te0*(1-sss)+ sss*iii;
+					_assert_(thetab>=0 && thetab<=1);
+					BR = VertexOnEdge(&R,eee,thetab);
+					return  Gh.ProjectOnCurve(*eee,thetab,R,GR);
+				  }
+			  }
+			// we find the end 
+			if (v1 != pvB){
+				if (( void*) v1 == pB)
+				 tB = iii;
+
+				double lg0 = lg;
+				_assert_(eee);
+				v1 = pvB;
+				double dp = LengthInterpole(v0->m,v1->m,(R2) *v1 - (R2) *v0);
+				lg += dp;	
+				abscisse = lg*theta;
+				if (abscisse <= lg && abscisse >= lg0 ) // small optimisation we know the lenght because end
+				  { // ok we find the geom edge 
+					double sss  =   (abscisse-lg0)/dp;
+					double thetab = te0*(1-sss)+ sss*tB;
+					_assert_(thetab>=0 && thetab<=1);
+					BR = VertexOnEdge(&R,eee,thetab);
+					return  Gh.ProjectOnCurve(*eee,thetab,R,GR);
+				  }
+			  }
+			abscisse = lg*theta;
+
+		  }
+		_error_("Big bug...");
+		return 0; // just for the compiler 
+	}                  
+	/*}}}*/
+/*FUNCTION Mesh::ReconstructExistingMesh{{{*/
+void Mesh::ReconstructExistingMesh(){
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/FillHoleInMesh)*/
+
+	/*This routine reconstruct an existing mesh to make it CONVEX:
+	 * -all the holes are filled
+	 * -concave boundaries are filled
+	 * A convex mesh is required for a lot of operations. This is why every mesh
+	 * goes through this process.
+	 * This routine also generates mesh properties such as adjencies,...
+	 */
+
+	/*Intermediary*/
+	int verbose=0;
+
+	// generation of the integer coordinate
+
+	// find extrema coordinates of vertices pmin,pmax
+	long i;
+	if(verbose>2) _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){ 
+		_error_("There are " << kk-nbe << " double edges in the mesh");
+	}
+
+	//Add edges of all triangles in existing mesh
+	long* st = new long[nbt*3];
+	for (i=0;i<nbt*3;i++) st[i]=-1;
+	for (i=0;i<nbt;i++){
+		for (int j=0;j<3;j++){
+
+			//Add current triangle edge to edge4
+			long k =edge4->SortAndAdd(GetId(triangles[i][VerticesOfTriangularEdge[j][0]]),GetId(triangles[i][VerticesOfTriangularEdge[j][1]]));
+
+			long invisible=triangles[i].Hidden(j);
+
+			//If the edge has not been added to st, add it
+			if(st[k]==-1) st[k]=3*i+j;
+
+			//If the edge already exists, add adjacency
+			else if(st[k]>=0) {
+				_assert_(!triangles[i].TriangleAdj(j));
+				_assert_(!triangles[st[k]/3].TriangleAdj((int) (st[k]%3)));
+
+				triangles[i].SetAdj2(j,triangles+st[k]/3,(int)(st[k]%3));
+				if (invisible) triangles[i].SetHidden(j);
+				if (k<nbe)     triangles[i].SetLocked(j);
+
+				//Make st[k] negative so that it will throw an error message if it is found again
+				st[k]=-2-st[k]; 
+			}
+
+			//An edge belongs to 2 triangles
+			else {
+				_error_("The edge (" << GetId(triangles[i][VerticesOfTriangularEdge[j][0]]) << " , " << GetId(triangles[i][VerticesOfTriangularEdge[j][1]]) << ") belongs to more than 2 triangles");
+			}
+		}
+	}
+
+	//Display info if required
+	if(verbose>5) {
+		_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) {
+		_error_(k << " boundary edges (from the geometry) are not defined as mesh edges");
+	}
+
+	/* mesh generation with boundary points*/
+	long nbvb=0;
+	for (i=0;i<nbv;i++){ 
+		vertices[i].t=0;
+		vertices[i].IndexInTriangle=0;
+		if (orderedvertices[i]) orderedvertices[nbvb++]=orderedvertices[i];
+	}
+
+	Triangle* savetriangles=triangles;
+	long savenbt=nbt;
+	long savemaxnbt=maxnbt;
+	SubDomain* savesubdomains=subdomains;
+	subdomains=0;
+
+	long  Nbtriafillhole=2*nbvb;
+	Triangle* triafillhole=new Triangle[Nbtriafillhole];
+	triangles = triafillhole;
+
+	nbt=2;
+	maxnbt= Nbtriafillhole;
+
+	//Find a vertex that is not aligned with vertices 0 and 1
+	for (i=2;det(orderedvertices[0]->i,orderedvertices[1]->i,orderedvertices[i]->i)==0;) 
+	 if  (++i>=nbvb) {
+		 _error_("ReconstructExistingMesh: All the vertices are aligned");
+	 }
+	//Move this vertex (i) to the 2d position in orderedvertices
+	Exchange(orderedvertices[2], orderedvertices[i]);
+
+	/*Reconstruct mesh beginning with 2 triangles*/
+	BamgVertex *  v0=orderedvertices[0], *v1=orderedvertices[1];
+
+	triangles[0](0) = NULL; // Infinite vertex
+	triangles[0](1) = v0;
+	triangles[0](2) = v1;
+
+	triangles[1](0) = NULL;// Infinite vertex
+	triangles[1](2) = v0;
+	triangles[1](1) = v1;
+	const int e0 = OppositeEdge[0];
+	const int e1 = NextEdge[e0];
+	const int e2 = PreviousEdge[e0];
+	triangles[0].SetAdj2(e0, &triangles[1] ,e0);
+	triangles[0].SetAdj2(e1, &triangles[1] ,e2);
+	triangles[0].SetAdj2(e2, &triangles[1] ,e1);
+
+	triangles[0].det = -1;  // boundary triangles
+	triangles[1].det = -1;  // boundary triangles
+
+	triangles[0].SetSingleVertexToTriangleConnectivity();
+	triangles[1].SetSingleVertexToTriangleConnectivity();
+
+	triangles[0].link=&triangles[1];
+	triangles[1].link=&triangles[0];
+
+	if (!quadtree) delete quadtree; //ReInitialise;
+	quadtree = new BamgQuadtree(this,0);
+	quadtree->Add(*v0);
+	quadtree->Add(*v1);
+
+	// vertices are added one by one
+	long NbSwap=0;
+	for (int icount=2; icount<nbvb; icount++) {
+		BamgVertex *vi  = orderedvertices[icount];
+		Icoor2 det3[3];
+		Triangle *tcvi = TriangleFindFromCoord(vi->i,det3);
+		quadtree->Add(*vi); 
+		AddVertex(*vi,tcvi,det3);
+		NbSwap += vi->Optim(1,1);
+	}
+
+	//enforce the boundary 
+	AdjacentTriangle ta(0,0);
+	long nbloss = 0,knbe=0;
+	for ( i = 0; i < nbe; i++){
+		if (st[i] >=0){ //edge alone => on border
+			BamgVertex &a=edges[i][0], &b=edges[i][1];
+			if (a.t && b.t){
+				knbe++;
+				if (ForceEdge(a,b,ta)<0) nbloss++;
+			}
+		}
+	}
+	if(nbloss) {
+		_error_("we lost " << nbloss << " existing edges other " << knbe);
+	}
+
+	FindSubDomain(1);
+	// remove all the hole 
+	// remove all the good sub domain
+	long krm =0;
+	for (i=0;i<nbt;i++){
+		if (triangles[i].link){ // remove triangles
+			krm++;
+			for (int j=0;j<3;j++){
+				AdjacentTriangle ta =  triangles[i].Adj(j);
+				Triangle &tta = *(Triangle*)ta;
+				//if edge between remove and not remove 
+				if(! tta.link){ 
+					// change the link of ta;
+					int ja = ta;
+					BamgVertex *v0= ta.EdgeVertex(0);
+					BamgVertex *v1= ta.EdgeVertex(1);
+					long k =edge4->SortAndAdd(v0?GetId(v0):nbv,v1? GetId(v1):nbv);
+
+					_assert_(st[k]>=0);
+					tta.SetAdj2(ja,savetriangles + st[k] / 3,(int) (st[k]%3));
+					ta.SetLock();
+					st[k]=-2-st[k]; 
+				}
+			}
+		}
+	}
+	long NbTfillHoll =0;
+	for (i=0;i<nbt;i++){
+		if (triangles[i].link) {
+			triangles[i]=Triangle((BamgVertex *) NULL,(BamgVertex *) NULL,(BamgVertex *) NULL);
+			triangles[i].color=-1;
+		}
+		else{
+			triangles[i].color= savenbt+ NbTfillHoll++;
+		}
+	}
+	_assert_(savenbt+NbTfillHoll<=savemaxnbt);
+
+	// copy of the outside triangles in saveMesh 
+	for (i=0;i<nbt;i++){
+		if(triangles[i].color>=0) {
+			savetriangles[savenbt]=triangles[i];
+			savetriangles[savenbt].link=0;
+			savenbt++;
+		}
+	}
+	// gestion of the adj
+	k =0;
+	Triangle * tmax = triangles + nbt;
+	for (i=0;i<savenbt;i++) { 
+		Triangle & ti = savetriangles[i];
+		for (int j=0;j<3;j++){
+			Triangle * ta = ti.TriangleAdj(j);
+			int aa = ti.NuEdgeTriangleAdj(j);
+			int lck = ti.Locked(j);
+			if (!ta) k++; // bug 
+			else if ( ta >= triangles && ta < tmax){
+				ta= savetriangles + ta->color;
+				ti.SetAdj2(j,ta,aa);
+				if(lck) ti.SetLocked(j);
+			}
+		}
+	}
+
+	// restore triangles;
+	nbt=savenbt;
+	maxnbt=savemaxnbt;
+	delete [] triangles;
+	delete [] subdomains;
+	triangles = savetriangles;
+	subdomains = savesubdomains;
+	if (k) {
+		_error_("number of triangles edges alone = " << k);
+	}
+	FindSubDomain();
+
+	delete edge4;
+	delete [] st;
+	for (i=0;i<nbv;i++) quadtree->Add(vertices[i]);
+
+	SetVertexFieldOn();
+
+	/*Check requirements consistency*/
+	for (i=0;i<nbe;i++){
+ 	/*If the current mesh edge is on Geometry*/
+		if(edges[i].GeomEdgeHook){
+			for(int j=0;j<2;j++){
+				/*Go through the edges adjacent to current edge (if on the same curve)*/
+				if (!edges[i].adj[j]){
+					/*The edge is on Geometry and does not have 2 adjacent edges... (not on a closed curve)*/
+					/*Check that the 2 vertices are on geometry AND required*/
+					if(!edges[i][j].GeomEdgeHook->IsRequiredVertex()){
+						_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");
+						_error_("See above (might be cryptic...)");
+					}
+				}
+			}
+		}
+	}
+}
+/*}}}*/
+	/*FUNCTION Mesh::TrianglesRenumberBySubDomain{{{*/
+	void Mesh::TrianglesRenumberBySubDomain(bool justcompress){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ReNumberingTheTriangleBySubDomain)*/
+
+		long int verbose=0;
+		long *renu= new long[nbt];
+		register Triangle *t0,*t,*te=triangles+nbt;
+		register long k=0,it,i,j;
+
+		for ( it=0;it<nbt;it++) 
+		 renu[it]=-1; // outside triangle 
+		for ( i=0;i<nbsubdomains;i++)
+		  { 
+			t=t0=subdomains[i].head;
+			if (!t0){ // not empty sub domain
+				_error_("!t0");
+			}
+			do { 
+				long kt = GetId(t);
+				if (kt<0 || kt >= nbt ){
+					_error_("kt<0 || kt >= nbt");
+				}
+				if (renu[kt]!=-1){
+					_error_("renu[kt]!=-1");
+				}
+				renu[kt]=k++;
+			}
+			while (t0 != (t=t->link));
+		  }
+		// take is same numbering if possible    
+		if(justcompress)
+		 for ( k=0,it=0;it<nbt;it++) 
+		  if(renu[it] >=0 ) 
+			renu[it]=k++;
+
+		// put the outside triangles at the end
+		for ( it=0;it<nbt;it++){
+			if (renu[it]==-1) renu[it]=k++;
+		}
+		if (k != nbt){
+			_error_("k != nbt");
+		}
+		// do the change on all the pointeur 
+		for ( it=0;it<nbt;it++)
+		 triangles[it].Renumbering(triangles,te,renu);
+
+		for ( i=0;i<nbsubdomains;i++)
+		 subdomains[i].head=triangles+renu[GetId(subdomains[i].head)];
+
+		// move the Triangles  without a copy of the array 
+		// be carefull not trivial code 
+		for ( it=0;it<nbt;it++) // for all sub cycles of the permutation renu
+		 if (renu[it] >= 0) // a new sub cycle
+			{ 
+			 i=it;
+			 Triangle ti=triangles[i],tj;
+			 while ( (j=renu[i]) >= 0) 
+				{ // i is old, and j is new 
+				 renu[i] = -1; // mark 
+				 tj = triangles[j]; // save new
+				 triangles[j]= ti; // new <- old
+				 i=j;     // next 
+				 ti = tj;
+				}  
+			}
+		delete [] renu;
+
+	}
+	/*}}}*/
+	/*FUNCTION Mesh::VerticesRenumber{{{*/
+	void Mesh::VerticesRenumber(long * renu) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ReNumberingVertex)*/
+
+		// warning be carfull because pointer
+		// from on mesh to over mesh 
+		//  --  so do ReNumbering at the beginning
+		BamgVertex * ve = vertices+nbv;
+		long it,ie,i;
+
+		_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){
+		_error_("coefIcoor should be positive, a problem in the geometry is likely");
+	}
+
+	// generation of integer coord  
+	for (i=0;i<nbv;i++) {
+		vertices[i].i = R2ToI2(vertices[i].r);    
+	}
+
+	// computation of the det 
+	int number_of_errors=0;
+	for (i=0;i<nbt;i++) {
+		BamgVertex & v0 = triangles[i][0];
+		BamgVertex & v1 = triangles[i][1];
+		BamgVertex & v2 = triangles[i][2];
+
+		//If this is not a boundary triangle
+		if ( &v0 && &v1 &&  &v2 ){
+
+			/*Compute determinant*/
+			triangles[i].det= det(v0,v1,v2);
+
+			/*Check that determinant is positive*/
+			if (triangles[i].det <=0){
+
+				/*increase number_of_errors and print error only for the first 20 triangles*/
+				number_of_errors++;
+				if (number_of_errors<20){
+					_printLine_("Area of Triangle " << i+1 << " < 0 (det=" << triangles[i].det << ")");
+				}
+			}
+		}
+
+		//else, set as -1
+		else triangles[i].det=-1;
+	}
+
+	if (number_of_errors) _error_("Fatal error: some triangles have negative areas, see above");
+}
+/*}}}*/
+/*FUNCTION Mesh::ShowRegulaty{{{*/
+void  Mesh::ShowRegulaty() const {
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr>*/
+
+	const  double  sqrt32=sqrt(3.)*0.5; 
+	const double  aireKh=sqrt32*0.5;
+	D2  Beq(1,0),Heq(0.5,sqrt32);
+	D2xD2 Br(D2xD2(Beq,Heq).t());
+	D2xD2 B1r(Br.inv());
+	double gammamn=1e100,hmin=1e100;
+	double gammamx=0,hmax=0;
+	double beta=1e100;
+	double beta0=0;
+	double  alpha2=0;
+	double area=0,Marea=0;
+	// double cf= double(coefIcoor);
+	// double cf2= 6.*cf*cf;
+	int nt=0;
+	for (int it=0;it<nbt;it++)
+	 if ( triangles[it].link){
+		 Triangle &K=triangles[it];
+		 double  area3= Area2((R2) K[0],(R2) K[1],(R2) K[2])/6.;
+		 area+= area3;
+		 D2xD2 B_Kt(K[0],K[1],K[2]);
+		 D2xD2 B_K(B_Kt.t());
+		 D2xD2 B1K = Br*B_K.inv();
+		 D2xD2 BK =  B_K*B1r;
+		 D2xD2 B1B1 = B1K.t()*B1K;
+		 Metric MK(B1B1.x.x,B1B1.x.y,B1B1.y.y);
+		 EigenMetric VMK(MK);
+		 alpha2 = Max(alpha2,Max(VMK.lambda1/VMK.lambda2,VMK.lambda2/VMK.lambda1));
+		 double betaK=0;
+
+		 for (int j=0;j<3;j++)
+			{
+			 double he= Norme2(R2(K[j],K[(j+1)%3]));
+			 hmin=Min(hmin,he);
+			 hmax=Max(hmax,he);
+			 BamgVertex & v=K[j];
+			 D2xD2 M((Metric)v);
+			 betaK += sqrt(M.det());
+
+			 D2xD2 BMB = BK.t()*M*BK;
+			 Metric M1(BMB.x.x,BMB.x.y,BMB.y.y);
+			 EigenMetric VM1(M1);
+			 gammamn=Min3(gammamn,VM1.lambda1,VM1.lambda2);
+			 gammamx=Max3(gammamx,VM1.lambda1,VM1.lambda2);		
+			}
+		 betaK *= area3;//  1/2 (somme sqrt(det))* area(K)
+		 Marea+= betaK;
+		 beta=min(beta,betaK);
+		 beta0=max(beta0,betaK);
+		}   
+	area*=3; 
+	gammamn=sqrt(gammamn);
+	gammamx=sqrt(gammamx);    
+	_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){
+				_error_("!t");
+			}
+			BamgVertex & vi = vertices[i];
+			AdjacentTriangle ta(t,EdgesVertexTriangle[vertices[i].IndexInTriangle][0]);
+			BamgVertex *pvj0 = ta.EdgeVertex(0);
+			while (1) {
+				ta=Previous(Adj(ta));
+				if (vertices+i != ta.EdgeVertex(1)){
+					_error_("vertices+i != ta.EdgeVertex(1)");
+				}
+				BamgVertex & vj = *(ta.EdgeVertex(0));
+				if ( &vj ) {
+					j= &vj-vertices;
+					if (j<0 || j >= nbv){
+						_error_("j<0 || j >= nbv");
+					}
+					R2 Aij = (R2) vj - (R2) vi;
+					double ll =  Norme2(Aij);
+					if (0) {  
+						double hi = ll/vi.m(Aij);
+						double hj = ll/vj.m(Aij);
+						if(hi < hj)
+						  {
+							double dh=(hj-hi)/ll;
+							if (dh>logseuil) {
+								vj.m.IntersectWith(vi.m/(1 +logseuil*ll/hi));
+								if(first_np_or_next_t1[j]<0)
+								 kch++,first_np_or_next_t1[j]=Head1,Head1=j;
+							}
+						  }
+					} 
+					else
+					  {
+						double li = vi.m(Aij);
+						if( vj.m.IntersectWith(vi.m/(1 +logseuil*li)) )
+						 if(first_np_or_next_t1[j]<0) // if the metrix change 
+						  kch++,first_np_or_next_t1[j]=Head1,Head1=j;
+					  }
+				}
+				if  ( &vj ==  pvj0 ) break;
+			}
+		}
+		Head0 = Head1;
+		Head1 = -1;
+		Exchange(first_np_or_next_t0,first_np_or_next_t1);
+	}
+	if(verbose>2) _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){
+						_error_("!edgesGtoB");
+					}
+					ong= ProjectOnCurve(*edgesGtoB[Gh.GetId(edges[i].GeomEdgeHook)],
+								edges[i][0],edges[i][1],0.5,vertices[k],
+								newVertexOnBThEdge[kvb],
+								newVerticesOnGeomEdge[kvg++]);
+					vertices[k].ReferenceNumber= edges[i].ReferenceNumber;
+					vertices[k].DirOfSearch =   NoDirOfSearch;        
+					;
+					// get the Info on background mesh 
+					double s =        newVertexOnBThEdge[kvb];
+					BamgVertex &  bv0  = newVertexOnBThEdge[kvb][0];
+					BamgVertex &  bv1  = newVertexOnBThEdge[kvb][1];
+					// compute the metrix of the new points 
+					vertices[k].m =  Metric(1-s,bv0,s,bv1); 
+					kvb++;
+				  }
+				else 
+				  {
+					ong=Gh.ProjectOnCurve(edges[i],
+								0.5,vertices[k],newVerticesOnGeomEdge[kvg++]);
+					// vertices[k].i = R2ToI2( vertices[k].r);
+					vertices[k].ReferenceNumber = edges[i].ReferenceNumber;
+					vertices[k].DirOfSearch = NoDirOfSearch;
+					vertices[k].m =  Metric(0.5,edges[i][0],0.5,edges[i][1]);	      
+				  }  
+			  }
+			else // straigth line edge ---
+			  { 
+				vertices[k].r = ((R2) edges[i][0] + (R2)  edges[i][1] )*0.5;
+				vertices[k].m =  Metric(0.5,edges[i][0],0.5,edges[i][1]);
+				vertices[k].GeomEdgeHook = 0;
+			  }
+			//vertices[k].i = R2ToI2( vertices[k].r);
+			R2 AB =  vertices[k].r;
+			R2 AA = (A+AB)*0.5;
+			R2 BB = (AB+B)*0.5;
+			vertices[k].ReferenceNumber = edges[i].ReferenceNumber;
+			vertices[k].DirOfSearch = NoDirOfSearch;
+
+			newedges[ie].GeomEdgeHook = Gh.Containing(AA,ong);
+			newedges[ie++].v[1]=vertices+k;
+
+			newedges[ie]=edges[i];
+			newedges[ie].adj[0]=newedges + ie -1;
+			newedges[ie].adj[1]=newedges+(edges[i].adj[1]-edges) ;
+			newedges[ie].GeomEdgeHook =  Gh.Containing(BB,ong);
+			newedges[ie++].v[0]=vertices+k;
+			k++;
+		  }
+		if (edgesGtoB) delete [] edgesGtoB;
+		edgesGtoB=0;
+
+		newnbv=k;
+		newNbVerticesOnGeomEdge=kvg;
+		if (newnbv> maxnbv) goto Error;// bug 
+
+		nbv = k;
+
+
+		kedge = new long[3*nbt+1];
+		ksplitarray = new long[nbt+1];
+		ksplit = ksplitarray +1; // because ksplit[-1] == ksplitarray[0]
+
+		for (i=0;i<3*nbt;i++)
+		 kedge[i]=-1;
+
+		//  
+
+		for (i=0;i<nbt;i++) {
+			Triangle & t = triangles[i];
+			if (!t.link){
+				_error_("!t.link");
+			}
+			for(int j=0;j<3;j++)
+			  {
+				const AdjacentTriangle ta = t.Adj(j);
+				const Triangle & tt = ta;
+				if (&tt >= lastT)
+				 t.SetAdj2(j,0,0);// unset adj
+				const BamgVertex & v0 = t[VerticesOfTriangularEdge[j][0]];
+				const BamgVertex & v1 = t[VerticesOfTriangularEdge[j][1]];
+				long  ke =edge4->SortAndFind(GetId(v0),GetId(v1));
+				if (ke>0) 
+				  {
+					long ii = GetId(tt);
+					int  jj = ta;
+					long ks = ke + nbvold;
+					kedge[3*i+j] = ks;
+					if (ii<nbt) // good triangle
+					 kedge[3*ii+jj] = ks;
+					BamgVertex &A=vertices[ks];
+					double aa,bb,cc,dd;
+					if ((dd=Area2(v0.r,v1.r,A.r)) >=0){
+						// warning PB roundoff error 
+						if (t.link && ( (aa=Area2( A.r    , t[1].r , t[2].r )) < 0.0 
+										||   (bb=Area2( t[0].r , A.r    , t[2].r )) < 0.0  
+										||   (cc=Area2( t[0].r , t[1].r , A.r    )) < 0.0)){
+							_printLine_(ke + nbvold << " not in triangle " << i << " In= " << !!t.link << " " << aa << " " << bb << " " << cc << " " << dd);
+							_error_("Number of triangles with P2 interpolation Problem");
+						}
+					}
+					else {
+						if (tt.link && ( (aa=Area2( A.r     , tt[1].r , tt[2].r )) < 0 
+										||   (bb=Area2( tt[0].r , A.r     , tt[2].r )) < 0 
+										||   (cc=Area2( tt[0].r , tt[1].r , A.r     )) < 0)){
+							_printLine_(ke + nbvold << " not in triangle " << ii << " In= " << !!tt.link << " " << aa << " " << bb << " " << cc << " " << dd);
+							_error_("Number of triangles with P2 interpolation Problem");
+						}
+					} 
+				  }
+			  }
+		}
+
+		for (i=0;i<nbt;i++){
+			ksplit[i]=1; // no split by default
+			const Triangle & t = triangles[ i];
+			int nbsplitedge =0;
+			int nbinvisible =0;
+			int invisibleedge=0;
+			int kkk[3];      
+			for (int j=0;j<3;j++)
+			  {
+				if (t.Hidden(j)) invisibleedge=j,nbinvisible++;
+
+				const AdjacentTriangle ta = t.Adj(j);
+				const Triangle & tt = ta;
+
+
+				const BamgVertex & v0 = t[VerticesOfTriangularEdge[j][0]];
+				const BamgVertex & v1 = t[VerticesOfTriangularEdge[j][1]];
+				if ( kedge[3*i+j] < 0) 
+				  {
+					long  ke =edge4->SortAndFind(GetId(v0),GetId(v1));
+					if (ke<0) // new 
+					  {
+						if (&tt) // internal triangles all the boundary 
+						  { // new internal edges 
+							long ii = GetId(tt);
+							int  jj = ta;
+
+							kedge[3*i+j]=k;// save the vertex number 
+							kedge[3*ii+jj]=k;
+							if (k<maxnbv) 
+							  {
+								vertices[k].r = ((R2) v0+(R2) v1 )/2;
+								//vertices[k].i = R2ToI2( vertices[k].r);
+								vertices[k].ReferenceNumber=0;
+								vertices[k].DirOfSearch =NoDirOfSearch;
+								vertices[k].m =  Metric(0.5,v0,0.5,v1);
+							  }
+							k++;
+							kkk[nbsplitedge++]=j;		      
+						  } // tt 
+						else
+						 _error_("Bug...");
+					  } // ke<0	       
+					else
+					  { // ke >=0
+						kedge[3*i+j]=nbvold+ke;
+						kkk[nbsplitedge++]=j;// previously splited
+					  }
+				  }
+				else 
+				 kkk[nbsplitedge++]=j;// previously splited
+
+			  } 
+			if (nbinvisible>=2){
+				_error_("nbinvisible>=2");
+			}
+			switch (nbsplitedge) {
+				case 0: ksplit[i]=10; newnbt++; break;   // nosplit
+				case 1: ksplit[i]=20+kkk[0];newnbt += 2; break; // split in 2 
+				case 2: ksplit[i]=30+3-kkk[0]-kkk[1];newnbt += 3; break; // split in 3 
+				case 3:
+						  if (nbinvisible) ksplit[i]=40+invisibleedge,newnbt += 4;
+						  else   ksplit[i]=10*nfortria,newnbt+=nfortria;
+						  break;
+			} 
+			if (ksplit[i]<40){
+				_error_("ksplit[i]<40");
+			}
+		  }
+		//  now do the element split
+		newnbq = 4*nbq;
+		nbv = k;
+		kkk = nbt;
+		ksplit[-1] = nbt;
+		// look on  old true  triangles 
+
+		for (i=0;i<nbtsave;i++){
+			int  nbmkadj=0;
+			long mkadj [100];
+			mkadj[0]=i;
+			long kk=ksplit[i]/10;
+			int  ke=(int) (ksplit[i]%10);
+			if (kk>=7 || kk<=0){
+				_error_("kk>=7 || kk<=0");
+			}
+
+			// def the numbering   k (edge) i vertex 
+			int k0 = ke;
+			int k1 = NextEdge[k0];
+			int k2 = PreviousEdge[k0];
+			int i0 = OppositeVertex[k0];
+			int i1 = OppositeVertex[k1];
+			int i2 = OppositeVertex[k2];
+
+			Triangle &t0=triangles[i];
+			BamgVertex * v0=t0(i0);           
+			BamgVertex * v1=t0(i1);           
+			BamgVertex * v2=t0(i2);
+
+			if (nbmkadj>=10){
+				_error_("nbmkadj>=10");
+			}
+			// --------------------------
+			AdjacentTriangle ta0(t0.Adj(i0)),ta1(t0.Adj(i1)),ta2(t0.Adj(i2));
+			// save the flag Hidden
+			int hid[]={t0.Hidden(0),t0.Hidden(1),t0.Hidden(2)};
+			// un set all adj -- save Hidden flag --
+			t0.SetAdj2(0,0,hid[0]);
+			t0.SetAdj2(1,0,hid[1]);
+			t0.SetAdj2(2,0,hid[2]);
+			// --  remake 
+			switch  (kk) {
+				case 1: break;// nothing 
+				case 2: // 
+						  {
+							Triangle &t1=triangles[kkk++];
+							t1=t0;
+							if (kedge[3*i+i0]<0){
+								_error_("kedge[3*i+i0]<0");
+							}
+							BamgVertex * v3 = vertices + kedge[3*i+k0];
+
+							t0(i2) = v3;
+							t1(i1) = v3;
+							t0.SetAllFlag(k2,0);
+							t1.SetAllFlag(k1,0);
+						  } 
+						break; 
+				case 3: //
+						  {
+							Triangle &t1=triangles[kkk++];
+							Triangle &t2=triangles[kkk++];
+							t2=t1=t0;
+							if (kedge[3*i+k1]<0){
+								_error_("kedge[3*i+k1]<0");
+							}
+							if (kedge[3*i+k2]<0){
+								_error_("kedge[3*i+k2]<0");
+							}
+
+							BamgVertex * v01 = vertices + kedge[3*i+k2];
+							BamgVertex * v02 = vertices + kedge[3*i+k1]; 
+							t0(i1) = v01; 
+							t0(i2) = v02; 
+							t1(i2) = v02;
+							t1(i0) = v01; 
+							t2(i0) = v02; 
+							t0.SetAllFlag(k0,0);
+							t1.SetAllFlag(k1,0);
+							t1.SetAllFlag(k0,0);
+							t2.SetAllFlag(k2,0);
+						  } 
+						break;
+				case 4: // 
+				case 6: // split in 4 
+						  {
+							Triangle &t1=triangles[kkk++];
+							Triangle &t2=triangles[kkk++];
+							Triangle &t3=triangles[kkk++];
+							t3=t2=t1=t0;
+							if (kedge[3*i+k0] <0 || kedge[3*i+k1]<0 || kedge[3*i+k2]<0){
+								_error_("kedge[3*i+k0] <0 || kedge[3*i+k1]<0 || kedge[3*i+k2]<0");
+							}
+							BamgVertex * v12 = vertices + kedge[3*i+k0];
+							BamgVertex * v02 = vertices + kedge[3*i+k1]; 
+							BamgVertex * v01 = vertices + kedge[3*i+k2];
+							t0(i1) = v01;
+							t0(i2) = v02;
+							t0.SetAllFlag(k0,hid[k0]);
+
+							t1(i0) = v01;
+							t1(i2) = v12;
+							t0.SetAllFlag(k1,hid[k1]);
+
+							t2(i0) = v02;
+							t2(i1) = v12;
+							t2.SetAllFlag(k2,hid[k2]);
+
+							t3(i0) = v12;
+							t3(i1) = v02;
+							t3(i2) = v01;
+
+							t3.SetAllFlag(0,hid[0]);	   
+							t3.SetAllFlag(1,hid[1]);	   
+							t3.SetAllFlag(2,hid[2]);
+
+							if ( kk == 6)
+							  {
+
+								Triangle &t4=triangles[kkk++];
+								Triangle &t5=triangles[kkk++];
+
+								t4 = t3;
+								t5 = t3;
+
+								t0.SetHidden(k0);
+								t1.SetHidden(k1);
+								t2.SetHidden(k2);
+								t3.SetHidden(0);
+								t4.SetHidden(1);
+								t5.SetHidden(2);
+
+								if (nbv < maxnbv ) 
+								  {
+									vertices[nbv].r = ((R2) *v01 + (R2) *v12  + (R2) *v02 ) / 3.0;
+									vertices[nbv].ReferenceNumber =0;
+									vertices[nbv].DirOfSearch =NoDirOfSearch;
+									//vertices[nbv].i = R2ToI2(vertices[nbv].r);
+									double a3[]={1./3.,1./3.,1./3.};
+									vertices[nbv].m = Metric(a3,v0->m,v1->m,v2->m);
+									BamgVertex * vc =  vertices +nbv++;
+									t3(i0) = vc;
+									t4(i1) = vc;
+									t5(i2) = vc;
+
+								  }
+								else
+								 goto Error; 
+							  }
+
+						  } 
+						break;         
+			}
+
+			// save all the new triangles
+			mkadj[nbmkadj++]=i;
+			long jj;
+			if (t0.link) 
+			 for (jj=nbt;jj<kkk;jj++)
+				{
+				 triangles[jj].link=t0.link;
+				 t0.link= triangles+jj;
+				 mkadj[nbmkadj++]=jj;
+				}
+			if (nbmkadj>13){// 13 = 6 + 4 +
+				_error_("nbmkadj>13");
+			}
+
+			if (kk==6)  newnbq+=3;
+			for (jj=ksplit[i-1];jj<kkk;jj++) nbt = kkk;
+			ksplit[i]= nbt; // save last adresse of the new triangles
+			kkk = nbt;
+		  }
+
+		for (i=0;i<nbv;i++) vertices[i].m = vertices[i].m*2.;
+
+		if(withBackground)
+		 for (i=0;i<BTh.nbv;i++)
+		  BTh.vertices[i].m =  BTh.vertices[i].m*2.;
+
+
+		ret = 2;
+		if (nbt>= maxnbt) goto Error; // bug 
+		if (nbv>= maxnbv) goto Error; // bug 
+		// generation of the new triangles 
+
+		SetIntCoor("In SplitElement"); 
+
+		CreateSingleVertexToTriangleConnectivity();
+		if(withBackground)
+		 BTh.CreateSingleVertexToTriangleConnectivity();
+
+		delete [] edges;
+		edges = newedges;
+		nbe = newnbe;
+		nbq = newnbq;
+
+		for (i=0;i<nbsubdomains;i++)
+		  { 
+			long k = subdomains[i].edge- edges;
+			subdomains[i].edge =  edges+2*k; // spilt all edge in 2 
+		  }
+
+		if (ksplitarray) delete [] ksplitarray;
+		if (kedge) delete [] kedge;
+		if (edge4) delete edge4;
+		if (VerticesOnGeomEdge) delete [] VerticesOnGeomEdge;
+		VerticesOnGeomEdge= newVerticesOnGeomEdge;
+		if(VertexOnBThEdge) delete []  VertexOnBThEdge;
+		VertexOnBThEdge = newVertexOnBThEdge;
+		NbVerticesOnGeomEdge = newNbVerticesOnGeomEdge;
+		NbVertexOnBThEdge=newNbVertexOnBThEdge;
+		//  CreateSingleVertexToTriangleConnectivity();
+
+		ReconstructExistingMesh();
+
+		if (verbose>2){
+			_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
+				_error_("!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) _error_("no starting triangle provided and no quadtree available");
+
+		/*Call NearestVertex*/
+		BamgVertex *a = quadtree->NearestVertex(B.x,B.y) ;
+
+		/*Check output (Vertex a)*/
+		if (!a)    _error_("problem while trying to find nearest vertex from a given point. No output found");
+		if (!a->t) _error_("no triangle is associated to vertex number " << GetId(a)+1 << " (orphan?)");
+		_assert_(a>=vertices && a<vertices+nbv);
+
+		/*Get starting triangle*/
+		t = a->t;
+		_assert_(t>=triangles && t<triangles+nbt);
+	}
+
+	Icoor2  detop ;
+
+	/*initialize number of test triangle*/
+	counter=0; 
+
+	/*The initial triangle might be outside*/
+	while (t->det < 0){ 
+
+		/*Get a real vertex from this triangle (k0)*/
+		int k0=(*t)(0)?(((*t)(1)?((*t)(2)?-1:2):1)):0;
+		_assert_(k0>=0);// k0 the NULL vertex
+		int k1=NextVertex[k0],k2=PreviousVertex[k0];
+		det3[k0]=det(B,(*t)[k1],(*t)[k2]);
+		det3[k1]=det3[k2]=-1;     
+		if (det3[k0] > 0) // outside B 
+		 return t; 
+		t = t->TriangleAdj(OppositeEdge[k0]);
+		counter++;
+		_assert_(counter<2);
+	}
+
+	jj=0;
+	detop = det(*(*t)(VerticesOfTriangularEdge[jj][0]),*(*t)(VerticesOfTriangularEdge[jj][1]),B);
+
+	while(t->det>0) { 
+
+		/*Increase counter*/
+		if (++counter>=10000) _error_("Maximum number of iteration reached (threshold = " << counter << ").");
+
+		j= OppositeVertex[jj];
+		det3[j] = detop;  //det(*b,*s1,*s2);
+		jn = NextVertex[j];
+		jp = PreviousVertex[j];
+		det3[jp]= det(*(*t)(j),*(*t)(jn),B);
+		det3[jn] = t->det-det3[j] -det3[jp];
+
+		// count the number k of  det3 <0
+		int k=0,ii[3];
+		if (det3[0] < 0 ) ii[k++]=0; 
+		if (det3[1] < 0 ) ii[k++]=1;
+		if (det3[2] < 0 ) ii[k++]=2;
+		// 0 => ok
+		// 1 => go in way 1
+		// 2 => two way go in way 1 or 2 randomly
+
+		if (k==0) break;
+		if (k==2 && BinaryRand()) Exchange(ii[0],ii[1]);
+		_assert_(k<3);
+		AdjacentTriangle t1 = t->Adj(jj=ii[0]);
+		if ((t1.det() < 0 ) && (k == 2))
+		 t1 = t->Adj(jj=ii[1]);
+		t=t1;
+		j=t1;// for optimisation we now the -det[OppositeVertex[j]];
+		detop = -det3[OppositeVertex[jj]];
+		jj = j;
+	}
+
+	if (t->det<0) // outside triangle 
+	 det3[0]=det3[1]=det3[2]=-1,det3[OppositeVertex[jj]]=detop;
+	return t;
+}
+/*}}}*/
+/*FUNCTION Mesh::TriangleIntNumbering{{{*/
+void Mesh::TriangleIntNumbering(long* renumbering){
+
+	long num=0;
+	for (int i=0;i<nbt;i++){
+		if (triangles[i].det>0) renumbering[i]=num++;
+		else renumbering[i]=-1;
+	}
+	return;   
+}
+/*}}}*/
+/*FUNCTION Mesh::TriangleReferenceList{{{*/
+long  Mesh::TriangleReferenceList(long* reft) const {
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ConsRefTriangle)*/
+
+	long int verbose=0;
+	register Triangle *t0,*t;
+	register long k=0, num;   
+
+	//initialize all triangles as -1 (outside)
+	for (int it=0;it<nbt;it++) reft[it]=-1;
+
+	//loop over all subdomains
+	for (int i=0;i<nbsubdomains;i++){ 
+
+		//first triangle of the subdomain i
+		t=t0=subdomains[i].head;
+
+		//check that the subdomain is not empty
+		if (!t0){ _error_("At least one subdomain is empty");}
+
+		//loop
+		do{
+			k++;
+
+			//get current triangle number
+			num = GetId(t);
+
+			//check that num is in [0 nbt[
+			_assert_(num>=0 && num<nbt);
+
+			//reft of this triangle is the subdomain number
+			reft[num]=i;
+
+		} while (t0 != (t=t->link));
+		//stop when all triangles of subdomains have been tagged
+
+	}
+	return k;   
+}
+/*}}}*/
+/*FUNCTION Mesh::Triangulate{{{*/
+void Mesh::Triangulate(double* x,double* y,int nods){
+
+	int verbose=0;
+	int i;
+	Metric M1(1);
+
+	/*Initialize mesh*/
+	Init(nods);//this resets nbv to 0
+	nbv=nods;
+
+	//Vertices
+	if(verbose) _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) _error_("too many vertices on geometry: " << NbVerticesOnGeomVertex << " >= " << maxnbv);
+		_assert_(nbv==0);
+		//Build VerticesOnGeomVertex
+		for (i=0;i<Gh.nbv;i++){
+			/* Add vertex only if required*/
+			if (Gh[i].Required()) {//Gh  vertices Required
+
+				//Add the vertex
+				_assert_(nbv<maxnbv);
+				vertices[nbv]=Gh[i];
+				
+				//Add pointer from geometry (Gh) to vertex from mesh (Th)
+				Gh[i].MeshVertexHook=vertices+nbv;
+
+				//Build VerticesOnGeomVertex for current point
+				VerticesOnGeomVertex[nbv]=VertexOnGeom(*Gh[i].MeshVertexHook,Gh[i]);
+
+				//nbv increment
+				nbv++;
+			}
+		}
+
+		/*Build VerticesOnGeomEdge*/
+
+		//check that edges is still empty (Init)
+		_assert_(!edges);
+
+		/* Now we are going to create the first edges corresponding
+		 * to the one present in the geometry provided.
+		 * We proceed in 2 steps
+		 *  -step 0: we count all the edges
+		 *           we allocate the number of edges at the end of step 0
+		 *  -step 1: the edges are created */
+		for (int step=0;step<2;step++){
+
+			//initialize number of edges and number of edges max
+			long nbex=0;
+			nbe=0;
+			long NbVerticesOnGeomEdge0=NbVerticesOnGeomEdge;
+			Gh.UnMarkEdges();	
+			nbcurves=0;
+
+			//go through the edges of the geometry
+			for (i=0;i<Gh.nbe;i++){
+
+				//ei = current Geometrical edge
+				GeomEdge &ei=Gh.edges[i];   
+
+				//loop over the two vertices of the edge ei
+				for(int j=0;j<2;j++) {
+
+					/*Take only required vertices (corner->beginning of a new curve)*/
+					if (!ei.Mark() && ei[j].Required()){ 
+
+						long  nbvend=0;
+						Edge* PreviousNewEdge=NULL;
+						lstep = -1;
+
+						/*If Edge is required (do that only once for the 2 vertices)*/
+						if(ei.Required()){
+							if (j==0){
+								//do not create internal points if required (take it as is)
+								if(step==0) nbe++;
+								else{ 
+									e=&ei;
+									a=ei(0);
+									b=ei(1);
+
+									//check that edges has been allocated
+									_assert_(edges);
+									edges[nbe].v[0]=a->MeshVertexHook;
+									edges[nbe].v[1]=b->MeshVertexHook;;
+									edges[nbe].ReferenceNumber = e->ReferenceNumber;
+									edges[nbe].GeomEdgeHook = e;
+									edges[nbe].adj[0] = 0;
+									edges[nbe].adj[1] = 0;
+									nbe++;
+								}
+							}
+						}
+
+						/*If Edge is not required: we are on a curve*/
+						else {
+							for (int kstep=0;kstep<=step;kstep++){
+								//kstep=0, compute number of edges (discretize curve)
+								//kstep=1  create the points and edge
+								PreviousNewEdge=0;
+								NbNewPoints=0;
+								NbEdgeCurve=0;
+								if (nbvend>=maxnbv) _error_("maximum number of vertices too low! Check the domain outline or increase maxnbv");
+								lcurve =0;
+								s = lstep; //-1 initially, then length of each sub edge
+
+								/*reminder: i = edge number, j=[0;1] vertex index in edge*/
+								k=j;            // k = vertex index in edge (0 or 1)
+								e=&ei;          // e = reference of current edge
+								a=ei(k);        // a = pointer toward the kth vertex of the current edge
+								va = a->MeshVertexHook; // va = pointer toward mesh vertex associated
+								e->SetMark();   // Mark edge
+
+								/*Loop until we reach the end of the curve*/
+								for(;;){ 
+									k = 1-k;            // other vertx index of the curve
+									b = (*e)(k);        // b = pointer toward the other vertex of the current edge
+									AB= b->r - a->r;   // AB = vector of the current edge
+									Metric MA = background ? BTh.MetricAt(a->r) :a->m ;  //Get metric associated to A
+									Metric MB = background ? BTh.MetricAt(b->r) :b->m ;  //Get metric associated to B
+									double ledge = (MA(AB) + MB(AB))/2;                  //Get edge length in metric
+
+									/* We are now creating the mesh edges from the geometrical edge selected above.
+									 * The edge will be divided according to the metric previously computed and cannot
+									 * be divided more than 10 times (MaxSubEdge). */
+
+									//By default, there is only one subedge that is the geometrical edge itself
+									int NbSubEdge = 1;
+
+									//initialize lSubEdge, holding the length of each subedge (cannot be higher than 10)
+									double lSubEdge[MaxSubEdge];
+
+									//Build Subedges according to the edge length
+									if (ledge < 1.5){
+										//if ledge < 1.5 (between one and 2), take the edge as is
+										lSubEdge[0] = ledge;
+									}
+									//else, divide the edge
+									else {
+										//compute number of subedges (division of the edge), Maximum is 10
+										NbSubEdge = Min( MaxSubEdge, (int) (ledge +0.5));
+										/*Now, we are going to divide the edge according to the metric.
+										 * Get segment by sement along the edge.
+										 * Build lSubEdge, which holds the distance between the first vertex
+										 * of the edge and the next point on the edge according to the 
+										 * discretization (each SubEdge is AB)*/
+										R2 A,B;
+										A=a->r;
+										Metric MAs=MA,MBs;
+										ledge=0; 
+										double x =0, xstep= 1./NbSubEdge;
+										for (int kk=0; kk < NbSubEdge; kk++,A=B,MAs=MBs ) {
+											x += xstep;
+											B =  e->F(k ? x : 1-x);
+											MBs= background ? BTh.MetricAt(B) : Metric(1-x,MA,x,MB);
+											AB = A-B;
+											lSubEdge[kk]=(ledge+=(MAs(AB)+MBs(AB))/2);
+										}
+									}
+
+									double lcurveb = lcurve+ledge;
+
+									/*Now, create corresponding points*/
+									while(s>=lcurve && s<=lcurveb && nbv<nbvend){
+
+										/*Schematic of current curve
+										 *
+										 *  a                   vb                  b          // vertex
+										 *  0              ll0     ll1              ledge      // length from a
+										 *  + --- + - ... - + --S-- + --- + - ... - +          // where is S
+										 *  0              kk0     kk1              NbSubEdge  // Sub edge index
+										 *
+										 */
+
+										double ss = s-lcurve;
+
+										/*Find the SubEdge containing ss using Dichotomy*/
+										int kk0=-1,kk1=NbSubEdge-1,kkk;
+										double ll0=0,ll1=ledge,llk;
+										while (kk1-kk0>1){
+											if (ss < (llk=lSubEdge[kkk=(kk0+kk1)/2]))
+											 kk1=kkk,ll1=llk;
+											else
+											 kk0=kkk,ll0=llk;
+										}
+										_assert_(kk1!=kk0);
+
+										/*Curvilinear coordinate in [0 1] of ss in current edge*/
+										// WARNING: This is what we would do
+										// ssa = (ss-ll0)/(ll1-ll0);
+										// aa = (kk0+ssa)/NbSubEdge
+										// This is what Bamg does:
+										double sbb = (ss-ll0)/(ll1-ll0);
+										/*Curvilinear coordinate in [0 1] of ss in current curve*/
+										double bb = (kk1+sbb)/NbSubEdge;
+										double aa = 1-bb;
+
+										// new vertex on edge
+										vb = &vertices[nbv++];
+										vb->m = Metric(aa,a->m,bb,b->m);
+										vb->ReferenceNumber = e->ReferenceNumber;
+										vb->DirOfSearch =NoDirOfSearch;
+										double abcisse = k ? bb : aa;
+										vb->r =  e->F(abcisse);
+										VerticesOnGeomEdge[NbVerticesOnGeomEdge++]= VertexOnGeom(*vb,*e,abcisse);        
+
+										// to take into account the direction of the edge
+										s += lstep;
+										edges[nbe].v[0]=va;
+										edges[nbe].v[1]=vb;
+										edges[nbe].ReferenceNumber =e->ReferenceNumber;
+										edges[nbe].GeomEdgeHook = e;
+										edges[nbe].adj[0] = PreviousNewEdge;
+										if(PreviousNewEdge) PreviousNewEdge->adj[1]=&edges[nbe];
+										PreviousNewEdge=edges+nbe;
+										nbe++;
+										va = vb;
+									}
+									
+									/*We just added one edge to the curve: Go to the next one*/
+									lcurve = lcurveb;
+									e->SetMark();
+									a=b;
+
+									/*If b is required, we are on a new curve->break*/
+									if (b->Required()) break;
+									int kprev=k;
+									k = e->AdjVertexIndex[kprev];// next vertices
+									e = e->Adj[kprev];
+									_assert_(e);
+								}// for(;;)
+								vb = b->MeshVertexHook;
+
+								/*Number of edges in the last disretized curve*/
+								NbEdgeCurve = Max((long) (lcurve +0.5), (long) 1);
+								/*Number of internal vertices in the last disretized curve*/
+								NbNewPoints = NbEdgeCurve-1;
+								if(!kstep){
+									NbVerticesOnGeomEdge0 += NbNewPoints;
+									nbcurves++;
+								}
+								nbvend=nbv+NbNewPoints; 
+								lstep = lcurve / NbEdgeCurve; //approximately one
+							}// end of curve --
+							if (edges) { // last edges of the curves 
+								edges[nbe].v[0]=va;
+								edges[nbe].v[1]=vb;
+								edges[nbe].ReferenceNumber = e->ReferenceNumber;
+								edges[nbe].GeomEdgeHook = e;
+								edges[nbe].adj[0] = PreviousNewEdge;
+								edges[nbe].adj[1] = 0;
+								if(PreviousNewEdge) PreviousNewEdge->adj[1] = & edges[nbe];
+								nbe++;
+							}
+							else nbe += NbEdgeCurve;
+						} // end on  curve ---
+					}
+				}
+			} // for (i=0;i<nbe;i++)
+			if(!step) {
+				_assert_(!edges);
+				_assert_(!VerticesOnGeomEdge);
+
+				edges = new Edge[nbex=nbe];
+				if(NbVerticesOnGeomEdge0) VerticesOnGeomEdge = new VertexOnGeom[NbVerticesOnGeomEdge0];
+
+				// do the vertex on a geometrical vertex
+				_assert_(VerticesOnGeomEdge || NbVerticesOnGeomEdge0==0);
+				NbVerticesOnGeomEdge0 = NbVerticesOnGeomEdge;       
+			}
+			else{
+				_assert_(NbVerticesOnGeomEdge==NbVerticesOnGeomEdge0);
+			}
+		}
+
+		//Insert points inside existing triangles
+		if (verbose>4) _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){
+			_error_("too many vertices on geometry: " << NbVerticesOnGeomVertex << " >= " << maxnbv);
+		}
+
+		VerticesOnGeomVertex = new VertexOnGeom[  NbVerticesOnGeomVertex];
+		VertexOnBThVertex    = new VertexOnVertex[NbVerticesOnGeomVertex];
+
+		//At this point there is NO vertex but vertices should have been allocated by Init
+		_assert_(vertices);
+		for (i=0;i<Gh.nbv;i++){
+			if (Gh[i].Required()) {//Gh vertices Required
+				vertices[nbv]  =Gh[i];
+				vertices[nbv].i=I2(0,0);
+				Gh[i].MeshVertexHook = vertices + nbv;// save Geom -> Th
+				VerticesOnGeomVertex[nbv]= VertexOnGeom(vertices[nbv],Gh[i]);
+				nbv++;
+			}
+			else Gh[i].MeshVertexHook=0;
+		} 
+		for (i=0;i<BTh.NbVerticesOnGeomVertex;i++){ 
+			VertexOnGeom &vog=BTh.VerticesOnGeomVertex[i];
+			if (vog.IsRequiredVertex()){
+				GeomVertex* gv=vog;
+				BamgVertex *bv = vog;
+				_assert_(gv->MeshVertexHook); // use of Geom -> Th
+				VertexOnBThVertex[NbVertexOnBThVertex++]=VertexOnVertex(gv->MeshVertexHook,bv);
+				gv->MeshVertexHook->m = bv->m; // for taking the metric of the background mesh
+			}
+		}
+		_assert_(NbVertexOnBThVertex==NbVerticesOnGeomVertex); /*This might be due to MaxCornerAngle too small*/
+
+		/*STEP 2: reseed boundary edges*/
+
+		//  find the begining of the curve in BTh
+		Gh.UnMarkEdges();	
+		int bfind=0;
+		for (int i=0;i<Gh.nbcurves;i++) bcurve[i]=-1; 
+
+		/*Loop over the backgrounf mesh BTh edges*/
+		for (int iedge=0;iedge<BTh.nbe;iedge++){      
+			Edge &ei = BTh.edges[iedge];
+
+			/*Loop over the 2 vertices of the current edge*/
+			for(int je=0;je<2;je++){
+
+				/* If one of the vertex is required we are in a new curve*/
+				if (ei[je].GeomEdgeHook->IsRequiredVertex()){ 
+
+					/*Get curve number*/
+					int nc=ei.GeomEdgeHook->CurveNumber;
+					
+					//_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;
+			_error_("problem generating number of curves (" << Gh.nbcurves << " found in the geometry but " << bfind << " curve found in the mesh)");
+		}
+
+		// method in 2 + 1 step 
+		//  0.0) compute the length and the number of vertex to do allocation
+		//  1.0) recompute the length
+		//  1.1) compute the  vertex 
+
+		long nbex=0,NbVerticesOnGeomEdgex=0;
+		for (int step=0; step <2;step++){
+
+			long NbOfNewPoints=0;
+			long NbOfNewEdge=0;
+			long iedge;
+			Gh.UnMarkEdges();	
+			double L=0;
+
+			/*Go through all geometrical curve*/
+			for (int icurve=0;icurve<Gh.nbcurves;icurve++){ 
+
+				/*Get edge and vertex (index) of background mesh on this curve*/
+				iedge=bcurve[icurve]/2;
+				int jedge=bcurve[icurve]%2;
+
+				/*Get edge of Bth with index iedge*/
+				Edge &ei = BTh.edges[iedge];
+			
+				/*Initialize variables*/
+				double Lstep=0,Lcurve=0;    // step between two points   (phase==1) 
+				long NbCreatePointOnCurve=0;// Nb of new points on curve (phase==1) 
+
+				/*Do phase 0 to step*/
+				for(int phase=0;phase<=step;phase++){
+
+					/*Current curve pointer*/
+					Curve *curve= Gh.curves+icurve;
+
+					/*Get index of current curve*/
+					int icurveequi= Gh.GetId(curve);
+
+					/*For phase 0, check that we are at the begining of the curve only*/
+					if(phase==0 &&  icurveequi!=icurve)  continue;
+
+					int   k0=jedge,k1;
+					Edge* pe=  BTh.edges+iedge;
+					int   iedgeequi=bcurve[icurveequi]/2;
+					int   jedgeequi=bcurve[icurveequi]%2;
+
+					int k0equi=jedgeequi,k1equi;		  
+					Edge * peequi= BTh.edges+iedgeequi;
+					GeomEdge *ongequi = peequi->GeomEdgeHook;
+
+					double sNew=Lstep;// abscisse of the new points (phase==1) 
+					L=0;// length of the curve
+					long i=0;// index of new points on the curve
+					register GeomVertex * GA0 = *(*peequi)[k0equi].GeomEdgeHook;
+					BamgVertex *A0;
+					A0 = GA0->MeshVertexHook;  // the vertex in new mesh
+					BamgVertex *A1;
+					VertexOnGeom *GA1;
+					Edge* PreviousNewEdge = 0;
+
+					// New Curve phase 
+					_assert_(A0-vertices>=0 && A0-vertices<nbv);
+					if(ongequi->Required()){
+						GeomVertex *GA1 = *(*peequi)[1-k0equi].GeomEdgeHook;
+						A1 = GA1->MeshVertexHook;  //
+					}       
+					else {
+						for(;;){
+							Edge &ee=*pe; 
+							Edge &eeequi=*peequi; 
+							k1 = 1-k0; // next vertex of the edge 
+							k1equi= 1 - k0equi;
+							_assert_(pe && ee.GeomEdgeHook);
+							ee.GeomEdgeHook->SetMark();
+							BamgVertex & v0=ee[0], & v1=ee[1];
+							R2 AB=(R2)v1-(R2)v0;
+							double L0=L,LAB;
+							LAB=LengthInterpole(v0.m,v1.m,AB);
+							L+= LAB;
+
+							if (phase){
+								// computation of the new points for the given curve
+								while ((i!=NbCreatePointOnCurve) && sNew<=L) { 
+
+									//some checks
+									_assert_(sNew>=L0);
+									_assert_(LAB);
+									_assert_(vertices && nbv<maxnbv);
+									_assert_(edges && nbe<nbex);
+									_assert_(VerticesOnGeomEdge && NbVerticesOnGeomEdge<NbVerticesOnGeomEdgex);
+
+									// new vertex on edge
+									A1=vertices+nbv++;
+									GA1=VerticesOnGeomEdge+NbVerticesOnGeomEdge;
+									Edge* e = edges + nbe++;
+									double se= (sNew-L0)/LAB;
+									if (se<0 || se>=1.000000001){
+										_error_("Problem creating point on a boundary: se=" << se << " should be in [0 1]");
+									}
+									se = abscisseInterpole(v0.m,v1.m,AB,se,1);
+									if (se<0 || se>1){
+										_error_("Problem creating point on a boundary: se=" << se << " should be in [0 1]");
+									}
+									se = k1         ? se : 1. - se;
+									se = k1==k1equi ? se : 1. - se;
+									VertexOnBThEdge[NbVerticesOnGeomEdge++] = VertexOnEdge(A1,&eeequi,se); // save 
+									ongequi=Gh.ProjectOnCurve(eeequi,se,*A1,*GA1); 
+									A1->ReferenceNumber = eeequi.ReferenceNumber;
+									A1->DirOfSearch =NoDirOfSearch;
+									e->GeomEdgeHook = ongequi;
+									e->v[0]=A0;
+									e->v[1]=A1;
+									e->ReferenceNumber = eeequi.ReferenceNumber;
+									e->adj[0]=PreviousNewEdge;
+
+									if (PreviousNewEdge) PreviousNewEdge->adj[1]=e;
+									PreviousNewEdge=e;
+									A0=A1;
+									sNew += Lstep;
+									if (++i== NbCreatePointOnCurve) break;
+								}
+							}
+
+							//some checks
+							_assert_(ee.GeomEdgeHook->CurveNumber==ei.GeomEdgeHook->CurveNumber);
+							if (ee[k1].GeomEdgeHook->IsRequiredVertex()) {
+								_assert_(eeequi[k1equi].GeomEdgeHook->IsRequiredVertex());
+								register GeomVertex * GA1 = *eeequi[k1equi].GeomEdgeHook;
+								A1=GA1->MeshVertexHook;// the vertex in new mesh
+								_assert_(A1-vertices>=0 && A1-vertices<nbv);
+								break;
+							}
+							if (!ee.adj[k1]) {
+								_error_("adj edge " << BTh.GetId(ee) << ", nbe=" << nbe << ", Gh.vertices=" << Gh.vertices);
+							}
+							pe = ee.adj[k1]; // next edge
+							k0 = pe->Intersection(ee); 
+							peequi= eeequi.adj[k1equi];  // next edge
+							k0equi=peequi->Intersection(eeequi);            
+						}// for(;;) end of the curve
+					}
+
+
+					if (phase){ // construction of the last edge
+						Edge* e=edges + nbe++;
+						e->GeomEdgeHook  = ongequi;
+						e->v[0]=A0;
+						e->v[1]=A1;
+						e->ReferenceNumber = peequi->ReferenceNumber;
+						e->adj[0]=PreviousNewEdge;
+						e->adj[1]=0;
+						if (PreviousNewEdge) PreviousNewEdge->adj[1]=e;
+						PreviousNewEdge = e;
+
+						_assert_(i==NbCreatePointOnCurve);
+					}
+
+					if (!phase)  { // 
+						long NbSegOnCurve = Max((long)(L+0.5),(long) 1);// nb of seg
+						Lstep = L/NbSegOnCurve; 
+						Lcurve = L;
+						NbCreatePointOnCurve = NbSegOnCurve-1;
+						NbOfNewEdge += NbSegOnCurve;
+						NbOfNewPoints += NbCreatePointOnCurve;
+					}
+				}
+			}//  end of curve loop 
+
+			//Allocate memory
+			if(step==0){
+				if(nbv+NbOfNewPoints > maxnbv) {
+					_error_("too many vertices on geometry: " << nbv+NbOfNewPoints << " >= " << maxnbv);
+				}
+				edges = new Edge[NbOfNewEdge];
+				nbex = NbOfNewEdge;
+				if(NbOfNewPoints) {
+					VerticesOnGeomEdge    = new VertexOnGeom[NbOfNewPoints];
+					NbVertexOnBThEdge     = NbOfNewPoints;
+					VertexOnBThEdge       = new  VertexOnEdge[NbOfNewPoints];
+					NbVerticesOnGeomEdgex = NbOfNewPoints;
+				}
+				NbOfNewPoints =0;
+				NbOfNewEdge = 0;
+			}
+		}
+		_assert_(nbe!=0);
+		delete [] bcurve;
+
+		//Insert points inside existing triangles
+		if (verbose>4) _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){
+			_error_("k<0");
+		}
+		int kkk=0;  
+		Icoor2 IJ_IA,IJ_AJ;
+		AdjacentTriangle edge(t,OppositeEdge[k]);          
+		for (;;edge = dir >0 ? Next(Adj(Next(edge))) : Previous(Adj(Previous(edge)))) {  
+			kkk++;
+			if (kkk>=1000){
+				_error_("kkk>=1000");
+			}
+			BamgVertex  &vI =  *edge.EdgeVertex(0);
+			BamgVertex  &vJ =  *edge.EdgeVertex(1);
+			I2 I=vI, J=vJ, IJ= J-I;
+			IJ_IA = (IJ ,(A-I));
+			if (IJ_IA<0) {
+				if (dir>0) {a=1;b=0;return edge;}// change of signe => I
+				else {dir=-1;
+					continue;}};// go in direction i 
+					IJ_AJ = (IJ ,(J-A));
+					if (IJ_AJ<0) {
+						if(dir<0)  {a=0;b=1;return edge;}            
+						else {dir = 1;
+							continue;}}// go in direction j
+							double IJ2 = IJ_IA + IJ_AJ;
+							if (IJ2==0){
+								_error_("IJ2==0");
+							}
+							a= IJ_AJ/IJ2;
+							b= IJ_IA/IJ2;
+							return edge;
+		  } 
+	}
+	/*}}}*/
+/*FUNCTION ForceEdge{{{*/
+int ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret)  { 
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/ForceEdge)*/
+
+	int NbSwap =0;
+	if (!a.t || !b.t){ // the 2 vertex is in a mesh
+		_error_("!a.t || !b.t");
+	}
+	int k=0;
+	taret=AdjacentTriangle(0,0); // erreur 
+
+	AdjacentTriangle tta(a.t,EdgesVertexTriangle[a.IndexInTriangle][0]);
+	BamgVertex   *v1, *v2 = tta.EdgeVertex(0),*vbegin =v2;
+	// we turn around a in the  direct direction  
+
+	Icoor2 det2 = v2 ? det(*v2,a,b): -1 , det1;
+	if(v2) // normal case 
+	 det2 = det(*v2,a,b);
+	else { // no chance infini vertex try the next
+		tta= Previous(Adj(tta));
+		v2 = tta.EdgeVertex(0);
+		vbegin =v2;
+		if (!v2){
+			_error_("!v2");
+		}
+		det2 = det(*v2,a,b);
+	}
+
+	while (v2 != &b) {
+		AdjacentTriangle tc = Previous(Adj(tta));    
+		v1 = v2; 
+		v2 = tc.EdgeVertex(0);
+		det1 = det2;
+		det2 =  v2 ? det(*v2,a,b): det2; 
+
+		if((det1 < 0) && (det2 >0)) { 
+			// try to force the edge 
+			BamgVertex * va = &a, *vb = &b;
+			tc = Previous(tc);
+			if (!v1 || !v2){
+				_error_("!v1 || !v2");
+			}
+			Icoor2 detss = 0,l=0,ks;
+			while ((ks=SwapForForcingEdge(  va,  vb, tc, detss, det1,det2,NbSwap)))
+			 if(l++ > 10000000) {
+				 _error_("Loop in forcing Egde, nb de swap=" << NbSwap << ", nb of try swap (" << l << ") too big");
+			 }
+			BamgVertex *aa = tc.EdgeVertex(0), *bb = tc.EdgeVertex(1);
+			if (( aa == &a ) && (bb == &b) ||  (bb ==  &a ) && (aa == &b)) {
+				tc.SetLock();
+				a.Optim(1,0);
+				b.Optim(1,0);
+				taret = tc;
+				return NbSwap;
+			}
+			else 
+			  {
+				taret = tc;
+				return -2; // error  boundary is crossing
+			  }
+		}
+		tta = tc;
+		k++;
+		if (k>=2000){
+			_error_("k>=2000");
+		}
+		if ( vbegin == v2 ) return -1;// error 
+	}
+
+	tta.SetLock();
+	taret=tta;
+	a.Optim(1,0);
+	b.Optim(1,0);
+	return NbSwap; 
+}
+/*}}}*/
+/*FUNCTION swap{{{*/
+void  swap(Triangle *t1,short a1, Triangle *t2,short a2, BamgVertex *s1,BamgVertex *s2,Icoor2 det1,Icoor2 det2){ 
+	/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/swap)*/
+	// --------------------------------------------------------------
+	// short a2=aa[a];// les 2 numero de l arete dans les 2 triangles
+	//                               
+	//               sb                     sb    
+	//             / | \                   /   \                      !
+	//         as1/  |  \                 /a2   \                     !
+	//           /   |   \               /    t2 \                    !
+	//       s1 /t1  | t2 \s2  -->   s1 /___as2___\s2                 !
+	//          \  a1|a2  /             \   as1   /  
+	//           \   |   /               \ t1    /   
+	//            \  |  / as2             \   a1/    
+	//             \ | /                   \   /     
+	//              sa                       sa   
+	//  -------------------------------------------------------------
+	int as1 = NextEdge[a1];
+	int as2 = NextEdge[a2];
+	int ap1 = PreviousEdge[a1];
+	int ap2 = PreviousEdge[a2];
+	(*t1)(VerticesOfTriangularEdge[a1][1]) = s2 ; // avant sb
+	(*t2)(VerticesOfTriangularEdge[a2][1]) = s1  ; // avant sa
+	// mise a jour des 2 adjacences externes 
+	AdjacentTriangle taas1 = t1->Adj(as1),
+						  taas2 = t2->Adj(as2),
+						  tas1(t1,as1), tas2(t2,as2),
+						  ta1(t1,a1),ta2(t2,a2);
+	// externe haut gauche
+	taas1.SetAdj2(ta2, taas1.GetAllFlag_UnSwap());
+	// externe bas droite
+	taas2.SetAdj2(ta1, taas2.GetAllFlag_UnSwap());
+	// remove the Mark  UnMarkSwap 
+	t1->SetUnMarkUnSwap(ap1);
+	t2->SetUnMarkUnSwap(ap2);
+	// interne 
+	tas1.SetAdj2(tas2);
+
+	t1->det = det1;
+	t2->det = det2;
+
+	t1->SetSingleVertexToTriangleConnectivity();
+	t2->SetSingleVertexToTriangleConnectivity();
+} // end swap 
+/*}}}*/
+	/*FUNCTION SwapForForcingEdge{{{*/
+	int SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,AdjacentTriangle & tt1,Icoor2 & dets1, Icoor2 & detsa,Icoor2 & detsb, int & NbSwap) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/SwapForForcingEdge)*/
+		// l'arete ta coupe l'arete pva pvb
+		// de cas apres le swap sa coupe toujours
+		// on cherche l'arete suivante 
+		// on suppose que detsa >0 et detsb <0
+		// attention la routine echange pva et pvb 
+
+		if(tt1.Locked()) return 0; // frontiere croise 
+
+		AdjacentTriangle tt2 = Adj(tt1);
+		Triangle *t1=tt1,*t2=tt2;// les 2 triangles adjacent
+		short a1=tt1,a2=tt2;// les 2 numero de l arete dans les 2 triangles
+		if ( a1<0 || a1>=3 ){
+			_error_("a1<0 || a1>=3");
+		}
+
+		BamgVertex & sa= (* t1)[VerticesOfTriangularEdge[a1][0]];
+		BamgVertex & s1= (*t1)[OppositeVertex[a1]];
+		BamgVertex & s2= (*t2)[OppositeVertex[a2]];
+
+
+		Icoor2 dets2 = det(*pva,*pvb,s2);
+		Icoor2 det1=t1->det , det2=t2->det ;
+		Icoor2 detT = det1+det2;
+		if ((det1<=0 ) || (det2<=0)){
+			_error_("(det1<=0 ) || (det2<=0)");
+		}
+		if ( (detsa>=0) || (detsb<=0) ){ // [a,b] cut infinite line va,bb
+			_error_("(detsa>=0) || (detsb<=0)");
+		}
+		Icoor2 ndet1 = bamg::det(s1,sa,s2);
+		Icoor2 ndet2 = detT - ndet1;
+
+		int ToSwap =0; //pas de swap
+		if ((ndet1 >0) && (ndet2 >0)) 
+		  { // on peut swaper  
+			if ((dets1 <=0 && dets2 <=0) || (dets2 >=0 && detsb >=0))
+			 ToSwap =1; 
+			else // swap alleatoire 
+			 if (BinaryRand()) 
+			  ToSwap =2; 
+		  }
+		if (ToSwap) NbSwap++,
+		 bamg::swap(t1,a1,t2,a2,&s1,&s2,ndet1,ndet2);
+
+		int ret=1;
+
+		if (dets2 < 0) {// haut
+			dets1 = ToSwap ? dets1 : detsa ;
+			detsa = dets2; 
+			tt1 =  Previous(tt2) ;}
+		else if (dets2 > 0){// bas 
+			dets1 = ToSwap ? dets1 : detsb ;
+			detsb = dets2;
+			//xxxx tt1 = ToSwap ? tt1 : Next(tt2);
+			if(!ToSwap) tt1 =  Next(tt2);
+		}
+		else { // changement de direction 
+			ret = -1;
+			Exchange(pva,pvb);
+			Exchange(detsa,detsb);
+			Exchange(dets1,dets2);
+			Exchange(tt1,tt2);
+			dets1=-dets1;
+			dets2=-dets2;
+			detsa=-detsa;
+			detsb=-detsb;
+
+			if (ToSwap) 
+			 if (dets2 < 0) {// haut
+				 dets1 = (ToSwap ? dets1 : detsa) ;
+				 detsa = dets2; 
+				 tt1 =  Previous(tt2) ;}
+			 else if (dets2 > 0){// bas 
+				 dets1 = (ToSwap ? dets1 : detsb) ;
+				 detsb =  dets2;
+				 if(!ToSwap) tt1 =  Next(tt2);
+			 }
+			 else {// on a fin ???
+				 tt1 = Next(tt2);
+				 ret =0;}
+
+		}
+		return ret;
+	}
+	/*}}}*/
+
+}
Index: /issm/trunk/src/c/classes/bamg/Mesh.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/Mesh.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Mesh.h	(revision 13395)
@@ -0,0 +1,193 @@
+#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 &) ;
+	void  swap(Triangle *t1,short a1,
+				Triangle *t2,short a2,
+				BamgVertex *s1,BamgVertex *s2,Icoor2 det1,Icoor2 det2);
+	int SwapForForcingEdge(BamgVertex   *  & pva ,BamgVertex  * &   pvb ,
+				AdjacentTriangle & tt1,Icoor2 & dets1,
+				Icoor2 & detsa,Icoor2 & detsb, int & nbswap);
+	int ForceEdge(BamgVertex &a, BamgVertex & b,AdjacentTriangle & taret) ;
+	inline AdjacentTriangle Previous(const AdjacentTriangle & ta){
+		return AdjacentTriangle(ta.t,PreviousEdge[ta.a]);
+	}
+	inline AdjacentTriangle Next(const AdjacentTriangle & ta){
+		return AdjacentTriangle(ta.t,NextEdge[ta.a]);
+	}
+	inline  AdjacentTriangle Adj(const AdjacentTriangle & a){
+		return  a.Adj();
+	}
+	inline void Adj(GeomEdge * & on,int &i){
+		int j=i;i=on->AdjVertexIndex[i];on=on->Adj[j];
+	}
+	inline double qualite(const BamgVertex &va,const BamgVertex &vb,const BamgVertex &vc){
+		double ret; 
+		I2 ia=va,ib=vb,ic=vc;
+		I2 ab=ib-ia,bc=ic-ib,ac=ic-ia;
+		Icoor2 deta=Det(ab,ac);
+		if (deta <=0) ret = -1;
+		else {
+			double a = sqrt((double) (ac,ac)),
+					 b = sqrt((double) (bc,bc)),
+					 c = sqrt((double) (ab,ab)),
+					 p = a+b+c;
+			double h= Max(Max(a,b),c),ro=deta/p;
+			ret = ro/h;
+		}
+		return ret;
+	}
+
+}
+#endif
Index: /issm/trunk/src/c/classes/bamg/Metric.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/Metric.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Metric.cpp	(revision 13395)
@@ -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){
+			_error_("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){
+			_error_("r>1 || r<0");
+		}
+		return r ;
+	}
+	/*}}}*/
+
+}
Index: /issm/trunk/src/c/classes/bamg/Metric.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/Metric.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Metric.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/R2.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/R2.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/R2.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/SetOfE4.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/SetOfE4.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/SetOfE4.cpp	(revision 13395)
@@ -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 ) {
+			_error_("SetOfEdges4::add overflow: NbOfEdges=" << NbOfEdges << " > nbax=" << nbax);
+		}
+
+		//update chain
+		Edges[NbOfEdges].i=ii;
+		Edges[NbOfEdges].j=jj;
+		Edges[NbOfEdges].next= head[h];
+		head[h] = NbOfEdges;
+		return NbOfEdges ++;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::find {{{*/
+	long SetOfEdges4::find(long ii,long jj) { 
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, SetOfEdges4.cpp/find)*/
+
+		/*Intermediary*/
+		int n;
+
+		//check that head is not empty
+		_assert_(head);
+
+		//get n from h (usually h=ii)
+		n=head[Abs(ii)%nx];
+
+		//go through the existing edges that holds h (=ii) and return position in Edge
+		while (n >= 0){
+
+			//if the edge ii jj is already in Edges, return n
+			if (ii == Edges[n].i && jj == Edges[n].j) return n;
+
+			//else go to next edge that holds ii
+			else n = Edges[n].next;
+		}
+
+		//if we reach this point, the edge does not exist return -1
+		return -1;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::i{{{*/
+	long SetOfEdges4::i(long k){
+		return Edges[k].i;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::j{{{*/
+	long SetOfEdges4::j(long k){
+		return Edges[k].j;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::nb{{{*/
+	long SetOfEdges4::nb(){
+		return NbOfEdges;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::newarete{{{*/
+	long SetOfEdges4::newarete(long k){
+		return NbOfEdges == k+1;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::SortAndAdd{{{*/
+	long SetOfEdges4::SortAndAdd (long ii,long jj) {
+		return ii <=jj ? add (ii,jj)  : add (jj,ii) ;
+	}
+	/*}}}*/
+	/*FUNCTION  SetOfEdges4::SortAndFind{{{*/
+	long SetOfEdges4::SortAndFind (long ii,long jj) {
+		return ii <=jj ? find (ii,jj)  : find (jj,ii) ;
+	}
+	/*}}}*/
+}
Index: /issm/trunk/src/c/classes/bamg/SetOfE4.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/SetOfE4.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/SetOfE4.h	(revision 13395)
@@ -0,0 +1,42 @@
+#ifndef _SetOfEdge4_h
+#define _SetOfEdge4_h
+
+namespace bamg {
+
+	class SetOfEdges4;
+
+	class IntEdge{
+		friend class SetOfEdges4;
+		public:
+		long i,j;
+		long next; 
+	};
+
+	class SetOfEdges4 {
+
+		private:
+			long nx,nbax,NbOfEdges;
+			long* head; 
+			IntEdge* Edges;
+
+		public:
+
+			// Constructors
+			SetOfEdges4(long ,long);// nb Edges mx , nb de sommet 
+			~SetOfEdges4() {delete [] head; delete [] Edges;}
+
+			//operators
+			IntEdge & operator[](long k){return  Edges[k];}
+
+			//Methods
+			long add (long ii,long jj);
+			long SortAndAdd (long ii,long jj);
+			long nb();
+			long find (long ii,long jj);
+			long SortAndFind (long ii,long jj);
+			long i(long k);
+			long j(long k);
+			long newarete(long k);
+	};
+}
+#endif 
Index: /issm/trunk/src/c/classes/bamg/SubDomain.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/SubDomain.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/SubDomain.cpp	(revision 13395)
@@ -0,0 +1,28 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "SubDomain.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+
+	/*Methods*/
+	/*FUNCTION SubDomain::Set {{{*/
+	void SubDomain::Set(const Mesh & Th ,long i,Mesh & ThNew){
+		*this = Th.subdomains[i];
+		if ( head-Th.triangles<0 || head-Th.triangles>=Th.nbt){
+			_error_("head-Th.triangles<0 || head-Th.triangles>=Th.nbt");
+		}
+		head = ThNew.triangles + Th.GetId(head) ; 
+		if (edge-Th.edges<0 || edge-Th.edges>=Th.nbe);{
+			_error_("edge-Th.edges<0 || edge-Th.edges>=Th.nbe");
+		}
+		edge = ThNew.edges+ Th.GetId(edge);
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/classes/bamg/SubDomain.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/SubDomain.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/SubDomain.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/Triangle.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/Triangle.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Triangle.cpp	(revision 13395)
@@ -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){
+			_error_("i<0 || j<0 || k<0");
+		}
+		if (i>=nbv || j>=nbv || k>=nbv){
+			_error_("i>=nbv || j>=nbv || k>=nbv");
+		}
+		vertices[0]=v+i;
+		vertices[1]=v+j;
+		vertices[2]=v+k;
+		adj[0]=adj[1]=adj[2]=0;
+		AdjEdgeIndex[0]=AdjEdgeIndex[1]=AdjEdgeIndex[2]=0;
+		det=0;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2) {{{*/
+	Triangle::Triangle(BamgVertex *v0,BamgVertex *v1,BamgVertex *v2){
+		vertices[0]=v0;
+		vertices[1]=v1;
+		vertices[2]=v2;
+		adj[0]=adj[1]=adj[2]=0;
+		AdjEdgeIndex[0]=AdjEdgeIndex[1]=AdjEdgeIndex[2]=0;
+		if (v0) det=0;
+		else {
+			det=-1;
+			link=NULL;};  
+	}
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION Triangle::Adj{{{*/
+	AdjacentTriangle Triangle::Adj(int i)  const {
+		return AdjacentTriangle(adj[i],AdjEdgeIndex[i]&3);
+	};/*}}}*/
+	/*FUNCTION Triangle::Anisotropy{{{*/
+	double Triangle::Anisotropy() const{
+
+		double lmin,lmax;
+
+		/*Get three vertices A,B and C*/
+		R2 A=*this->vertices[0];
+		R2 B=*this->vertices[1];
+		R2 C=*this->vertices[2];
+
+		/*Compute edges*/
+		R2 e1=B-A;
+		R2 e2=C-A;
+		R2 e3=B-C;
+
+		/*Compute edge length*/
+		double l1=Norme2(e1);
+		double l2=Norme2(e2);
+		double l3=Norme2(e3);
+
+		lmin=l1;
+		lmin=min(lmin,l2);
+		lmin=min(lmin,l3);
+		lmax=l1;
+		lmax=max(lmax,l2);
+		lmax=max(lmax,l3);
+
+		return lmax/lmin;
+	};/*}}}*/
+	/*FUNCTION Triangle::Length{{{*/
+	double Triangle::Length() const{
+
+		double l;
+
+		/*Get three vertices A,B and C*/
+		R2 A=*this->vertices[0];
+		R2 B=*this->vertices[1];
+		R2 C=*this->vertices[2];
+
+		/*Compute edges*/
+		R2 e1=B-A;
+		R2 e2=C-A;
+		R2 e3=B-C;
+
+		/*Compute edge length*/
+		l=Norme2(e1);
+		l=max(l,Norme2(e2));
+		l=max(l,Norme2(e3));
+
+		return l;
+	};/*}}}*/
+	/*FUNCTION Triangle::Echo {{{*/
+	void Triangle::Echo(void){
+
+		int i;
+
+		_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){
+				_error_("too many iteration in Triangle::FindBoundaryEdge (k>=2000)");
+			}
+		} while (this!= t);
+		//not found, return empty triangle
+		return AdjacentTriangle(NULL,0);
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::GetAllflag{{{*/
+	int    Triangle::GetAllflag(int a){
+		return AdjEdgeIndex[a] & 1020;
+	}/*}}}*/
+	/*FUNCTION Triangle::Hidden{{{*/
+	int    Triangle::Hidden(int a)const {
+		return AdjEdgeIndex[a]&16;
+	} /*}}}*/
+	/*FUNCTION Triangle::Locked{{{*/
+	int    Triangle::Locked(int a)const {
+		return AdjEdgeIndex[a]&4;
+	} /*}}}*/
+	/*FUNCTION Triangle::NuEdgeTriangleAdj{{{*/
+	short  Triangle::NuEdgeTriangleAdj(int i) const {
+		/*Number of the  adjacent edge in adj tria (make sure it is between 0 and 2*/
+		return AdjEdgeIndex[i&3]&3;
+	}/*}}}*/
+	/*FUNCTION Triangle::Optim{{{*/
+	long  Triangle::Optim(short i,int koption) {
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Optim)*/
+
+		// turn around (positive direction)
+		Triangle *t=this;
+		long NbSwap =0;
+		int  k = 0;
+		int  j = OppositeEdge[i];
+		int  jp= PreviousEdge[j];
+
+		// initialize tp, jp the previous triangle & edge
+		Triangle *tp=adj[jp];
+		jp = AdjEdgeIndex[jp]&3;
+		do {
+			while (t->swap(j,koption)){
+				if (k>=20000) _error_("k>=20000");
+				NbSwap++;
+				k++;
+				t=  tp->adj[jp];      // set unchange t qnd j for previous triangles
+				j=  NextEdge[tp->AdjEdgeIndex[jp]&3];
+			}
+			// end on this  Triangle 
+			tp = t;
+			jp = NextEdge[j];
+
+			t=  tp->adj[jp];      // set unchange t qnd j for previous triangles
+			j=  NextEdge[tp->AdjEdgeIndex[jp]&3];
+
+		} while( t != this);
+		return NbSwap;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::Quadrangle {{{*/
+	Triangle* Triangle::Quadrangle(BamgVertex * & v0,BamgVertex * & v1,BamgVertex * & v2,BamgVertex * & v3) const{
+		// return the other triangle of the quad if a quad or 0 if not a quat
+		Triangle * t =0;
+		if (link) {
+			int a=-1;
+			if (AdjEdgeIndex[0] & 16 ) a=0;
+			if (AdjEdgeIndex[1] & 16 ) a=1;
+			if (AdjEdgeIndex[2] & 16 ) a=2;
+			if (a>=0) {
+				t = adj[a];
+				//  if (t-this<0) return 0;
+				v2 = vertices[VerticesOfTriangularEdge[a][0]];
+				v0 = vertices[VerticesOfTriangularEdge[a][1]];
+				v1 = vertices[OppositeEdge[a]];
+				v3 = t->vertices[OppositeEdge[AdjEdgeIndex[a]&3]];
+			}
+		}
+		return t;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::QualityQuad {{{*/
+	double   Triangle::QualityQuad(int a,int option) const{
+		double q;
+		if (!link || AdjEdgeIndex[a] &4)
+		 q=  -1;
+		else {
+			Triangle * t = adj[a];
+			if (t-this<0) q=  -1;// because we do 2 times 
+			else if (!t->link ) q=  -1;
+			else if (AdjEdgeIndex[0] & 16 || AdjEdgeIndex[1] & 16  || AdjEdgeIndex[2] & 16 || t->AdjEdgeIndex[0] & 16 || t->AdjEdgeIndex[1] & 16 || t->AdjEdgeIndex[2] & 16 )
+			 q= -1;
+			else if(option){ 
+				const BamgVertex & v2 = *vertices[VerticesOfTriangularEdge[a][0]];
+				const BamgVertex & v0 = *vertices[VerticesOfTriangularEdge[a][1]];
+				const BamgVertex & v1 = *vertices[OppositeEdge[a]];
+				const BamgVertex & v3 = * t->vertices[OppositeEdge[AdjEdgeIndex[a]&3]];
+				q =  QuadQuality(v0,v1,v2,v3); // do the float part
+			}
+			else q= 1;
+		}
+		return  q;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::Renumbering(Triangle *tb,Triangle *te, long *renu){{{*/
+	void  Triangle::Renumbering(Triangle *tb,Triangle *te, long *renu){
+
+		if (link  >=tb && link  <te) link  = tb + renu[link -tb];
+		if (adj[0] >=tb && adj[0] <te) adj[0] = tb + renu[adj[0]-tb];
+		if (adj[1] >=tb && adj[1] <te) adj[1] = tb + renu[adj[1]-tb];
+		if (adj[2] >=tb && adj[2] <te) adj[2] = tb + renu[adj[2]-tb];    
+	}/*}}}*/
+	/*FUNCTION Triangle::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){{{*/
+	void Triangle::Renumbering(BamgVertex *vb,BamgVertex *ve, long *renu){
+		if (vertices[0] >=vb && vertices[0] <ve) vertices[0] = vb + renu[vertices[0]-vb];
+		if (vertices[1] >=vb && vertices[1] <ve) vertices[1] = vb + renu[vertices[1]-vb];
+		if (vertices[2] >=vb && vertices[2] <ve) vertices[2] = vb + renu[vertices[2]-vb];    
+	}/*}}}*/
+	/*FUNCTION Triangle::Set {{{*/
+	void Triangle::Set(const Triangle & rec,const Mesh & Th ,Mesh & ThNew){ 
+		*this = rec;
+		if ( vertices[0] ) vertices[0] = ThNew.vertices +  Th.GetId(vertices[0]);
+		if ( vertices[1] ) vertices[1] = ThNew.vertices +  Th.GetId(vertices[1]);
+		if ( vertices[2] ) vertices[2] = ThNew.vertices +  Th.GetId(vertices[2]);
+		if(adj[0]) adj[0] =  ThNew.triangles + Th.GetId(adj[0]);
+		if(adj[1]) adj[1] =  ThNew.triangles + Th.GetId(adj[1]);
+		if(adj[2]) adj[2] =  ThNew.triangles + Th.GetId(adj[2]);
+		if (link  >= Th.triangles && link  < Th.triangles + Th.nbt)
+		 link = ThNew.triangles + Th.GetId(link);
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::SetAdjAdj{{{*/
+	void Triangle::SetAdjAdj(short a){
+		// Copy all the mark 
+		a &= 3;
+		register Triangle *tt=adj[a];
+		AdjEdgeIndex [a] &= 55; // remove MarkUnSwap
+		register short aatt = AdjEdgeIndex[a] & 3;
+		if(tt){ 
+			tt->adj[aatt]=this;
+			tt->AdjEdgeIndex[aatt]=a + (AdjEdgeIndex[a] & 60 ) ;
+		}
+	}/*}}}*/
+	/*FUNCTION Triangle::SetAdj2{{{*/
+	void Triangle::SetAdj2(short a,Triangle *t,short aat){
+		/*For current triangle:
+		 * - a is the index of the edge were the adjency is set (in [0 2])
+		 * - t is the adjacent triangle
+		 * - aat is the index of the same edge in the adjacent triangle*/
+		adj[a]=t;
+		AdjEdgeIndex[a]=aat;
+		if(t){ //if t!=NULL add adjacent triangle to t (this)
+			t->adj[aat]=this;
+			t->AdjEdgeIndex[aat]=a;
+		}
+	}/*}}}*/
+	/*FUNCTION Triangle::SetAllFlag{{{*/
+	void   Triangle::SetAllFlag(int a,int f){
+		AdjEdgeIndex[a] = (AdjEdgeIndex[a] &3) + (1020 & f);
+	}/*}}}*/
+	/*FUNCTION Triangle::SetDet{{{*/
+	void Triangle::SetDet() {
+		if(vertices[0] && vertices[1] && vertices[2])    det = bamg::det(*vertices[0],*vertices[1],*vertices[2]);
+		else det = -1; 
+	}/*}}}*/
+	/*FUNCTION Triangle::SetHidden{{{*/
+	void Triangle::SetHidden(int a){
+		//Get Adjacent Triangle number a
+		register Triangle* t = adj[a];
+		//if it exist
+		//C|=D -> C=(C|D) bitwise inclusive OR
+		if(t) t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=16;
+		AdjEdgeIndex[a] |= 16;
+	}/*}}}*/
+	/*FUNCTION Triangle::SetLocked{{{*/
+	void Triangle::SetLocked(int a){
+		//mark the edge as on Boundary
+		register Triangle * t = adj[a];
+		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=4;
+		AdjEdgeIndex[a] |= 4;
+	}/*}}}*/
+	/*FUNCTION Triangle::SetMarkUnSwap{{{*/
+	void Triangle::SetMarkUnSwap(int a){
+		register Triangle * t = adj[a];
+		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] |=8;
+		AdjEdgeIndex[a] |=8 ;
+	}/*}}}*/
+	/*FUNCTION Triangle::SetSingleVertexToTriangleConnectivity{{{*/
+	void Triangle::SetSingleVertexToTriangleConnectivity() { 
+		if (vertices[0]) (vertices[0]->t=this,vertices[0]->IndexInTriangle=0);
+		if (vertices[1]) (vertices[1]->t=this,vertices[1]->IndexInTriangle=1);
+		if (vertices[2]) (vertices[2]->t=this,vertices[2]->IndexInTriangle=2);
+	}/*}}}*/
+	/*FUNCTION Triangle::SetUnMarkUnSwap{{{*/
+	void Triangle::SetUnMarkUnSwap(int a){ 
+		register Triangle * t = adj[a];
+		t->AdjEdgeIndex[AdjEdgeIndex[a] & 3] &=55; // 23 + 32 
+		AdjEdgeIndex[a] &=55 ;
+	}/*}}}*/
+	/*FUNCTION Triangle::swap{{{*/
+	int Triangle::swap(short a,int koption){
+		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/swap)*/
+
+		if(a/4 !=0) return 0;// arete lock or MarkUnSwap
+
+		register Triangle *t1=this,*t2=adj[a];// les 2 triangles adjacent
+		register short a1=a,a2=AdjEdgeIndex[a];// les 2 numero de l arete dans les 2 triangles
+		if(a2/4 !=0) return 0; // arete lock or MarkUnSwap
+
+		register BamgVertex  *sa=t1->vertices[VerticesOfTriangularEdge[a1][0]];
+		register BamgVertex  *sb=t1->vertices[VerticesOfTriangularEdge[a1][1]];
+		register BamgVertex  *s1=t1->vertices[OppositeVertex[a1]];
+		register BamgVertex  *s2=t2->vertices[OppositeVertex[a2]];
+
+		Icoor2 det1=t1->det , det2=t2->det ;
+		Icoor2 detT = det1+det2;
+		Icoor2 detA = Abs(det1) + Abs(det2);
+		Icoor2 detMin = Min(det1,det2);
+
+		int OnSwap = 0;       
+		// si 2 triangle infini (bord) => detT = -2;
+		if (sa == 0) {// les deux triangles sont frontieres
+			det2=bamg::det(s2->i,sb->i,s1->i);
+			OnSwap = det2 >0;}
+		else if (sb == 0) { // les deux triangles sont frontieres
+			det1=bamg::det(s1->i,sa->i,s2->i);
+			OnSwap = det1 >0;}
+		else if(( s1 != 0) && (s2 != 0) ) {
+			det1 = bamg::det(s1->i,sa->i,s2->i);
+			det2 = detT - det1;
+			OnSwap = (Abs(det1) + Abs(det2)) < detA;
+
+			Icoor2 detMinNew=Min(det1,det2);
+			//     if (detMin<0 && (Abs(det1) + Abs(det2) == detA)) OnSwap=BinaryRand();// just for test   
+			if (! OnSwap &&(detMinNew>0)) {
+				OnSwap = detMin ==0;
+				if (! OnSwap) {
+					int  kopt = koption;
+					while (1)
+					 if(kopt) {
+						 // critere de Delaunay pure isotrope
+						 register Icoor2 xb1 = sb->i.x - s1->i.x,
+									 x21 = s2->i.x - s1->i.x,
+									 yb1 = sb->i.y - s1->i.y,
+									 y21 = s2->i.y - s1->i.y,
+									 xba = sb->i.x - sa->i.x, 
+									 x2a = s2->i.x - sa->i.x,
+									 yba = sb->i.y - sa->i.y,
+									 y2a = s2->i.y - sa->i.y;
+						 register double
+							cosb12 =  double(xb1*x21 + yb1*y21),
+									 cosba2 =  double(xba*x2a + yba*y2a) ,
+									 sinb12 = double(det2),
+									 sinba2 = double(t2->det);
+
+
+						 // angle b12 > angle ba2 => cotg(angle b12) < cotg(angle ba2)
+						 OnSwap =  ((double) cosb12 * (double)  sinba2) <  ((double) cosba2 * (double) sinb12);
+						 break;
+					 }
+					 else {	
+						 // critere de Delaunay anisotrope 
+						 double som;
+						 I2 AB=(I2) *sb - (I2) *sa;
+						 I2 MAB2=((I2) *sb + (I2) *sa);
+						 R2 MAB(MAB2.x*0.5,MAB2.y*0.5);
+						 I2 A1=(I2) *s1 - (I2) *sa;
+						 I2 D = (I2) * s1 - (I2) * sb ;
+						 R2 S2(s2->i.x,s2->i.y);
+						 R2 S1(s1->i.x,s1->i.y);
+							{
+							 Metric M=s1->m;
+							 R2 ABo = M.Orthogonal(AB);
+							 R2 A1o = M.Orthogonal(A1);
+							 // (A+B)+ x ABo = (S1+B)/2+ y A1 
+							 // ABo x - A1o y =  (S1+B)/2-(A+B)/2 = (S1-B)/2 = D/2
+							 double dd = Abs(ABo.x*A1o.y)+Abs(ABo.y*A1o.x);
+							 double d = (ABo.x*A1o.y - ABo.y*A1o.x)*2; // because D/2
+							 if (Abs(d) > dd*1.e-3) {
+								 R2 C(MAB+ABo*((D.x*A1o.y - D.y*A1o.x)/d));
+								 som  = M(C - S2)/M(C - S1);
+							 } else 
+								{kopt=1;continue;}
+
+							}
+							{
+							 Metric M=s2->m;
+							 R2 ABo = M.Orthogonal(AB);
+							 R2 A1o = M.Orthogonal(A1);
+							 // (A+B)+ x ABo = (S1+B)/2+ y A1 
+							 // ABo x - A1o y =  (S1+B)/2-(A+B)/2 = (S1-B)/2 = D/2 
+							 double dd = Abs(ABo.x*A1o.y)+Abs(ABo.y*A1o.x);
+							 double d = (ABo.x*A1o.y - ABo.y*A1o.x)*2; // because D/2
+							 if(Abs(d) > dd*1.e-3) {
+								 R2 C(MAB+ABo*((D.x*A1o.y - D.y*A1o.x)/d));
+								 som  += M(C - S2)/M(C -  S1);
+							 } else 
+								{kopt=1;continue;}
+							}
+						 OnSwap = som < 2;
+						 break;
+					 }
+
+				} // OnSwap 
+			} // (! OnSwap &&(det1 > 0) && (det2 > 0) )
+		}
+		if( OnSwap ) 
+		 bamg::swap(t1,a1,t2,a2,s1,s2,det1,det2);
+		else {
+			t1->SetMarkUnSwap(a1);     
+		}
+		return OnSwap;
+	}
+	/*}}}*/
+	/*FUNCTION Triangle::TriangleAdj{{{*/
+	Triangle* Triangle::TriangleAdj(int i) const {
+		return adj[i&3];
+	}/*}}}*/
+
+}
Index: /issm/trunk/src/c/classes/bamg/Triangle.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/Triangle.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/Triangle.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/VertexOnEdge.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/VertexOnEdge.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/VertexOnEdge.cpp	(revision 13395)
@@ -0,0 +1,25 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "VertexOnEdge.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Methods*/
+	/*FUNCTION VertexOnEdge::Set {{{*/
+	void VertexOnEdge::Set(const Mesh & Th ,long i,Mesh & ThNew){
+		*this = Th.VertexOnBThEdge[i];  
+		v = ThNew.vertices + Th.GetId(v);
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnEdge::SetOnBTh{{{*/
+	void VertexOnEdge::SetOnBTh(){
+		v->BackgroundEdgeHook=this;
+		v->IndexInTriangle=IsVertexOnEdge;  
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/classes/bamg/VertexOnEdge.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/VertexOnEdge.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/VertexOnEdge.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/VertexOnGeom.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/VertexOnGeom.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/VertexOnGeom.cpp	(revision 13395)
@@ -0,0 +1,70 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "VertexOnGeom.h"
+#include "Mesh.h"
+#include "Geometry.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION VertexOnGeom::VertexOnGeom(){{{*/
+	VertexOnGeom::VertexOnGeom(){
+		meshvertex=NULL;
+		curvilincoord=0;
+		gv=0;
+	} 
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomVertex &g){{{*/
+	VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomVertex &g){
+		meshvertex=&m;
+		curvilincoord=-1;
+		gv=&g;
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomEdge &g,double s){{{*/
+	VertexOnGeom::VertexOnGeom(BamgVertex & m,GeomEdge &g,double s){
+		meshvertex=&m;
+		curvilincoord=s;
+		ge=&g;
+	}
+	/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION VertexOnGeom::Set {{{*/
+	void VertexOnGeom::Set(const VertexOnGeom & rec,const Mesh & Th ,Mesh & ThNew){
+		*this = rec;  
+		meshvertex = ThNew.vertices + Th.GetId(meshvertex);
+		if (gv)
+		 if (curvilincoord < 0 )
+		  gv = ThNew.Gh.vertices + Th.Gh.GetId(gv);
+		 else
+		  ge = ThNew.Gh.edges + Th.Gh.GetId(ge);
+
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::OnGeomVertex{{{*/
+	int VertexOnGeom::OnGeomVertex()const{
+		return this? curvilincoord <0 :0;
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::OnGeomEdge{{{*/
+	int VertexOnGeom::OnGeomEdge() const{
+		return this? curvilincoord >=0 :0;
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::IsRequiredVertex{{{*/
+	int VertexOnGeom::IsRequiredVertex() {
+		return this? ((curvilincoord<0 ? (gv?gv->Required():0):0 )) : 0;
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnGeom::SetOn{{{*/
+	void VertexOnGeom::SetOn(){
+		meshvertex->GeomEdgeHook=this;
+		meshvertex->IndexInTriangle=IsVertexOnGeom;
+	}
+	/*}}}*/
+
+} 
Index: /issm/trunk/src/c/classes/bamg/VertexOnGeom.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/VertexOnGeom.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/VertexOnGeom.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/VertexOnVertex.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/VertexOnVertex.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/VertexOnVertex.cpp	(revision 13395)
@@ -0,0 +1,34 @@
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <ctime>
+
+#include "VertexOnVertex.h"
+#include "Mesh.h"
+
+namespace bamg {
+
+	/*Constructors/Destructors*/
+	/*FUNCTION VertexOnVertex::VertexOnVertex(){{{*/
+	VertexOnVertex::VertexOnVertex() {
+		v=NULL;
+		bv=NULL;
+	};/*}}}*/
+	/*FUNCTION VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw){{{*/
+	VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw) :v(w),bv(bw){
+	
+	}/*}}}*/
+
+	/*Methods*/
+	/*FUNCTION VertexOnVertex::Set{{{*/
+	void VertexOnVertex::Set(const Mesh &Th ,long i,Mesh &ThNew) { 
+		*this = Th.VertexOnBThVertex[i];  
+		v     = ThNew.vertices + Th.GetId(v);
+	}
+	/*}}}*/
+	/*FUNCTION VertexOnVertex::SetOnBTh{{{*/
+	void VertexOnVertex::SetOnBTh(){
+		v->BackgroundVertexHook=bv;v->IndexInTriangle=IsVertexOnVertex;
+	}/*}}}*/
+
+} 
Index: /issm/trunk/src/c/classes/bamg/VertexOnVertex.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/VertexOnVertex.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/VertexOnVertex.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/bamgobjects.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/bamgobjects.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/bamgobjects.h	(revision 13395)
@@ -0,0 +1,34 @@
+/* \file bamgobjects.h
+ * \brief: prototype header for all bamg related objects.
+ */
+
+#ifndef BAMG_OBJECTS_H_
+#define BAMG_OBJECTS_H_
+
+/*Bamg: */
+#include "./BamgOpts.h"
+#include "./BamgGeom.h"
+#include "./BamgMesh.h"
+#include "./Metric.h"
+#include "./DoubleAndInt.h"
+#include "./Direction.h"
+#include "./BamgVertex.h"
+#include "./AdjacentTriangle.h"
+#include "./Edge.h"
+#include "./GeomVertex.h"
+#include "./GeomEdge.h"
+#include "./Curve.h"
+#include "./Triangle.h"
+#include "./ListofIntersectionTriangles.h"
+#include "./GeomSubDomain.h"
+#include "./SubDomain.h"
+#include "./VertexOnGeom.h"
+#include "./VertexOnVertex.h"
+#include "./VertexOnEdge.h"
+#include "./CrackedEdge.h"
+#include "./Mesh.h"
+#include "./Geometry.h"
+#include "./BamgQuadtree.h"
+#include "./SetOfE4.h"
+
+#endif
Index: /issm/trunk/src/c/classes/bamg/include.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/include.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/include.h	(revision 13395)
@@ -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/trunk/src/c/classes/bamg/macros.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/macros.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/macros.h	(revision 13395)
@@ -0,0 +1,24 @@
+#ifndef _BAMGMACROS_H
+#define _BAMGMACROS_H
+
+#include "./typedefs.h"
+
+namespace bamg {
+
+	const double Pi =3.141592653589793238462643383279502884197169399375105820974944592308;
+	const float  fPi=3.141592653589793238462643383279502884197169399375105820974944592308;
+	const  int   IsVertexOnGeom = 8;
+	const  int   IsVertexOnVertex = 16;
+	const  int   IsVertexOnEdge = 32;
+	static const short VerticesOfTriangularEdge[3][2] = {{1,2},{2,0},{0,1}};
+	static const short EdgesVertexTriangle[3][2] = {{1,2},{2,0},{0,1}};
+	static const short OppositeVertex[3] = {0,1,2};
+	static const short OppositeEdge[3] =  {0,1,2};
+	static const short NextEdge[3] = {1,2,0};
+	static const short PreviousEdge[3] = {2,0,1};
+	static const short NextVertex[3] = {1,2,0};
+	static const short PreviousVertex[3] = {2,0,1};
+	const  Icoor1 MaxICoor   = 1073741823; // 2^30-1 =111...111 (29 times one)
+}
+
+#endif
Index: /issm/trunk/src/c/classes/bamg/typedefs.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/typedefs.h	(revision 13395)
+++ /issm/trunk/src/c/classes/bamg/typedefs.h	(revision 13395)
@@ -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/trunk/src/c/classes/classes.h
===================================================================
--- /issm/trunk/src/c/classes/classes.h	(revision 13395)
+++ /issm/trunk/src/c/classes/classes.h	(revision 13395)
@@ -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/trunk/src/c/classes/dakota/DakotaPlugin.cpp
===================================================================
--- /issm/trunk/src/c/classes/dakota/DakotaPlugin.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/dakota/DakotaPlugin.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/dakota/DakotaPlugin.h
===================================================================
--- /issm/trunk/src/c/classes/dakota/DakotaPlugin.h	(revision 13395)
+++ /issm/trunk/src/c/classes/dakota/DakotaPlugin.h	(revision 13395)
@@ -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/trunk/src/c/classes/gauss/GaussPenta.cpp
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 13395)
@@ -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{
+		_error_("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{
+		_error_("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{
+		_error_("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:
+			_error_("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{
+		_error_("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/trunk/src/c/classes/gauss/GaussPenta.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussPenta.h	(revision 13395)
+++ /issm/trunk/src/c/classes/gauss/GaussPenta.h	(revision 13395)
@@ -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/trunk/src/c/classes/gauss/GaussTria.cpp
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussTria.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/gauss/GaussTria.cpp	(revision 13395)
@@ -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
+	 _error_("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
+	 _error_("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(IssmDouble x,IssmDouble y,IssmDouble* xyz_list){
+
+	/*Intermediaries*/
+	IssmDouble    area = 0;
+	IssmDouble    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:
+			_error_("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/trunk/src/c/classes/gauss/GaussTria.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussTria.h	(revision 13395)
+++ /issm/trunk/src/c/classes/gauss/GaussTria.h	(revision 13395)
@@ -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;
+		IssmDouble coord1;
+		IssmDouble coord2;
+		IssmDouble 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(IssmDouble x1,IssmDouble y1,IssmDouble* xyz_list);
+		void GaussPoint(int ig);
+		void GaussVertex(int iv);
+		void GaussCenter(void);
+		void GaussEdgeCenter(int index1,int index2);
+};
+#endif  /* _GAUSSTRIA_H_ */
Index: /issm/trunk/src/c/classes/gauss/gaussobjects.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/gaussobjects.h	(revision 13395)
+++ /issm/trunk/src/c/classes/gauss/gaussobjects.h	(revision 13395)
@@ -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/trunk/src/c/classes/kriging/ExponentialVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 13395)
@@ -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) _error_("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/trunk/src/c/classes/kriging/ExponentialVariogram.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/ExponentialVariogram.h	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/ExponentialVariogram.h	(revision 13395)
@@ -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(){_error_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");}; 
+		int   MyRank(){_error_("Not implemented yet");};
+		int   ObjectEnum(){_error_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
+
+		/*Variogram functions*/
+		double SemiVariogram(double deltax,double deltay);
+		double Covariance(double deltax,double deltay);
+};
+#endif  /* _EXPONENTIALVARIOGRAM_H */
Index: /issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp	(revision 13395)
@@ -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) _error_("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/trunk/src/c/classes/kriging/GaussianVariogram.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/GaussianVariogram.h	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/GaussianVariogram.h	(revision 13395)
@@ -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(){_error_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");}; 
+		int   MyRank(){_error_("Not implemented yet");};
+		int   ObjectEnum(){_error_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
+
+		/*Variogram functions*/
+		double SemiVariogram(double deltax,double deltay);
+		double Covariance(double deltax,double deltay);
+};
+#endif  /* _GAUSSIANVARIOGRAM_H */
Index: /issm/trunk/src/c/classes/kriging/Observation.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observation.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/Observation.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/kriging/Observation.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observation.h	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/Observation.h	(revision 13395)
@@ -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()  {_error_("Not implemented yet"); };
+		int     Id()        {_error_("Not implemented yet"); };
+		int     MyRank()    {_error_("Not implemented yet"); };
+		int     ObjectEnum(){_error_("Not implemented yet"); };
+		Object *copy()      {_error_("Not implemented yet"); };
+
+		/*Management*/
+		void WriteXYObs(double* px,double* py,double* pobs);
+};
+#endif  /* _OBSERVATION_*/
Index: /issm/trunk/src/c/classes/kriging/PowerVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/PowerVariogram.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/PowerVariogram.cpp	(revision 13395)
@@ -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) _error_("power must be betwwen 0 and 2 (0 < power < 2)");
+	if(slope<=0) _error_("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/trunk/src/c/classes/kriging/PowerVariogram.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/PowerVariogram.h	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/PowerVariogram.h	(revision 13395)
@@ -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(){_error_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");}; 
+		int   MyRank(){_error_("Not implemented yet");};
+		int   ObjectEnum(){_error_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
+
+		/*Variogram functions*/
+		double SemiVariogram(double deltax,double deltay);
+		double Covariance(double deltax,double deltay);
+};
+#endif  /* _POWERVARIOGRAM_H */
Index: /issm/trunk/src/c/classes/kriging/Quadtree.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Quadtree.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/Quadtree.cpp	(revision 13395)
@@ -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(){
+	_error_("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{
+		_error_("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:
+			_error_("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:
+			_error_("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/trunk/src/c/classes/kriging/Quadtree.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/Quadtree.h	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/Quadtree.h	(revision 13395)
@@ -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()  {_error_("not implemented yet"); };
+				int     Id()        {_error_("not implemented yet"); };
+				int     MyRank()    {_error_("not implemented yet"); };
+				int     ObjectEnum(){_error_("not implemented yet"); };
+				Object *copy()      {_error_("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/trunk/src/c/classes/kriging/SphericalVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp	(revision 13395)
@@ -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) _error_("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/trunk/src/c/classes/kriging/SphericalVariogram.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/SphericalVariogram.h	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/SphericalVariogram.h	(revision 13395)
@@ -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(){_error_("Not implemented yet");};
+		int   Id(){_error_("Not implemented yet");}; 
+		int   MyRank(){_error_("Not implemented yet");};
+		int   ObjectEnum(){_error_("Not implemented yet");};
+		Object* copy(){_error_("Not implemented yet");};
+
+		/*Variogram functions*/
+		double SemiVariogram(double deltax,double deltay);
+		double Covariance(double deltax,double deltay);
+};
+#endif  /* _SPHERICALVARIOGRAM_H */
Index: /issm/trunk/src/c/classes/kriging/Variogram.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/Variogram.h	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/Variogram.h	(revision 13395)
@@ -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/trunk/src/c/classes/kriging/krigingobjects.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/krigingobjects.h	(revision 13395)
+++ /issm/trunk/src/c/classes/kriging/krigingobjects.h	(revision 13395)
@@ -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/trunk/src/c/classes/matrix/ElementMatrix.cpp
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 13395)
@@ -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) _error_("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){
+		_error_("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) _error_("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<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){{{*/
+void ElementMatrix::AddToGlobal(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* 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{
+		_error_("non dofsymmetrical matrix AddToGlobal routine not support yet!");
+	}
+
+}
+/*}}}*/
+/*FUNCTION ElementMatrix::AddToGlobal(Matrix<IssmDouble>* Jff){{{*/
+void ElementMatrix::AddToGlobal(Matrix<IssmDouble>* 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{
+		_error_("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])) _error_("NaN found in Element Matrix");
+			if (fabs(this->values[i*this->ncols+j])>1.e+50) _error_("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){
+		_error_("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: " << this->nrows);
+	_printLine_("   ncols: " << this->ncols);
+	_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)_error_("need square matrix in input!");
+
+	for(i=0;i<this->nrows;i++){
+		this->values[this->ncols*i+i]=scalar;
+	}
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/matrix/ElementMatrix.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementMatrix.h	(revision 13395)
+++ /issm/trunk/src/c/classes/matrix/ElementMatrix.h	(revision 13395)
@@ -0,0 +1,71 @@
+/*!\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;
+template <class doublematrix> class Matrix;
+class Parameters;
+/*}}}*/
+
+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<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void AddToGlobal(Matrix<IssmDouble>* 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/trunk/src/c/classes/matrix/ElementVector.cpp
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementVector.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/matrix/ElementVector.cpp	(revision 13395)
@@ -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){
+		_error_("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<IssmDouble>* pf){{{*/
+void ElementVector::AddToGlobal(Vector<IssmDouble>* 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<IssmDouble>* pf){{{*/
+void ElementVector::InsertIntoGlobal(Vector<IssmDouble>* 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])) _error_("NaN found in Element Vector");
+		if (fabs( this->values[i])>1.e+50) _error_("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/trunk/src/c/classes/matrix/ElementVector.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementVector.h	(revision 13395)
+++ /issm/trunk/src/c/classes/matrix/ElementVector.h	(revision 13395)
@@ -0,0 +1,53 @@
+/*!\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;
+template <class doubletype> class Vector;
+class Parameters;
+/*}}}*/
+
+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<IssmDouble>* pf);
+		void InsertIntoGlobal(Vector<IssmDouble>* pf);
+		void Echo(void);
+		void CheckConsistency(void);
+		void Init(ElementVector* pe);
+		void SetValue(IssmDouble scalar);
+		/*}}}*/
+};
+#endif //#ifndef _ELEMENT_VECTOR_H_
+
Index: /issm/trunk/src/c/classes/matrix/Matrix.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/Matrix.h	(revision 13395)
+++ /issm/trunk/src/c/classes/matrix/Matrix.h	(revision 13395)
@@ -0,0 +1,345 @@
+/*!\file:  Matrix.h
+ * \brief wrapper to matrix objects. The goal is to control which API (PETSc,Scalpack, Plapack?) 
+ * implements our underlying matrix format.
+ */ 
+
+#ifndef _MATRIX_H_
+#define _MATRIX_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+/*}}}*/
+
+enum matrixtype { PetscMatType, SeqMatType };
+
+template <class doubletype> class Vector;
+
+template <class doubletype> 
+class Matrix{
+
+	public:
+
+		#ifdef _HAVE_PETSC_
+		PetscMat *pmatrix;
+		#endif
+		SeqMat<doubletype>   *smatrix;
+		int       type;
+
+		/*Matrix constructors, destructors*/
+		/*FUNCTION Matrix(){{{*/
+		Matrix(){
+
+			#ifdef _HAVE_PETSC_
+			pmatrix=NULL;
+			#endif
+			smatrix=NULL;
+
+			type=PetscMatType; //default
+			#ifndef _HAVE_PETSC_
+			type=SeqMatType;
+			#endif
+
+		}
+		/*}}}*/
+		/*FUNCTION Matrix(int M,int N,int in_type){{{*/
+		#ifdef _HAVE_PETSC_
+		Matrix(int M,int N,int in_type=PetscMatType){
+		#else
+		Matrix(int M,int N,int in_type=SeqMatType){
+		#endif
+
+			#ifdef _HAVE_PETSC_
+			pmatrix=NULL;
+			#endif
+			smatrix=NULL;
+			type=in_type;
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(M,N);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqMatType){
+				this->smatrix=new SeqMat<doubletype>(M,N);
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION Matrix(int M,int N,IssmDouble sparsity,int in_type){{{*/
+		#ifdef _HAVE_PETSC_
+		Matrix(int M,int N,double sparsity,int in_type=PetscMatType){
+		#else
+		Matrix(int M,int N,double sparsity,int in_type=SeqMatType){
+		#endif
+
+			#ifdef _HAVE_PETSC_
+			pmatrix=NULL;
+			#endif
+
+			smatrix=NULL;
+			type=in_type;
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(M,N,sparsity);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqMatType){
+				this->smatrix=new SeqMat<doubletype>(M,N,sparsity);
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+		}
+		/*}}}*/
+		/*FUNCTION Matrix(IssmDouble* serial_mat, int M,int N,IssmDouble sparsity,int in_type){{{*/
+		#ifdef _HAVE_PETSC_
+		Matrix(IssmPDouble* serial_mat,int M,int N,IssmPDouble sparsity,int in_type=PetscMatType){
+		#else
+		Matrix(IssmPDouble* serial_mat,int M,int N,IssmPDouble sparsity,int in_type=SeqMatType){
+		#endif
+
+			#ifdef _HAVE_PETSC_
+			pmatrix=NULL;
+			#endif
+			smatrix=NULL;
+			type=in_type;
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(serial_mat,M,N,sparsity);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqMatType){
+				this->smatrix=new SeqMat<doubletype>(serial_mat,M,N,sparsity);
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION Matrix(int M,int N,int connectivity,int numberofdofspernode,int in_type){{{*/
+		#ifdef _HAVE_PETSC_
+		Matrix(int M,int N,int connectivity,int numberofdofspernode,int in_type=PetscMatType){
+		#else
+		Matrix(int M,int N,int connectivity,int numberofdofspernode,int in_type=SeqMatType){
+		#endif
+
+			#ifdef _HAVE_PETSC_
+			pmatrix=NULL;
+			#endif
+			smatrix=NULL;
+			type=in_type;
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(M,N,connectivity,numberofdofspernode);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqMatType){
+				this->smatrix=new SeqMat<doubletype>(M,N,connectivity,numberofdofspernode);
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION ~Matrix(){{{*/
+		~Matrix(){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				delete this->pmatrix;
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqMatType){
+				delete this->smatrix;
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+
+		/*Matrix specific routines:*/
+		/*FUNCTION Echo{{{*/
+		void Echo(void){
+			_assert_(this);
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->Echo();
+				#endif
+			}
+			else if(type==SeqMatType){
+				this->smatrix->Echo();
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION Assemble{{{*/
+		void Assemble(void){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->Assemble();
+				#endif
+			}
+			else if(type==SeqMatType){
+				this->smatrix->Assemble();
+			}
+			else{
+				_error_("Matrix type: " << type << " not supported yet!");
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Norm{{{*/
+		IssmDouble Norm(NormMode norm_type){
+
+			IssmDouble norm=0;
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				norm=this->pmatrix->Norm(norm_type);
+				#endif
+			}
+			else if(type==SeqMatType){
+				norm=this->smatrix->Norm(norm_type);
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+
+			return norm;
+		}
+		/*}}}*/
+		/*FUNCTION GetSize{{{*/
+		void GetSize(int* pM,int* pN){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->GetSize(pM,pN);
+				#endif
+			}
+			else if(type==SeqMatType){
+				this->smatrix->GetSize(pM,pN);
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION GetLocalSize{{{*/
+		void GetLocalSize(int* pM,int* pN){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->GetLocalSize(pM,pN);
+				#endif
+			}
+			else if(type==SeqMatType){
+				this->smatrix->GetLocalSize(pM,pN);
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION MatMult{{{*/
+		void MatMult(Vector<doubletype>* X,Vector<doubletype>* AX){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->MatMult(X->pvector,AX->pvector);
+				#endif
+			}
+			else if(type==SeqMatType){
+				this->smatrix->MatMult(X->svector,AX->svector);
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION Duplicate{{{*/
+		Matrix* Duplicate(void){
+
+			Matrix* output=NULL;
+
+			output=new Matrix();
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				output->pmatrix=this->pmatrix->Duplicate();
+				#endif
+			}
+			else if(type==SeqMatType){
+				output->smatrix=this->smatrix->Duplicate();
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+
+			return output;
+		}
+		/*}}}*/
+		/*FUNCTION ToSerial{{{*/
+		doubletype* ToSerial(void){
+
+			doubletype* output=NULL;
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				output=this->pmatrix->ToSerial();
+				#endif
+			}
+			else if(type==SeqMatType){
+				output=this->smatrix->ToSerial();
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+
+
+			return output;
+		}
+		/*}}}*/
+		/*FUNCTION SetValues{{{*/
+		void SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->SetValues(m,idxm,n,idxn,values,mode);
+				#endif
+			}
+			else if(type==SeqMatType){
+				this->smatrix->SetValues(m,idxm,n,idxn,values,mode);
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+		}
+		/*}}}*/
+		/*FUNCTION Convert{{{*/
+		void Convert(MatrixType newtype){
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->Convert(newtype);
+				#endif
+			}
+			else if(type==SeqMatType){
+				this->smatrix->Convert(newtype);
+			}
+			else{
+				_error_("Matrix type: " << type << " not supported yet!");
+			}
+
+		}
+		/*}}}*/
+};
+
+#endif //#ifndef _MATRIX_H_
Index: /issm/trunk/src/c/classes/matrix/Vector.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/Vector.h	(revision 13395)
+++ /issm/trunk/src/c/classes/matrix/Vector.h	(revision 13395)
@@ -0,0 +1,469 @@
+/*!\file:  Vector.h
+ * \brief wrapper to vector objects. The goal is to control which API (PETSc,Scalpack, Plapack?) 
+ * implements our underlying vector format.
+ */ 
+
+#ifndef _VECTOR_H_
+#define _VECTOR_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+/*}}}*/
+
+enum vectortype { PetscVecType, SeqVecType };
+
+template <class doubletype> 
+class Vector{
+
+	public:
+
+		int  type;
+		#ifdef _HAVE_PETSC_
+		PetscVec* pvector;
+		#endif
+		SeqVec<doubletype>* svector; 
+
+		/*Vector constructors, destructors */
+		/*FUNCTION Vector(){{{*/
+		Vector(){
+
+			#ifdef _HAVE_PETSC_
+			this->pvector=NULL;
+			#endif
+			this->svector=NULL;
+
+			type=PetscVecType; //default
+			#ifndef _HAVE_PETSC_
+			type=SeqVecType;
+			#endif
+
+		}
+		/*}}}*/
+		/*FUNCTION Vector(int M,bool fromlocalsize,int in_type){{{*/
+		#ifdef _HAVE_PETSC_
+		Vector(int M,bool fromlocalsize=false,int in_type=PetscVecType){
+		#else
+		Vector(int M,bool fromlocalsize=false,int in_type=SeqVecType){
+		#endif
+
+			#ifdef _HAVE_PETSC_
+			pvector=NULL;
+			#endif
+			svector=NULL;
+			type=in_type;
+
+
+			if(type==PetscVecType){
+			#ifdef _HAVE_PETSC_
+				this->pvector=new PetscVec(M,fromlocalsize);
+			 #else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+			 #endif
+			}
+			else if(type==SeqVecType){
+				this->svector=new SeqVec<doubletype>(M,fromlocalsize);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION Vector(doubletype* serial_vec,int M,int in_type){{{*/
+		#ifdef _HAVE_PETSC_
+		Vector(doubletype* serial_vec,int M,int in_type=PetscVecType){
+		#else
+		Vector(doubletype* serial_vec,int M,int in_type=SeqVecType){
+			//} for vim
+		#endif
+
+			#ifdef _HAVE_PETSC_
+			pvector=NULL;
+			#endif
+
+			svector=NULL;
+			type=in_type;
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector=new PetscVec(serial_vec,M);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector=new SeqVec<doubletype>(serial_vec,M);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION ~Vector(){{{*/
+		~Vector(){
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				delete this->pvector;
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				delete this->svector;
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+		}
+		/*}}}*/
+		#ifdef _HAVE_PETSC_
+		/*FUNCTION Vector(Vec petsc_vector){{{*/
+		Vector(Vec petsc_vector){
+
+			this->type=PetscVecType;
+			this->svector=NULL;
+			this->pvector=new PetscVec(petsc_vector);
+
+		}
+		/*}}}*/
+		#endif
+
+		/*Vector specific routines*/
+		/*FUNCTION Echo{{{*/
+		void Echo(void){
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Echo();
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->Echo();
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION Assemble{{{*/
+		void Assemble(void){
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Assemble();
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->Assemble();
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION SetValues{{{*/
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){
+
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->SetValues(ssize,list,values,mode);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->SetValues(ssize,list,values,mode);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+
+
+		}
+		/*}}}*/
+		/*FUNCTION SetValue{{{*/
+		void SetValue(int dof, doubletype value, InsMode mode){
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->SetValue(dof,value,mode);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->SetValue(dof,value,mode);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION GetValue{{{*/
+		void GetValue(doubletype* pvalue,int dof){
+
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->GetValue(pvalue,dof);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->GetValue(pvalue,dof);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION GetSize{{{*/
+		void GetSize(int* pM){
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->GetSize(pM);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->GetSize(pM);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION IsEmpty{{{*/
+		bool IsEmpty(void){
+
+			int M;
+
+			this->GetSize(&M);
+
+			if(M==0) 
+				return true;
+			else
+				return false;
+		}
+		/*}}}*/
+		/*FUNCTION GetLocalSize{{{*/
+		void GetLocalSize(int* pM){
+
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->GetLocalSize(pM);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->GetLocalSize(pM);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION Duplicate{{{*/
+		Vector* Duplicate(void){
+
+			Vector* output=NULL;
+
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				output=new Vector();
+				output->pvector=this->pvector->Duplicate();
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				output=new Vector();
+				output->svector=this->svector->Duplicate();
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+			return output;
+
+		}
+		/*}}}*/
+		/*FUNCTION Set{{{*/
+		void Set(doubletype value){
+
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Set(value);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->Set(value);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION AXPY{{{*/
+		void AXPY(Vector* X, doubletype a){
+
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->AXPY(X->pvector,a);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->AXPY(X->svector,a);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION AYPX{{{*/
+		void AYPX(Vector* X, doubletype a){
+
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->AYPX(X->pvector,a);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->AYPX(X->svector,a);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+
+		}
+		/*}}}*/
+		/*FUNCTION ToMPISerial{{{*/
+		doubletype* ToMPISerial(void){
+
+			doubletype* vec_serial=NULL;
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				vec_serial=this->pvector->ToMPISerial();
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				vec_serial=this->svector->ToMPISerial();
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+			return vec_serial;
+
+		}
+		/*}}}*/
+		/*FUNCTION Copy{{{*/
+		void Copy(Vector* to){
+
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Copy(to->pvector);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->Copy(to->svector);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+
+		}
+		/*}}}*/
+		/*FUNCTION Norm{{{*/
+		doubletype Norm(NormMode norm_type){
+
+			doubletype norm=0;
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				norm=this->pvector->Norm(norm_type);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				norm=this->svector->Norm(norm_type);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+			return norm;
+		}
+		/*}}}*/
+		/*FUNCTION Scale{{{*/
+		void Scale(doubletype scale_factor){
+
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->Scale(scale_factor);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->Scale(scale_factor);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION Dot{{{*/
+		doubletype Dot(Vector* vector){
+
+			doubletype dot;
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				dot=this->pvector->Dot(vector->pvector);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				dot=this->svector->Dot(vector->svector);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+			return dot;
+		}
+		/*}}}*/
+		/*FUNCTION PointwiseDivide{{{*/
+		void PointwiseDivide(Vector* x,Vector* y){
+
+
+			if(type==PetscVecType){
+				#ifdef _HAVE_PETSC_
+				this->pvector->PointwiseDivide(x->pvector,y->pvector);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqVecType){
+				this->svector->PointwiseDivide(x->svector,y->svector);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+};
+#endif //#ifndef _VECTOR_H_
Index: /issm/trunk/src/c/classes/matrix/matrixobjects.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/matrixobjects.h	(revision 13395)
+++ /issm/trunk/src/c/classes/matrix/matrixobjects.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects.h
===================================================================
--- /issm/trunk/src/c/classes/objects.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Constraints/Constraint.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Constraints/Constraint.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Constraints/Constraint.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Constraints/SpcDynamic.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Constraints/SpcDynamic.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Constraints/SpcDynamic.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Constraints/SpcDynamic.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Constraints/SpcDynamic.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Constraints/SpcDynamic.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Constraints/SpcStatic.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Constraints/SpcStatic.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Constraints/SpcStatic.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Constraints/SpcStatic.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Constraints/SpcStatic.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Constraints/SpcStatic.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Constraints/SpcTransient.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Constraints/SpcTransient.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Constraints/SpcTransient.cpp	(revision 13395)
@@ -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)_error_("could not find time segment for constraint");
+
+		/*Apply or relax constraint: */
+		if(xIsNan<IssmDouble>(value)){
+			node->RelaxConstraint(dof);
+		}
+		else node->ApplyConstraint(dof,value);
+	}
+}
+/*}}}*/
+
+/*SpcTransient functions*/
+/*FUNCTION SpcTransient::GetDof {{{*/
+int SpcTransient::GetDof(){
+	return dof;
+}
+/*}}}*/
+/*FUNCTION SpcTransient::GetNodeId {{{*/
+int   SpcTransient::GetNodeId(){
+	
+	return nodeid;
+}
+/*}}}*/
+/*FUNCTION SpcTransient::GetValue {{{*/
+IssmDouble SpcTransient::GetValue(){
+	return values[0];
+}
+/*}}}*/
+
Index: /issm/trunk/src/c/classes/objects/Constraints/SpcTransient.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Constraints/SpcTransient.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Constraints/SpcTransient.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Contour.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Contour.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Contour.h	(revision 13395)
@@ -0,0 +1,112 @@
+/*!\file Contour.h
+ * \brief: header file for Contour object
+ */
+
+#ifndef _CONTOUR_H_
+#define _CONTOUR_H_
+
+/*Headers:*/
+/*{{{*/
+#include "../../include/include.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/Alloc/xNewDelete.h"
+#include "../../shared/MemOps/xMemCpy.h"
+#include "../../io/io.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "./Object.h"
+/*}}}*/
+
+template <class doubletype>
+class Contour: public Object{
+
+	public: 
+
+		int     id;
+		int	  nods;  //number of vertices in the contour
+		doubletype* x;
+		doubletype* y;
+		bool    closed; //is this contour closed?
+
+		/*Contour constructors, destructors :*/
+		/*FUNCTION Contour() default constructor {{{*/
+		Contour(){
+			this->id=0;
+			this->nods=0;
+			this->x=NULL;
+			this->y=NULL;
+			this->closed=false;
+		}
+		/*}}}*/
+		/*FUNCTION Contour(int pid, int nods, doubletype* x, doubletype* y,bool closed) {{{*/
+		Contour(int pid,int pnods, doubletype* px, doubletype* py,bool pclosed){
+
+			this->id=pid;
+			this->nods=pnods;
+			this->closed=pclosed;
+			if(nods){
+				this->x=xNew<doubletype>(nods);
+				xMemCpy<doubletype>(this->x,px,nods);
+				this->y=xNew<doubletype>(nods);
+				xMemCpy<doubletype>(this->y,py,nods);
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Contour() default constructor {{{*/
+		~Contour(){
+			xDelete<doubletype>(this->x);
+			xDelete<doubletype>(this->y);
+		}
+		/*}}}*/
+
+
+		/*Object virtual function resolutoin: */
+		/*FUNCTION Echo(){{{*/
+		void 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 DeepEcho(){{{*/
+		void DeepEcho(void){
+			this->Echo();
+		}
+		/*}}}*/
+		/*FUNCTION Id(){{{*/
+		int Id(void){
+			return id;
+		}
+		/*}}}*/
+		/*FUNCTION MyRank{{{*/
+		int    MyRank(void){ 
+			extern int my_rank;
+
+			return my_rank; 
+		}
+		/*}}}*/
+		/*FUNCTION ObjectEnum{{{*/
+		int ObjectEnum(void){
+
+			return ContourEnum;
+
+		}
+		/*}}}*/
+		/*FUNCTION copy {{{*/
+		Object* copy() {
+
+			return new Contour(*this); 
+
+		}
+		/*}}}*/
+};
+
+#endif  /* _CONTOUR_H_ */
Index: /issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.cpp	(revision 13395)
@@ -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<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs){
+
+	_error_("cannot return vector on vertices");
+} /*}}}*/
+/*FUNCTION BoolElementResult::GetElementVectorFromResults{{{*/
+void BoolElementResult::GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof){
+
+	vector->SetValue(dof,value,INS_VAL);
+} /*}}}*/
Index: /issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.h	(revision 13395)
@@ -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<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof);
+		/*}}}*/
+};
+#endif  /* _BOOLELEMENTRESULT_H */
Index: /issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.cpp	(revision 13395)
@@ -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<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs){
+
+	_error_("cannot return vector on vertices");
+} /*}}}*/
+/*FUNCTION DoubleElementResult::GetElementVectorFromResults{{{1*/
+void DoubleElementResult::GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof){
+
+	vector->SetValue(dof,value,INS_VAL);
+} /*}}}*/
Index: /issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.h	(revision 13395)
@@ -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<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof);
+		/*}}}*/
+};
+#endif  /* _DOUBLEELEMENTRESULT_H */
Index: /issm/trunk/src/c/classes/objects/ElementResults/ElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/ElementResult.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/ElementResults/ElementResult.h	(revision 13395)
@@ -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<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdof)=0;
+		virtual void    GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof)=0;
+
+};
+
+#endif
Index: /issm/trunk/src/c/classes/objects/ElementResults/ElementResultLocal.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/ElementResultLocal.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/ElementResults/ElementResultLocal.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp	(revision 13395)
@@ -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<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs){
+
+	IssmDouble data[6];
+
+	if(numdofs!=6)_error_("Result " << EnumToStringx(this->enum_type) << " is a PentaP1ElementResult and cannot write vector of " << numdofs << " dofs");
+	for(int i=0;i<6;i++) data[i]=this->values[i]/(IssmDouble)connectivitylist[i];
+	vector->SetValues(numdofs,doflist,&data[0],ADD_VAL);
+
+} /*}}}*/
+/*FUNCTION PentaP1ElementResult::GetElementVectorFromResults{{{*/
+void PentaP1ElementResult::GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof){
+
+	_error_("Result " << EnumToStringx(enum_type) << " is a PentaP1ElementResult and should not write vector of size numberofelemenrs");
+} /*}}}*/
Index: /issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.h	(revision 13395)
@@ -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<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof);
+		/*}}}*/
+
+};
+#endif  /* _PENTAP1ELEMENTRESULT_H */
Index: /issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp	(revision 13395)
@@ -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<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs){
+
+	IssmDouble data[3];
+
+	if(numdofs!=3)_error_("Result " << EnumToStringx(this->enum_type) << " is a TriaP1ElementResult and cannot write vector of " << numdofs << " dofs");
+	for(int i=0;i<3;i++) data[i]=this->values[i]/(IssmDouble)connectivitylist[i];
+	vector->SetValues(numdofs,doflist,&data[0],ADD_VAL);
+
+} /*}}}*/
+/*FUNCTION TriaP1ElementResult::GetElementVectorFromResults{{{*/
+void TriaP1ElementResult::GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof){
+	_error_("Result " << EnumToStringx(enum_type) << " is a TriaP1ElementResult and should not write vector of size numberofelemenrs");
+} /*}}}*/
Index: /issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.h	(revision 13395)
@@ -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<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs);
+		void GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof);
+		/*}}}*/
+
+};
+#endif  /* _TRIAP1ELEMENTRESULT_H */
Index: /issm/trunk/src/c/classes/objects/Elements/Element.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/Element.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/Element.h	(revision 13395)
@@ -0,0 +1,119 @@
+/*!\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;
+template <class doublematrix> class Matrix;
+template <class doubletype> class Vector;
+
+#include "../../../toolkits/toolkits.h"
+/*}}}*/
+
+class Element: public Object,public Update{
+
+	public: 
+		
+		virtual        ~Element(){};
+	
+		virtual void   Configure(Elements* elements,Loads* loads,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<IssmDouble>* Kff, Matrix<IssmDouble>*  Kfs,Vector<IssmDouble>* df)=0;
+		virtual void   CreatePVector(Vector<IssmDouble>* pf)=0;
+		virtual void   CreateJacobianMatrix(Matrix<IssmDouble>* Jff)=0;
+		virtual void   GetSolutionFromInputs(Vector<IssmDouble>* solution)=0;
+		virtual int    GetNodeIndex(Node* node)=0;
+		virtual int    Sid()=0;
+		virtual bool   IsFloating()=0; 
+		virtual bool   IsNodeOnShelf()=0; 
+		virtual bool   IsNodeOnShelfFromFlags(IssmDouble* flags)=0; 
+		virtual bool   IsOnBed()=0;
+		virtual void   GetInputListOnVertices(IssmDouble* pvalue,int enumtype)=0;
+		virtual void   GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue)=0;
+		virtual void   GetInputValue(IssmDouble* pvalue,Node* node,int enumtype)=0;
+		
+		virtual IssmDouble SurfaceArea(void)=0;
+		virtual void   InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum)=0;
+		virtual void   ComputeBasalStress(Vector<IssmDouble>* sigma_b)=0;
+		virtual void   ComputeStrainRate(Vector<IssmDouble>* eps)=0;
+		virtual void   PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes)=0;
+		virtual void   PatchFill(int* pcount, Patch* patch)=0;
+		virtual void   ListResultsInfo(int** results_enums,int** results_size,IssmDouble** results_times,int** results_steps,int* num_results)=0;
+		virtual void   DeleteResults(void)=0;
+		virtual void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type)=0;
+		virtual void   InputToResult(int enum_type,int step,IssmDouble time)=0;
+		virtual void   InputDuplicate(int original_enum,int new_enum)=0;
+		virtual void   InputCreate(IssmDouble scalar,int name,int code)=0;
+		virtual void   InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code)=0;
+		virtual void   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<IssmDouble>* vector, int name_enum)=0;
+		virtual void   GetVectorFromResults(Vector<IssmDouble>* vector,int id,int enum_in,int interp)=0;
+		virtual void   InputArtificialNoise(int enum_type,IssmDouble min,IssmDouble max)=0;
+		virtual bool   InputConvergence(IssmDouble* eps, int* enums,int num_enums,int* criterionenums,IssmDouble* criterionvalues,int num_criterionenums)=0;
+		virtual void   AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* 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<IssmDouble>* 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<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf)=0;
+		virtual void   ResetCoordinateSystem()=0;
+		virtual void   SmearFunction(Vector<IssmDouble>* 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<IssmDouble>* 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 ThicknessAlongGradient(bool process_units,int weight_index)=0;
+		virtual IssmDouble ThicknessAcrossGradient(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<IssmDouble>* gradient,int enum_type,int control_index)=0;
+		virtual void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index)=0;
+		virtual void   ControlInputScaleGradient(int enum_type, IssmDouble scale)=0;
+		virtual void   GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data)=0;
+		virtual void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index)=0;
+		virtual void   InputControlUpdate(IssmDouble scalar,bool save_parameter)=0;
+		#endif
+};
+#endif
Index: /issm/trunk/src/c/classes/objects/Elements/Penta.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/Penta.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/Penta.cpp	(revision 13395)
@@ -0,0 +1,9135 @@
+/*!\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->material=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: material id, iomodel->numberofelements+1: matpar id
+                                                                      { //i is the element index
+
+	int i;
+	int penta_elements_ids[2];
+
+	/*Checks in debugging mode*/
+	/*{{{*/
+	_assert_(iomodel->Data(MeshUpperelementsEnum));
+	_assert_(iomodel->Data(MeshLowerelementsEnum));
+	/*}}}*/
+
+	/*id: */
+	this->id=penta_id;
+	this->sid=penta_sid;
+
+	/*Build neighbors list*/
+	if (xIsNan<IssmDouble>(iomodel->Data(MeshUpperelementsEnum)[index])) penta_elements_ids[1]=this->id; //upper penta is the same penta
+	else                                    penta_elements_ids[1]=reCast<int,IssmDouble>((iomodel->Data(MeshUpperelementsEnum)[index]));
+	if (xIsNan<IssmDouble>(iomodel->Data(MeshLowerelementsEnum)[index])) penta_elements_ids[0]=this->id; //lower penta is the same penta
+	else                                    penta_elements_ids[0]=reCast<int,IssmDouble>((iomodel->Data(MeshLowerelementsEnum)[index]));
+	this->InitHookNeighbors(penta_elements_ids);
+
+	/*Build horizontalneighborsids list: */
+	_assert_(iomodel->Data(MeshElementconnectivityEnum));
+	for(i=0;i<3;i++) this->horizontalneighborsids[i]=reCast<int,IssmDouble>(iomodel->Data(MeshElementconnectivityEnum)[3*index+i])-1;
+
+	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
+	this->parameters=NULL;
+
+	/*intialize inputs and results: */
+	this->inputs=new Inputs();
+	this->results=new Results();
+	
+	/*initialize pointers:*/
+	this->nodes=NULL;
+	this->material=NULL;
+	this->matpar=NULL;
+	this->verticalneighbors=NULL;
+}
+/*}}}*/
+/*FUNCTION Penta::copy {{{*/
+Object* Penta::copy() {
+
+	int i;
+
+	Penta* penta=NULL;
+
+	penta=new Penta();
+
+	//deal with PentaRef mother class
+	penta->element_type_list=xNew<int>(this->numanalyses);
+	for(i=0;i<this->numanalyses;i++) penta->element_type_list[i]=this->element_type_list[i];
+
+	//deal with 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->hmaterial=(Hook*)this->hmaterial->copy();
+	penta->hmatpar=(Hook*)this->hmatpar->copy();
+	penta->hneighbors=(Hook*)this->hneighbors->copy();
+
+	/*deal with Penta  copy fields: */
+	penta->id=this->id;
+	penta->sid=this->sid;
+	if(this->inputs){
+		penta->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		penta->inputs=new Inputs();
+	}
+	if(this->results){
+		penta->results=(Results*)this->results->Copy();
+	}
+	else{
+		penta->results=new Results();
+	}
+	/*point parameters: */
+	penta->parameters=this->parameters;
+
+	/*recover objects: */
+	penta->nodes=xNew<Node*>(6); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
+	for(i=0;i<6;i++)penta->nodes[i]=this->nodes[i];
+	penta->material=(Material*)penta->hmaterial->delivers();
+	penta->matpar=(Matpar*)penta->hmatpar->delivers();
+	penta->verticalneighbors=(Penta**)penta->hneighbors->deliverp();
+
+	/*neighbors: */
+	for(i=0;i<3;i++)penta->horizontalneighborsids[i]=this->horizontalneighborsids[i];
+
+	return penta;
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION Penta::AverageOntoPartition {{{*/
+void  Penta::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){
+	_error_("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<IssmDouble>* 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) _error_("Not supported yet!");
+	if (approximation!=StokesApproximationEnum) _error_("Not supported yet!");
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	
+	if(!IsOnBed()){
+		//put zero
+		sigma_b->SetValue(id-1,0.0,INS_VAL);
+		return;
+	}
+
+	/*recovre material parameters: */
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], 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);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*Compute Stress*/
+		sigma_xx=2*viscosity*epsilon[0]-pressure*stokesreconditioning; // sigma = nu eps - pressure
+		sigma_yy=2*viscosity*epsilon[1]-pressure*stokesreconditioning;
+		sigma_zz=2*viscosity*epsilon[2]-pressure*stokesreconditioning;
+		sigma_xy=2*viscosity*epsilon[3];
+		sigma_xz=2*viscosity*epsilon[4];
+		sigma_yz=2*viscosity*epsilon[5];
+
+		/*Get normal vector to the bed */
+		BedNormal(&bed_normal[0],xyz_list_tria);
+
+		/*basalforce*/
+		basalforce[0] += sigma_xx*bed_normal[0] + sigma_xy*bed_normal[1] + sigma_xz*bed_normal[2];
+		basalforce[1] += sigma_xy*bed_normal[0] + sigma_yy*bed_normal[1] + sigma_yz*bed_normal[2];
+		basalforce[2] += sigma_xz*bed_normal[0] + sigma_yz*bed_normal[1] + sigma_zz*bed_normal[2];
+
+		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
+		value+=sigma_zz*Jdet2d*gauss->weight;
+		surface+=Jdet2d*gauss->weight;
+	}
+	value=value/surface;
+
+	/*Add value to output*/
+	sigma_b->SetValue(id-1,value,INS_VAL);
+}
+/*}}}*/
+/*FUNCTION Penta::ComputeStrainRate {{{*/
+void  Penta::ComputeStrainRate(Vector<IssmDouble>* eps){
+
+	_error_("Not implemented yet");
+
+}
+/*}}}*/
+/*FUNCTION Penta::ComputeStressTensor {{{*/
+void  Penta::ComputeStressTensor(){
+
+	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);
+		material->GetViscosity3d(&viscosity,&epsilon[0]);
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*Compute Stress*/
+		sigma_xx[iv]=2*viscosity*epsilon[0]-pressure; // sigma = nu eps - pressure
+		sigma_yy[iv]=2*viscosity*epsilon[1]-pressure;
+		sigma_zz[iv]=2*viscosity*epsilon[2]-pressure;
+		sigma_xy[iv]=2*viscosity*epsilon[3];
+		sigma_xz[iv]=2*viscosity*epsilon[4];
+		sigma_yz[iv]=2*viscosity*epsilon[5];
+	}
+	
+	/*Add Stress tensor components into inputs*/
+	this->inputs->AddInput(new PentaP1Input(StressTensorxxEnum,&sigma_xx[0]));
+	this->inputs->AddInput(new PentaP1Input(StressTensorxyEnum,&sigma_xy[0]));
+	this->inputs->AddInput(new PentaP1Input(StressTensorxzEnum,&sigma_xz[0]));
+	this->inputs->AddInput(new PentaP1Input(StressTensoryyEnum,&sigma_yy[0]));
+	this->inputs->AddInput(new PentaP1Input(StressTensoryzEnum,&sigma_yz[0]));
+	this->inputs->AddInput(new PentaP1Input(StressTensorzzEnum,&sigma_zz[0]));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+		/*FUNCTION Penta::Configure {{{*/
+void  Penta::Configure(Elements* elementsin, Loads* loadsin, 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->hmaterial->configure(materialsin);
+	this->hmatpar->configure(materialsin);
+	this->hneighbors->configure(elementsin);
+
+	/*Now, go pick up the objects inside the hooks: */
+	if (this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+	this->material=(Material*)this->hmaterial->delivers();
+	this->matpar=(Matpar*)this->hmatpar->delivers();
+	this->verticalneighbors=(Penta**)this->hneighbors->deliverp();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+	/*get inputs configured too: */
+	this->inputs->Configure(parameters);
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrix {{{*/
+void  Penta::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,Vector<IssmDouble>* df){
+
+	/*retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	ElementVector* De=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging {{{*/
+	_assert_(this->nodes && this->material && this->matpar && this->verticalneighbors && this->parameters && this->inputs);
+	/*}}}*/
+	
+	/*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=CreateBasalMassMatrix();
+			break;
+		case PrognosticAnalysisEnum:
+			Ke=CreateKMatrixPrognostic();
+			break;
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixBalancethickness();
+			break;
+		#endif
+		#ifdef _HAVE_THERMAL_
+		case ThermalAnalysisEnum:
+			Ke=CreateKMatrixThermal();
+			break;
+		case EnthalpyAnalysisEnum:
+			Ke=CreateKMatrixEnthalpy();
+			break;
+		case MeltingAnalysisEnum:
+			Ke=CreateKMatrixMelting();
+			break;
+		#endif
+		default:
+			_error_("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->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateBasalMassMatrix{{{*/
+ElementMatrix* Penta::CreateBasalMassMatrix(void){
+
+	if (!IsOnBed()) return NULL;
+
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateMassMatrix();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVector {{{*/
+void  Penta::CreatePVector(Vector<IssmDouble>* pf){
+
+	/*retrive parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*if debugging mode, check that all pointers exist {{{*/
+	_assert_(this->nodes && this->material && this->matpar && this->verticalneighbors && this->parameters && this->inputs);
+	/*}}}*/
+
+	/*Skip if water element*/
+	if(IsOnWater()) return;
+
+	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum:
+			pe=CreatePVectorDiagnosticHoriz();
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			pe=CreatePVectorDiagnosticHutter();
+			break;
+		case DiagnosticVertAnalysisEnum:
+			pe=CreatePVectorDiagnosticVert();
+			break;
+		#endif
+	 	#ifdef _HAVE_CONTROL_
+		case AdjointHorizAnalysisEnum:
+			pe=CreatePVectorAdjointHoriz();
+			break;
+		#endif
+		#ifdef _HAVE_THERMAL_
+		case ThermalAnalysisEnum:
+			pe=CreatePVectorThermal();
+			break;
+		case EnthalpyAnalysisEnum:
+			pe=CreatePVectorEnthalpy();
+			break;
+		case MeltingAnalysisEnum:
+			pe=CreatePVectorMelting();
+			break;
+		#endif
+		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+			pe=CreatePVectorSlope();
+			break;
+		case PrognosticAnalysisEnum:
+			pe=CreatePVectorPrognostic();
+			break;
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			pe=CreatePVectorBalancethickness();
+			break;
+		#endif
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorPrognostic {{{*/
+ElementVector* Penta::CreatePVectorPrognostic(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorPrognostic();
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorSlope {{{*/
+ElementVector* Penta::CreatePVectorSlope(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorSlope();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateJacobianMatrix{{{*/
+void  Penta::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){
+
+	/*retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging {{{*/
+	_assert_(this->nodes && this->material && this->matpar && this->verticalneighbors && this->parameters && this->inputs);
+	/*}}}*/
+
+	/*Skip if water element*/
+	if(IsOnWater()) return;
+
+	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum:
+			Ke=CreateJacobianDiagnosticHoriz();
+			break;
+#endif
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Jff);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::DeepEcho{{{*/
+void Penta::DeepEcho(void){
+
+	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();
+	material->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){
+        /*Are we on the base? If not, return*/
+        if(!IsOnBed()) return;
+
+	int        i;
+	IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+	IssmDouble TemperaturesPresentday[NUMVERTICES][12],TemperaturesLgm[NUMVERTICES][12];
+	IssmDouble PrecipitationsPresentday[NUMVERTICES][12];
+	IssmDouble tmp[NUMVERTICES];
+	IssmDouble Delta18oPresent,Delta18oLgm,Delta18oTime;
+	IssmDouble Delta18oSurfacePresent,Delta18oSurfaceLgm,Delta18oSurfaceTime;
+	IssmDouble time,yts,finaltime;
+	this->parameters->FindParam(&time,TimeEnum);
+	this->parameters->FindParam(&yts,ConstantsYtsEnum);
+	this->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
+
+	/*Recover present day temperature and precipitation*/
+	Input*     input=inputs->GetInput(SurfaceforcingsTemperaturesPresentdayEnum);    _assert_(input);
+	Input*     input2=inputs->GetInput(SurfaceforcingsTemperaturesLgmEnum);          _assert_(input2);
+	Input*     input3=inputs->GetInput(SurfaceforcingsPrecipitationsPresentdayEnum); _assert_(input3);
+	GaussPenta* gauss=new GaussPenta();
+	for(int month=0;month<12;month++) {
+		for(int iv=0;iv<NUMVERTICES;iv++) {
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&TemperaturesPresentday[iv][month],gauss,month/12.*yts);
+			input2->GetInputValue(&TemperaturesLgm[iv][month],gauss,month/12.*yts);
+			input3->GetInputValue(&PrecipitationsPresentday[iv][month],gauss,month/12.*yts);
+			PrecipitationsPresentday[iv][month]=PrecipitationsPresentday[iv][month]/yts; // converion in m/sec
+		}
+	}
+
+	/*Recover delta18o and Delta18oSurface at present day, lgm and at time t*/
+	this->parameters->FindParam(&Delta18oPresent,SurfaceforcingsDelta18oEnum,finaltime);
+	this->parameters->FindParam(&Delta18oLgm,SurfaceforcingsDelta18oEnum,finaltime-(21000*yts));
+	this->parameters->FindParam(&Delta18oTime,SurfaceforcingsDelta18oEnum,time);
+	this->parameters->FindParam(&Delta18oSurfacePresent,SurfaceforcingsDelta18oSurfaceEnum,finaltime);
+	this->parameters->FindParam(&Delta18oSurfaceLgm,SurfaceforcingsDelta18oSurfaceEnum,finaltime-(21000*yts));
+	this->parameters->FindParam(&Delta18oSurfaceTime,SurfaceforcingsDelta18oSurfaceEnum,time);
+
+	/*Compute the temperature and precipitation*/
+	for(int iv=0;iv<NUMVERTICES;iv++){
+		ComputeDelta18oTemperaturePrecipitation(Delta18oSurfacePresent, Delta18oSurfaceLgm, Delta18oSurfaceTime, 
+					Delta18oPresent, Delta18oLgm, Delta18oTime,
+					&PrecipitationsPresentday[iv][0], 
+					&TemperaturesLgm[iv][0], &TemperaturesPresentday[iv][0], 
+					&monthlytemperatures[iv][0], &monthlyprec[iv][0]);
+	}
+
+	/*Update inputs*/ 
+	TransientInput* NewTemperatureInput = new TransientInput(SurfaceforcingsMonthlytemperaturesEnum);
+	TransientInput* NewPrecipitationInput = new TransientInput(SurfaceforcingsPrecipitationEnum);
+	for (int imonth=0;imonth<12;imonth++) {
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlytemperatures[i][imonth];
+		PentaP1Input* newmonthinput1 = new PentaP1Input(SurfaceforcingsMonthlytemperaturesEnum,&tmp[0]);
+		NewTemperatureInput->AddTimeInput(newmonthinput1,time+imonth/12.*yts);
+
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlyprec[i][imonth];
+		PentaP1Input* newmonthinput2 = new PentaP1Input(SurfaceforcingsPrecipitationEnum,&tmp[0]);
+		NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
+	}
+
+	this->inputs->AddInput(NewTemperatureInput);
+	this->inputs->AddInput(NewPrecipitationInput);
+
+	this->InputExtrude(SurfaceforcingsMonthlytemperaturesEnum,ElementEnum);
+	this->InputExtrude(SurfaceforcingsPrecipitationEnum,ElementEnum);
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::Echo{{{*/
+
+void Penta::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION Penta::ObjectEnum{{{*/
+int Penta::ObjectEnum(void){
+
+	return PentaEnum;
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetBasalElement{{{*/
+Penta* Penta::GetBasalElement(void){
+
+	/*Output*/
+	Penta* penta=NULL;
+
+	/*Go through all elements till the bed is reached*/
+	penta=this;
+	for(;;){
+		/*Stop if we have reached the surface, else, take lower penta*/
+		if (penta->IsOnBed()) break;
+
+		/* get lower Penta*/
+		penta=penta->GetLowerElement();
+		_assert_(penta->Id()!=this->id);
+	}
+
+	/*return output*/
+	return penta;
+}
+/*}}}*/
+/*FUNCTION Penta::GetDofList {{{*/
+void  Penta::GetDofList(int** pdoflist,int approximation_enum,int setenum){
+
+	int  i,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;
+	}
+	_error_("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) _error_("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) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+
+	GaussPenta* gauss=new GaussPenta();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::GetPhi {{{*/
+void Penta::GetPhi(IssmDouble* phi, IssmDouble*  epsilon, IssmDouble viscosity){
+	/*Compute deformational heating from epsilon and viscosity */
+
+	IssmDouble epsilon_matrix[3][3];
+	IssmDouble epsilon_eff;
+	IssmDouble epsilon_sqr[3][3];
+
+	/* Build epsilon matrix */
+	epsilon_matrix[0][0]=*(epsilon+0);
+	epsilon_matrix[1][0]=*(epsilon+3);
+	epsilon_matrix[2][0]=*(epsilon+4);
+	epsilon_matrix[0][1]=*(epsilon+3);
+	epsilon_matrix[1][1]=*(epsilon+1);
+	epsilon_matrix[2][1]=*(epsilon+5);
+	epsilon_matrix[0][2]=*(epsilon+4);
+	epsilon_matrix[1][2]=*(epsilon+5);
+	epsilon_matrix[2][2]=*(epsilon+2);
+
+	/* Effective value of epsilon_matrix */
+	epsilon_sqr[0][0]=pow(epsilon_matrix[0][0],2);
+	epsilon_sqr[1][0]=pow(epsilon_matrix[1][0],2);
+	epsilon_sqr[2][0]=pow(epsilon_matrix[2][0],2);
+	epsilon_sqr[0][1]=pow(epsilon_matrix[0][1],2);
+	epsilon_sqr[1][1]=pow(epsilon_matrix[1][1],2);
+	epsilon_sqr[2][1]=pow(epsilon_matrix[2][1],2);
+	epsilon_sqr[0][2]=pow(epsilon_matrix[0][2],2);
+	epsilon_sqr[1][2]=pow(epsilon_matrix[1][2],2);
+	epsilon_sqr[2][2]=pow(epsilon_matrix[2][2],2);
+	epsilon_eff=1/pow(2,0.5)*pow((epsilon_sqr[0][0]+epsilon_sqr[0][1]+ epsilon_sqr[0][2]+ epsilon_sqr[1][0]+ epsilon_sqr[1][1]+ epsilon_sqr[1][2]+ epsilon_sqr[2][0]+ epsilon_sqr[2][1]+ epsilon_sqr[2][2]),0.5);
+
+	/*Phi = Tr(sigma * eps) 
+	 *    = Tr(sigma'* eps)
+	 *    = 2 * eps_eff * sigma'_eff
+	 *    = 4 * mu * eps_eff ^2*/
+	*phi=4*pow(epsilon_eff,2.0)*viscosity;
+}
+/*}}}*/
+/*FUNCTION Penta::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<IssmDouble>* solution){
+
+	int analysis_type;
+
+	/*retrive parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Just branch to the correct InputUpdateFromSolution generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+	#ifdef _HAVE_DIAGNOSTIC_
+	case DiagnosticHorizAnalysisEnum:
+		int approximation;
+		inputs->GetInputValue(&approximation,ApproximationEnum);
+		if(approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
+			GetSolutionFromInputsDiagnosticStokes(solution);
+		}
+		else if (approximation==MacAyealApproximationEnum || approximation==PattynApproximationEnum || approximation==HutterApproximationEnum){
+			GetSolutionFromInputsDiagnosticHoriz(solution);
+		}
+		else if (approximation==MacAyealPattynApproximationEnum || approximation==PattynStokesApproximationEnum || approximation==MacAyealStokesApproximationEnum){
+			return; //the elements around will create the solution
+		}
+		break;
+	case DiagnosticHutterAnalysisEnum:
+		GetSolutionFromInputsDiagnosticHutter(solution);
+		break;
+	case DiagnosticVertAnalysisEnum:
+		GetSolutionFromInputsDiagnosticVert(solution);
+		break;
+	#endif
+	#ifdef _HAVE_THERMAL_
+	case ThermalAnalysisEnum:
+		GetSolutionFromInputsThermal(solution);
+		break;
+	case EnthalpyAnalysisEnum:
+		GetSolutionFromInputsEnthalpy(solution);
+		break;
+	#endif
+	default:
+		_error_("analysis: " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::GetStabilizationParameter {{{*/
+IssmDouble Penta::GetStabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){
+	/*Compute stabilization parameter*/
+	/*kappa=thermalconductivity/(rho_ice*hearcapacity) for thermal model*/
+	/*kappa=enthalpydiffusionparameter for enthalpy model*/
+
+	IssmDouble normu;
+	IssmDouble tau_parameter;
+
+	normu=pow(pow(u,2)+pow(v,2)+pow(w,2),0.5);
+	if(normu*diameter/(3*2*kappa)<1){ 
+		tau_parameter=pow(diameter,2)/(3*2*2*kappa);
+	}
+	else tau_parameter=diameter/(2*normu);
+
+	return tau_parameter;
+}
+/*}}}*/
+/*FUNCTION Penta::GetStrainRate3dPattyn{{{*/
+void Penta::GetStrainRate3dPattyn(IssmDouble* epsilon,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input){
+	/*Compute the 3d Blatter/PattynStrain Rate (5 components):
+	 *
+	 * epsilon=[exx eyy exy exz eyz]
+	 *
+	 * with exz=1/2 du/dz
+	 *      eyz=1/2 dv/dz
+	 *
+	 * the contribution of vz is neglected
+	 */
+
+	int i;
+	IssmDouble epsilonvx[5];
+	IssmDouble epsilonvy[5];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetVxStrainRate3dPattyn(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate3dPattyn(epsilonvy,xyz_list,gauss);
+
+	/*Sum all contributions*/
+	for(i=0;i<5;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i];
+}
+/*}}}*/
+/*FUNCTION Penta::GetStrainRate3d{{{*/
+void Penta::GetStrainRate3d(IssmDouble* epsilon,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input, Input* vz_input){
+	/*Compute the 3d Strain Rate (6 components):
+	 *
+	 * epsilon=[exx eyy ezz exy exz eyz]
+	 */
+
+	int i;
+	IssmDouble epsilonvx[6];
+	IssmDouble epsilonvy[6];
+	IssmDouble epsilonvz[6];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input || !vz_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << ", vz: " << vz_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetVxStrainRate3d(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate3d(epsilonvy,xyz_list,gauss);
+	vz_input->GetVzStrainRate3d(epsilonvz,xyz_list,gauss);
+
+	/*Sum all contributions*/
+	for(i=0;i<6;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i]+epsilonvz[i];
+}
+/*}}}*/
+/*FUNCTION Penta::GetUpperElement{{{*/
+Penta* Penta::GetUpperElement(void){
+
+	Penta* upper_penta=NULL;
+
+	upper_penta=(Penta*)verticalneighbors[1]; //first one under, second one above
+
+	return upper_penta;
+}
+/*}}}*/
+/*FUNCTION Penta::GetVectorFromInputs{{{*/
+void  Penta::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
+
+	int 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) _error_("Input " << EnumToStringx(input_enum) << " not found in element");
+
+	/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
+	input->GetVectorFromInputs(vector,&doflist1[0]);
+}
+/*}}}*/
+/*FUNCTION Penta::GetVectorFromResults{{{*/
+void  Penta::GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int enum_in,int interp){
+
+	/*Get result*/
+	ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(offset);
+	if(elementresult->InstanceEnum()!=enum_in){
+		_error_("Results of offset "<<offset<<" is "<<EnumToStringx(elementresult->InstanceEnum())<<" when "<<EnumToStringx(enum_in)<<" was expected");
+	}  
+	if(interp==P1Enum){
+		int 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)_error_("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])_error_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
+		if(!old_inputs[i])_error_("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,reCast<bool,IssmDouble>(scalar)));
+	}
+	else if ((code==6) || (code==2)){ //integer
+		this->inputs->AddInput(new IntInput(name,reCast<int,IssmDouble>(scalar)));
+	}
+	else if ((code==7) || (code==3)){ //IssmDouble
+		this->inputs->AddInput(new DoubleInput(name,scalar));
+	}
+	else _error_("could not recognize nature of vector from code " << code);
+
+}
+/*}}}*/
+/*FUNCTION Penta::InputCreate(IssmDouble* vector,int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){{{*/
+void Penta::InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){//index into elements
+
+	/*Intermediaries*/
+	int    i,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]=reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[6*index+i]); //ids for vertices are in the elements array from Matlab
+		}
+
+		/*Are we in transient or static? */
+		if(M==numberofvertices){
+
+			/*create input values: */
+			for(i=0;i<6;i++)nodeinputs[i]=(IssmDouble)vector[penta_vertex_ids[i]-1];
+
+			/*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 _error_("nodal vector is either numberofnodes (" << numberofvertices << "), or numberofnodes+1 long. Field provided is " << M << " long. Enum " << EnumToStringx(vector_enum));
+	}
+	else if(vector_type==2){ //element vector
+		/*Are we in transient or static? */
+		if(M==numberofelements){
+
+			/*static mode: create an input out of the element value: */
+
+			if (code==5){ //boolean
+				this->inputs->AddInput(new BoolInput(vector_enum,reCast<bool,IssmDouble>(vector[index])));
+			}
+			else if (code==6){ //integer
+				this->inputs->AddInput(new IntInput(vector_enum,reCast<int,IssmDouble>(vector[index])));
+			}
+			else if (code==7){ //IssmDouble
+				this->inputs->AddInput(new DoubleInput(vector_enum,vector[index]));
+			}
+			else _error_("could not recognize nature of vector from code " << code);
+		}
+		else {
+			_error_("transient elementary inputs not supported yet!");
+		}
+	}
+	else{
+		_error_("Cannot add input for vector type " << vector_type << " (not supported)");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Penta::InputDepthAverageAtBase{{{*/
+void  Penta::InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum){
+
+	int  step,i;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  Helem_list[NUMVERTICES];
+	IssmDouble  zeros_list[NUMVERTICES]={0.0};
+	Penta* penta=NULL;
+	Input* original_input=NULL;
+	Input* element_integrated_input=NULL;
+	Input* total_integrated_input=NULL;
+	Input* element_thickness_input=NULL;
+	Input* total_thickness_input=NULL;
+	Input* depth_averaged_input=NULL;
+
+	/*recover parameters: */
+
+	/*Are we on the base? If not, return*/
+	if(!IsOnBed()) return;
+
+	/*OK, we are on bed. Initialize global inputs as 0*/
+	total_thickness_input =new PentaP1Input(ThicknessEnum,zeros_list);
+
+	/*Now follow all the upper element from the base to the surface to integrate the input*/
+	penta=this;
+	step =0;
+	for(;;){
+
+		/*Step1: Get original input (to be depth avegaged): */
+		if (object_enum==MeshElementsEnum)
+		 original_input=(Input*)penta->inputs->GetInput(enum_type);
+		else if (object_enum==MaterialsEnum)
+		 original_input=(Input*)penta->material->inputs->GetInput(enum_type);
+		else
+		 _error_("object " << EnumToStringx(object_enum) << " not supported yet");
+		if(!original_input) _error_("could not find input with enum " << EnumToStringx(enum_type));
+
+		/*If first time, initialize total_integrated_input*/
+		if (step==0){
+			if (original_input->ObjectEnum()==PentaP1InputEnum)
+			 total_integrated_input=new PentaP1Input(average_enum_type,zeros_list);
+			else if (original_input->ObjectEnum()==ControlInputEnum)
+			 total_integrated_input=new PentaP1Input(average_enum_type,zeros_list);
+			else if (original_input->ObjectEnum()==DoubleInputEnum)
+			 total_integrated_input=new DoubleInput(average_enum_type,0.0);
+			else
+			 _error_("object " << EnumToStringx(original_input->ObjectEnum()) << " not supported yet");
+		}
+
+		/*Step2: Create element thickness input*/
+		GetVerticesCoordinates(&xyz_list[0][0],penta->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->material->inputs->AddInput((Input*)depth_averaged_input);
+	else
+	 _error_("object " << EnumToStringx(object_enum) << " not supported yet");
+}
+/*}}}*/
+/*FUNCTION Penta::InputDuplicate{{{*/
+void  Penta::InputDuplicate(int original_enum,int new_enum){
+
+	/*Call inputs method*/
+	if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
+
+}
+/*}}}*/
+/*FUNCTION Penta::InputExtrude {{{*/
+void  Penta::InputExtrude(int enum_type,int object_type){
+
+	int     i,num_inputs;
+	Penta  *penta       = NULL;
+	Input  *copy        = NULL;
+	Input **base_inputs = NULL;
+
+	/*Are we on the base, not on the surface?:*/
+	if(!IsOnBed()) return;
+
+	/*Step1: Get and Extrude original input: */
+	if (object_type==ElementEnum){
+		num_inputs=1;
+		base_inputs=xNew<Input*>(num_inputs);
+		base_inputs[0]=(Input*)this->inputs->GetInput(enum_type);
+	}
+	else if (object_type==MaterialsEnum){
+		num_inputs=1;
+		base_inputs=xNew<Input*>(num_inputs);
+		base_inputs[0]=(Input*)material->inputs->GetInput(enum_type);
+	}
+	else if (object_type==NodeEnum){
+		num_inputs=3; //only the three upper nodes
+		base_inputs=xNew<Input*>(num_inputs);
+		for(i=0;i<num_inputs;i++){
+			base_inputs[i]=(Input*)this->nodes[i]->inputs->GetInput(enum_type);
+		}
+	}
+	else{
+		_error_("object of type " << EnumToStringx(object_type) << " not supported yet");
+	}
+	for(i=0;i<num_inputs;i++){
+		if(!base_inputs[i]) _error_("could not find input with enum " << EnumToStringx(enum_type) << " in object " << EnumToStringx(object_type));
+		base_inputs[i]->Extrude();
+	}
+
+	/*Stop if there is only one layer of element*/
+	if (this->IsOnSurface()) return;
+
+	/*Step 2: this input has been extruded for this element, now follow the upper element*/
+	penta=this;
+	for(;;){
+		/* get upper Penta*/
+		penta=penta->GetUpperElement();
+		_assert_(penta->Id()!=this->id);
+
+		/*Add input of the basal element to penta->inputs*/
+		for(i=0;i<num_inputs;i++){
+			copy=(Input*)base_inputs[i]->copy();
+			if (object_type==ElementEnum){
+				penta->inputs->AddInput((Input*)copy);
+			}
+			else if(object_type==MaterialsEnum){
+				penta->material->inputs->AddInput((Input*)copy);
+			}
+			else if(object_type==NodeEnum){
+				penta->nodes[i+3]->inputs->AddInput((Input*)copy); //change only the three upper nodes
+			}
+			else{
+				_error_("object of type " << EnumToStringx(object_type) << " not supported yet");
+			}
+		}
+
+		/*Stop if we have reached the surface*/
+		if (penta->IsOnSurface()) break;
+	}
+
+	/*clean-up and return*/
+	xDelete<Input*>(base_inputs);
+}
+/*}}}*/
+/*FUNCTION Penta::InputScale{{{*/
+void  Penta::InputScale(int enum_type,IssmDouble scale_factor){
+
+	Input* input=NULL;
+
+	/*Make a copy of the original input: */
+	input=(Input*)this->inputs->GetInput(enum_type);
+	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
+
+	/*Scale: */
+	input->Scale(scale_factor);
+}
+/*}}}*/
+/*FUNCTION Penta::InputToResult{{{*/
+void  Penta::InputToResult(int enum_type,int step,IssmDouble time){
+
+	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->material->inputs->GetInput(MaterialsRheologyBEnum);
+	else if (enum_type==MaterialsRheologyZbarEnum) input=this->material->inputs->GetInput(MaterialsRheologyZEnum);
+	else input=this->inputs->GetInput(enum_type);
+	//if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found in penta->inputs"); why error out? if the requested input does not exist, we should still 
+	//try and output whatever we can instead of just failing.
+	if(!input)return;
+
+	/*If we don't find it, no big deal, just don't do the transfer. Otherwise, build a new Result 
+	 * object out of the input, with the additional step and time information: */
+	this->results->AddObject((Object*)input->SpawnResult(step,time));
+	#ifdef _HAVE_CONTROL_
+	if(input->ObjectEnum()==ControlInputEnum){
+		if(((ControlInput*)input)->gradient!=NULL) this->results->AddObject((Object*)((ControlInput*)input)->SpawnGradient(step,time));
+	}
+	#endif
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromConstant(bool value, int name);{{{*/
+void  Penta::InputUpdateFromConstant(bool constant, int name){
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new BoolInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromConstant(IssmDouble value, int name);{{{*/
+void  Penta::InputUpdateFromConstant(IssmDouble constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new DoubleInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromConstant(int value, int name);{{{*/
+void  Penta::InputUpdateFromConstant(int constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new IntInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromIoModel {{{*/
+void Penta::InputUpdateFromIoModel(int index,IoModel* iomodel){ 
+
+	/*Intermediaries*/
+	IssmInt i,j;
+	int     penta_vertex_ids[6];
+	IssmDouble  nodeinputs[6];
+	IssmDouble  cmmininputs[6];
+	IssmDouble  cmmaxinputs[6];
+
+	IssmDouble  yts;
+	bool    control_analysis;
+	int     num_control_type;
+	int     num_cm_responses;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+	if(control_analysis) iomodel->Constant(&num_cm_responses,InversionNumCostFunctionsEnum);
+
+	/*Checks if debuging*/
+	/*{{{*/
+	_assert_(iomodel->Data(MeshElementsEnum));
+	/*}}}*/
+
+	/*Recover vertices ids needed to initialize inputs*/
+	for(i=0;i<6;i++){ 
+		penta_vertex_ids[i]=reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[6*index+i]); //ids for vertices are in the elements array from Matlab
+	}
+
+	/*Control Inputs*/
+	#ifdef _HAVE_CONTROL_
+	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+		for(i=0;i<num_control_type;i++){
+			switch(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])){
+				case BalancethicknessThickeningRateEnum:
+					if (iomodel->Data(BalancethicknessThickeningRateEnum)){
+						for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(BalancethicknessThickeningRateEnum)[penta_vertex_ids[j]-1]/yts;
+						for(j=0;j<6;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<6;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case VxEnum:
+					if (iomodel->Data(VxEnum)){
+						for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(VxEnum)[penta_vertex_ids[j]-1]/yts;
+						for(j=0;j<6;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<6;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(VxEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case VyEnum:
+					if (iomodel->Data(VyEnum)){
+						for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(VyEnum)[penta_vertex_ids[j]-1]/yts;
+						for(j=0;j<6;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						for(j=0;j<6;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
+						this->inputs->AddInput(new ControlInput(VyEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case FrictionCoefficientEnum:
+					if (iomodel->Data(FrictionCoefficientEnum)){
+						for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(FrictionCoefficientEnum)[penta_vertex_ids[j]-1];
+						for(j=0;j<6;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i];
+						for(j=0;j<6;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i];
+						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+					}
+					break;
+				case MaterialsRheologyBbarEnum:
+				case MaterialsRheologyZbarEnum:
+					/*Material will take care of it*/ break;
+				default:
+					_error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
+			}
+		}
+	}
+	#endif
+
+	//Need to know the type of approximation for this element
+	if(iomodel->Data(FlowequationElementEquationEnum)){
+		if (iomodel->Data(FlowequationElementEquationEnum)[index]==MacAyealApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,MacAyealApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==PattynApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,PattynApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==MacAyealPattynApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,MacAyealPattynApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==HutterApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,HutterApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==L1L2ApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,L1L2ApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==StokesApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,StokesApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==MacAyealStokesApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,MacAyealStokesApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==PattynStokesApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,PattynStokesApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==NoneApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,NoneApproximationEnum));
+		}
+		else{
+			_error_("Approximation type " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(FlowequationElementEquationEnum)[index])) << " not supported yet");
+		}
+	}
+
+	/*DatasetInputs*/
+	if (control_analysis && iomodel->Data(InversionCostFunctionsCoefficientsEnum)) {
+
+		/*Create inputs and add to DataSetInput*/
+		DatasetInput* datasetinput=new DatasetInput(InversionCostFunctionsCoefficientsEnum);
+		for(i=0;i<num_cm_responses;i++){
+			for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(InversionCostFunctionsCoefficientsEnum)[(penta_vertex_ids[j]-1)*num_cm_responses+i];
+			datasetinput->inputs->AddObject(new PentaP1Input(InversionCostFunctionsCoefficientsEnum,nodeinputs));
+		}
+
+		/*Add datasetinput to element inputs*/
+		this->inputs->AddInput(datasetinput);
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolution {{{*/
+void  Penta::InputUpdateFromSolution(IssmDouble* solution){
+
+	int analysis_type;
+
+	/*retreive parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Just branch to the correct InputUpdateFromSolution generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+	#ifdef _HAVE_DIAGNOSTIC_
+	case DiagnosticHorizAnalysisEnum:
+		InputUpdateFromSolutionDiagnosticHoriz( solution);
+		break;
+	case DiagnosticHutterAnalysisEnum:
+		InputUpdateFromSolutionDiagnosticHutter( solution);
+		break;
+	case DiagnosticVertAnalysisEnum:
+		InputUpdateFromSolutionDiagnosticVert( solution);
+		break;
+	#endif
+	#ifdef _HAVE_CONTROL_
+	case AdjointHorizAnalysisEnum:
+		int approximation;
+		inputs->GetInputValue(&approximation,ApproximationEnum);
+		if(approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
+			InputUpdateFromSolutionAdjointStokes( solution);
+		}
+		else{
+			InputUpdateFromSolutionAdjointHoriz( solution);
+		}
+		break;
+	#endif
+	#ifdef _HAVE_THERMAL_
+	case ThermalAnalysisEnum:
+		InputUpdateFromSolutionThermal( solution);
+		break;
+	case EnthalpyAnalysisEnum:
+		InputUpdateFromSolutionEnthalpy( solution);
+		break;
+	case MeltingAnalysisEnum:
+		InputUpdateFromSolutionOneDof(solution,BasalforcingsMeltingRateEnum);
+		break;
+	#endif
+	case BedSlopeXAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,BedSlopeXEnum);
+		break;
+	case BedSlopeYAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,BedSlopeYEnum);
+		break;
+	case SurfaceSlopeXAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,SurfaceSlopeXEnum);
+		break;
+	case SurfaceSlopeYAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,SurfaceSlopeYEnum);
+		break;
+	case PrognosticAnalysisEnum:
+		InputUpdateFromSolutionPrognostic(solution);
+		break;
+	#ifdef _HAVE_BALANCED_
+	case BalancethicknessAnalysisEnum:
+		InputUpdateFromSolutionOneDofCollapsed(solution,ThicknessEnum);
+		break;
+	#endif
+	default: 
+		_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionPrognostic{{{*/
+void  Penta::InputUpdateFromSolutionPrognostic(IssmDouble* solution){
+
+	const int  numdof   = NDOF1*NUMVERTICES;
+	const int  numdof2d = NDOF1*NUMVERTICES2D;
+
+	int    i,hydroadjustment;
+	int*   doflist = NULL;
+	IssmDouble rho_ice,rho_water,minthickness;
+	IssmDouble newthickness[numdof];
+	IssmDouble newbed[numdof];
+	IssmDouble newsurface[numdof];
+	IssmDouble oldbed[NUMVERTICES];
+	IssmDouble oldsurface[NUMVERTICES];
+	IssmDouble oldthickness[NUMVERTICES];
+	Penta  *penta   = NULL;
+
+	/*If not on bed, return*/
+	if (!IsOnBed()) return;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector and extrude it */
+	this->parameters->FindParam(&minthickness,PrognosticMinThicknessEnum);
+	for(i=0;i<numdof2d;i++){
+		newthickness[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(newthickness[i])) _error_("NaN found in solution vector");
+		/*Constrain thickness to be at least 1m*/
+		if(newthickness[i]<minthickness) newthickness[i]=minthickness;
+		newthickness[i+numdof2d]=newthickness[i];
+	}
+
+	/*Get previous bed, thickness and surface*/
+	GetInputListOnVertices(&oldbed[0],BedEnum);
+	GetInputListOnVertices(&oldsurface[0],SurfaceEnum);
+	GetInputListOnVertices(&oldthickness[0],ThicknessEnum);
+
+	/*Fing PrognosticHydrostaticAdjustment to figure out how to update the geometry:*/
+	this->parameters->FindParam(&hydroadjustment,PrognosticHydrostaticAdjustmentEnum);
+
+	/*recover material parameters: */
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	for(i=0;i<numdof;i++) {
+		/*If shelf: hydrostatic equilibrium*/
+		if (this->nodes[i]->IsGrounded()){
+			newsurface[i]=oldbed[i]+newthickness[i]; //surface = oldbed + newthickness
+			newbed[i]=oldbed[i];               //same bed: do nothing
+		}
+		else{ //so it is an ice shelf
+			if(hydroadjustment==AbsoluteEnum){
+				newsurface[i]=newthickness[i]*(1-rho_ice/rho_water);
+				newbed[i]=newthickness[i]*(-rho_ice/rho_water);
+			}
+			else if(hydroadjustment==IncrementalEnum){
+				newsurface[i]=oldsurface[i]+(1.0-rho_ice/rho_water)*(newthickness[i]-oldthickness[i]); //surface = oldsurface + (1-di) * dH 
+				newbed[i]=oldbed[i]-rho_ice/rho_water*(newthickness[i]-oldthickness[i]); //bed = oldbed + di * dH
+			}
+			else _error_("Hydrostatic adjustment " << hydroadjustment << " (" << EnumToStringx(hydroadjustment) << ") not supported yet");
+		}
+	}
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	for(;;){
+		/*Add input to the element: */
+		penta->inputs->AddInput(new PentaP1Input(ThicknessEnum,newthickness));
+		penta->inputs->AddInput(new PentaP1Input(SurfaceEnum,newsurface));
+		penta->inputs->AddInput(new PentaP1Input(BedEnum,newbed));
+
+		/*Stop if we have reached the surface*/
+		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
+	}
+	
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionOneDof{{{*/
+void  Penta::InputUpdateFromSolutionOneDof(IssmDouble* solution,int enum_type){
+
+	const int numdof = NDOF1*NUMVERTICES;
+
+	IssmDouble values[numdof];
+	int*   doflist=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new PentaP1Input(enum_type,values));
+	
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionOneDofCollpased{{{*/
+void  Penta::InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int enum_type){
+
+	const int  numdof   = NDOF1*NUMVERTICES;
+	const int  numdof2d = NDOF1*NUMVERTICES2D;
+
+	IssmDouble  values[numdof];
+	int*    doflist = NULL;
+	Penta  *penta   = NULL;
+
+	/*If not on bed, return*/
+	if (!IsOnBed()) return;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector and extrude it */
+	for(int i=0;i<numdof2d;i++){
+		values[i]         =solution[doflist[i]];
+		values[i+numdof2d]=values[i];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	for(;;){
+		/*Add input to the element: */
+		penta->inputs->AddInput(new PentaP1Input(enum_type,values));
+
+		/*Stop if we have reached the surface*/
+		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
+	}
+	
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromVector(IssmDouble* vector, int name, int type);{{{*/
+void  Penta::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+
+	/*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*/
+				if (name==MaterialsRheologyZEnum || name==MaterialsRheologyZbarEnum){
+					material->inputs->AddInput(new PentaP1Input(name,values));
+				}
+				else{
+					this->inputs->AddInput(new PentaP1Input(name,values));
+				}
+				return;
+				break;
+			}
+
+		default:
+
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromVector(int* vector, int name, int type);{{{*/
+void  Penta::InputUpdateFromVector(int* vector, int name, int type){
+	_error_("not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromVector(bool* vector, int name, int type);{{{*/
+void  Penta::InputUpdateFromVector(bool* vector, int name, int type){
+	_error_("not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Penta::IsOnBed{{{*/
+bool Penta::IsOnBed(void){
+
+	bool onbed;
+	inputs->GetInputValue(&onbed,MeshElementonbedEnum);
+	return onbed;
+}
+/*}}}*/
+/*FUNCTION Penta::IsInput{{{*/
+bool Penta::IsInput(int name){
+	if (
+				name==ThicknessEnum ||
+				name==SurfaceEnum ||
+				name==BedEnum ||
+				name==SurfaceSlopeXEnum ||
+				name==SurfaceSlopeYEnum ||
+				name==SurfaceforcingsMassBalanceEnum ||
+				name==BasalforcingsMeltingRateEnum ||
+				name==BasalforcingsGeothermalfluxEnum ||
+				name==SurfaceAreaEnum||
+				name==PressureEnum ||
+				name==VxEnum ||
+				name==VyEnum ||
+				name==VzEnum ||
+				name==VxMeshEnum ||
+				name==VyMeshEnum ||
+				name==VzMeshEnum ||
+				name==InversionVxObsEnum ||
+				name==InversionVyObsEnum ||
+				name==InversionVzObsEnum ||
+				name==TemperatureEnum ||
+				name==EnthalpyEnum ||
+				name==EnthalpyPicardEnum ||
+				name==WaterfractionEnum||
+				name==FrictionCoefficientEnum ||
+				name==GradientEnum ||
+				name==OldGradientEnum  ||
+				name==ConvergedEnum || 
+				name==QmuVxEnum ||
+				name==QmuVyEnum ||
+				name==QmuVzEnum ||
+				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 (reCast<bool,IssmDouble>(flags[nodes[i]->Sid()])){
+			shelf=true;
+			break;
+		}
+	}
+	return shelf;
+}
+/*}}}*/
+/*FUNCTION Penta::IsOnSurface{{{*/
+bool Penta::IsOnSurface(void){
+
+	bool onsurface;
+	inputs->GetInputValue(&onsurface,MeshElementonsurfaceEnum);
+	return onsurface;
+}
+/*}}}*/
+/*FUNCTION Penta::IsOnWater {{{*/
+bool   Penta::IsOnWater(){
+
+	bool onwater;
+	inputs->GetInputValue(&onwater,MaskElementonwaterEnum);
+	return onwater;
+}
+/*}}}*/
+/*FUNCTION Penta::ListResultsInfo{{{*/
+void Penta::ListResultsInfo(int** in_resultsenums,int** in_resultssizes,IssmDouble** in_resultstimes,int** in_resultssteps,int* in_num_results){
+
+	/*Intermediaries*/
+	int     i;
+	int     numberofresults = 0;
+	int     *resultsenums   = NULL;
+	int     *resultssizes   = NULL;
+	IssmDouble  *resultstimes   = NULL;
+	int     *resultssteps   = NULL;
+
+	/*Checks*/
+	_assert_(in_num_results);
+
+	/*Count number of results*/
+	for(i=0;i<this->results->Size();i++){
+		ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+		numberofresults++;
+	}
+
+	if(numberofresults){
+
+		/*Allocate output*/
+		resultsenums=xNew<int>(numberofresults);
+		resultssizes=xNew<int>(numberofresults);
+		resultstimes=xNew<IssmDouble>(numberofresults);
+		resultssteps=xNew<int>(numberofresults);
+
+		/*populate enums*/
+		for(i=0;i<this->results->Size();i++){
+			ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(i);
+			resultsenums[i]=elementresult->InstanceEnum();
+			resultstimes[i]=elementresult->GetTime();
+			resultssteps[i]=elementresult->GetStep();
+			if(elementresult->ObjectEnum()==PentaP1ElementResultEnum){
+				resultssizes[i]=P1Enum;
+			}
+			else{
+				resultssizes[i]=P0Enum;
+			}
+		}
+	}
+
+	/*Assign output pointers:*/
+	*in_num_results=numberofresults;
+	*in_resultsenums=resultsenums;
+	*in_resultssizes=resultssizes;
+	*in_resultstimes=resultstimes;
+	*in_resultssteps=resultssteps;
+
+}/*}}}*/
+/*FUNCTION Penta::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(reCast<bool,IssmDouble>(old_floating_ice[nodes[i]->Sid()])){
+			if(b[i]<=ba[i]){ 
+				b[i]=ba[i];
+				s[i]=b[i]+h[i];
+				nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,false));
+				nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,true));
+			}
+		}
+		/*Ice sheet: if hydrostatic bed above bathymetry, ice sheet starts to unground, elso do nothing */
+		/*Change only if AgressiveMigration or if the ice sheet is in contact with the ocean*/
+		else{
+			bed_hydro=-density*h[i];
+			if (bed_hydro>ba[i]){
+				/*Unground only if the element is connected to the ice shelf*/
+				if(migration_style==AgressiveMigrationEnum){
+					s[i]=(1-density)*h[i];
+					b[i]=-density*h[i];
+					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,true));
+					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,false));
+				}
+				else if(migration_style==SoftMigrationEnum && reCast<int,IssmDouble>(sheet_ungrounding[nodes[i]->Sid()])){
+					s[i]=(1-density)*h[i];
+					b[i]=-density*h[i];
+					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,true));
+					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,false));
+				}
+			}
+		}
+	}
+
+	/*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<IssmDouble>* 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){
+
+	_error_("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 material*/
+	tria->material=NULL;
+	tria->material=(Material*)this->material->copy();
+	delete tria->material->inputs;
+	tria->material->inputs=(Inputs*)this->material->inputs->SpawnTriaInputs(indices);
+
+	/*recover nodes, material and matpar: */
+	tria->nodes=(Node**)tria->hnodes[analysis_counter]->deliverp();
+	tria->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->material; delete tria;
+		return S;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		S=tria->SurfaceArea();
+		delete tria->material; delete tria;
+		return S;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceNormal {{{*/
+void Penta::SurfaceNormal(IssmDouble* surface_normal, IssmDouble xyz_list[3][3]){
+
+	int    i;
+	IssmDouble v13[3],v23[3];
+	IssmDouble normal[3];
+	IssmDouble normal_norm;
+
+	for (i=0;i<3;i++){
+		v13[i]=xyz_list[0][i]-xyz_list[2][i];
+		v23[i]=xyz_list[1][i]-xyz_list[2][i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+
+	normal_norm=sqrt( pow(normal[0],2)+pow(normal[1],2)+pow(normal[2],2) );
+
+	*(surface_normal)=normal[0]/normal_norm;
+	*(surface_normal+1)=normal[1]/normal_norm;
+	*(surface_normal+2)=normal[2]/normal_norm;
+}
+/*}}}*/
+/*FUNCTION Penta::TimeAdapt{{{*/
+IssmDouble  Penta::TimeAdapt(void){
+
+	int    i;
+	IssmDouble C,dx,dy,dz,dt;
+	IssmDouble maxabsvx,maxabsvy,maxabsvz;
+	IssmDouble maxx,minx,maxy,miny,maxz,minz;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*get CFL coefficient:*/
+	this->parameters->FindParam(&C,TimesteppingCflCoefficientEnum);
+
+	/*Get for Vx and Vy, the max of abs value: */
+	this->MaxAbsVx(&maxabsvx,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]=reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[6*index+i]); //ids for vertices are in the elements array from Matlab
+
+	/*Recover nodes ids needed to initialize the node hook.*/
+	for(i=0;i<6;i++){ 
+		//go recover node ids, needed to initialize the node hook.
+		//WARNING: We assume P1 elements here!!!!!
+		penta_node_ids[i]=iomodel->nodecounter+reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[6*index+i]); //ids for vertices are in the elements array from Matlab
+	}
+
+	/*hooks: */
+	this->SetHookNodes(penta_node_ids,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 _error_("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<IssmDouble>* 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 (reCast<bool,IssmDouble>(vertices_potentially_ungrounding[nodes[i]->Sid()])){
+			vec_nodes_on_iceshelf->SetValue(nodes[i]->Sid(),1,INS_VAL);
+		
+			/*If node was not on ice shelf, we flipped*/
+			if(nodes_on_iceshelf[nodes[i]->Sid()]==0){
+				nflipped++;
+			}
+		}
+	}
+	return nflipped;
+}
+/*}}}*/
+/*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);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		GetPhi(&phi, &epsilon[0], viscosity);
+		
+
+		viscousheating[iv]=phi*thickness;
+	}
+
+	/*Create PentaVertex input, which will hold the basal friction:*/
+	this->inputs->AddInput(new PentaP1Input(ViscousHeatingEnum,&viscousheating[0]));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::SmearFunction {{{*/
+void  Penta::SmearFunction(Vector<IssmDouble>* smearedvector,IssmDouble (*WeightFunction)(IssmDouble distance,IssmDouble radius),IssmDouble radius){
+	_error_("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->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return mass_flux;
+}
+/*}}}*/
+/*FUNCTION Penta::MaxAbsVx{{{*/
+void  Penta::MaxAbsVx(IssmDouble* pmaxabsvx, 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->material->GetBbar();
+			break;
+		case MaterialsRheologyZbarEnum:
+			*presponse=this->material->GetZbar();
+			break;
+		case VelEnum:
+			{
+
+				/*Get input:*/
+				IssmDouble vel;
+				Input* vel_input;
+
+				vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+				vel_input->GetInputAverage(&vel);
+
+				/*process units if requested: */
+				if(process_units) vel=UnitConversion(vel,IuToExtEnum,VelEnum);
+
+				/*Assign output pointers:*/
+				*presponse=vel;
+			}
+			break;
+		default:  
+			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Penta::TotalSmb {{{*/
+IssmDouble Penta::TotalSmb(void){
+
+	/*The smb[Gt yr-1] of one element is area[m2] * smb [ m ice yr^-1] * rho_ice [kg m-3] / 1e+10^12 */
+	IssmDouble base,smb,rho_ice;
+	IssmDouble Total_Smb=0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetRhoIce();
+
+	if(IsOnWater() || !IsOnSurface()) return 0.;
+	
+	GetVerticesCoordinates(&xyz_list[0][0], 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(reCast<bool,IssmDouble>(dt)) D_scalar_conduct=D_scalar_conduct*dt;
+
+		D[0][0]=D_scalar_conduct; D[0][1]=0; D[0][2]=0;
+		D[1][0]=0; D[1][1]=D_scalar_conduct; D[1][2]=0;
+		D[2][0]=0; D[2][1]=0; D[2][2]=D_scalar_conduct;
+
+		TripleMultiply(&B_conduct[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&B_conduct[0][0],3,numdof,0,
+					&Ke->values[0],1);
+
+		/*Advection: */
+		GetBAdvec(&B_advec[0][0],&xyz_list[0][0],gauss); 
+		GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
+
+		vx_input->GetInputValue(&u, gauss); vxm_input->GetInputValue(&um,gauss); vx=u-um; 
+		vy_input->GetInputValue(&v, gauss); vym_input->GetInputValue(&vm,gauss); vy=v-vm; 
+		vz_input->GetInputValue(&w, gauss); vzm_input->GetInputValue(&wm,gauss); vz=w-wm;
+
+		D_scalar_advec=gauss->weight*Jdet;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar_advec=D_scalar_advec*dt;
+
+		D[0][0]=D_scalar_advec*vx;D[0][1]=0;                D[0][2]=0;
+		D[1][0]=0;                D[1][1]=D_scalar_advec*vy;D[1][2]=0;
+		D[2][0]=0;                D[2][1]=0;                D[2][2]=D_scalar_advec*vz;
+
+		TripleMultiply(&B_advec[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&Bprime_advec[0][0],3,numdof,0,
+					&Ke->values[0],1);
+
+		/*Transient: */
+		if(reCast<bool,IssmDouble>(dt)){
+			GetNodalFunctionsP1(&L[0], gauss);
+			D_scalar_trans=gauss->weight*Jdet;
+			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(reCast<bool,IssmDouble>(dt)) D_scalar_stab=D_scalar_stab*dt;
+			for(i=0;i<3;i++) for(j=0;j<3;j++) K[i][j] = D_scalar_stab*K[i][j];
+
+			GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
+
+			TripleMultiply(&Bprime_advec[0][0],3,numdof,1,
+						&K[0][0],3,3,0,
+						&Bprime_advec[0][0],3,numdof,0,
+						&Ke->values[0],1);
+		}
+		else if(stabilization==2){
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+			tau_parameter=GetStabilizationParameter(u-um,v-vm,w-wm,diameter,kappa);
+
+			for(i=0;i<numdof;i++){
+				for(j=0;j<numdof;j++){
+					Ke->values[i*numdof+j]+=tau_parameter*D_scalar_advec*
+					  ((u-um)*dbasis[0][i]+(v-vm)*dbasis[1][i]+(w-wm)*dbasis[2][i])*((u-um)*dbasis[0][j]+(v-vm)*dbasis[1][j]+(w-wm)*dbasis[2][j]);
+				}
+			}
+			if(reCast<bool,IssmDouble>(dt)){
+				for(i=0;i<numdof;i++){
+					for(j=0;j<numdof;j++){
+						Ke->values[i*numdof+j]+=tau_parameter*D_scalar_trans*L[j]*((u-um)*dbasis[0][i]+(v-vm)*dbasis[1][i]+(w-wm)*dbasis[2][i]);
+					}
+				}
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixEnthalpyShelf {{{*/
+ElementMatrix* Penta::CreateKMatrixEnthalpyShelf(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int       i,j,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(reCast<bool,IssmDouble>(dt)) D_scalar=dt*D_scalar;
+
+		TripleMultiply(&basis[0],numdof,1,0,
+					&D_scalar,1,1,0,
+					&basis[0],1,numdof,0,
+					&Ke->values[0],1);
+	}
+	
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixMelting {{{*/
+ElementMatrix* Penta::CreateKMatrixMelting(void){
+
+	if (!IsOnBed()) return NULL;
+
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixMelting();
+
+	delete tria->material; delete tria;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixThermal {{{*/
+ElementMatrix* Penta::CreateKMatrixThermal(void){
+	
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixThermalVolume();
+	ElementMatrix* Ke2=CreateKMatrixThermalShelf();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+	
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixThermalVolume {{{*/
+ElementMatrix* Penta::CreateKMatrixThermalVolume(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        stabilization;
+	int        i,j,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(reCast<bool,IssmDouble>(dt)) D_scalar_conduct=D_scalar_conduct*dt;
+
+		D[0][0]=D_scalar_conduct; D[0][1]=0; D[0][2]=0;
+		D[1][0]=0; D[1][1]=D_scalar_conduct; D[1][2]=0;
+		D[2][0]=0; D[2][1]=0; D[2][2]=D_scalar_conduct;
+
+		TripleMultiply(&B_conduct[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&B_conduct[0][0],3,numdof,0,
+					&Ke->values[0],1);
+
+		/*Advection: */
+
+		GetBAdvec(&B_advec[0][0],&xyz_list[0][0],gauss); 
+		GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
+
+		vx_input->GetInputValue(&u, gauss); vxm_input->GetInputValue(&um,gauss); vx=u-um;
+		vy_input->GetInputValue(&v, gauss); vym_input->GetInputValue(&vm,gauss); vy=v-vm;
+		vz_input->GetInputValue(&w, gauss); vzm_input->GetInputValue(&wm,gauss); vz=w-wm;
+
+		D_scalar_advec=gauss->weight*Jdet;
+		if(reCast<bool,IssmDouble>(dt)) D_scalar_advec=D_scalar_advec*dt;
+
+		D[0][0]=D_scalar_advec*vx;    D[0][1]=0;                    D[0][2]=0;
+		D[1][0]=0;                    D[1][1]=D_scalar_advec*vy;    D[1][2]=0;
+		D[2][0]=0;                    D[2][1]=0;                    D[2][2]=D_scalar_advec*vz;
+
+		TripleMultiply(&B_advec[0][0],3,numdof,1,
+					&D[0][0],3,3,0,
+					&Bprime_advec[0][0],3,numdof,0,
+					&Ke->values[0],1);
+
+		/*Transient: */
+		if(reCast<bool,IssmDouble>(dt)){
+			GetNodalFunctionsP1(&L[0], gauss);
+			D_scalar_trans=gauss->weight*Jdet;
+			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(reCast<bool,IssmDouble>(dt)) D_scalar_stab=D_scalar_stab*dt;
+			for(i=0;i<3;i++) for(j=0;j<3;j++) K[i][j] = D_scalar_stab*K[i][j];
+
+			GetBprimeAdvec(&Bprime_advec[0][0],&xyz_list[0][0],gauss); 
+
+			TripleMultiply(&Bprime_advec[0][0],3,numdof,1,
+						&K[0][0],3,3,0,
+						&Bprime_advec[0][0],3,numdof,0,
+						&Ke->values[0],1);
+		}
+		else if(stabilization==2){
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+			tau_parameter=GetStabilizationParameter(u-um,v-vm,w-wm,diameter,kappa);
+
+			for(i=0;i<numdof;i++){
+				for(j=0;j<numdof;j++){
+					Ke->values[i*numdof+j]+=tau_parameter*D_scalar_advec*
+					  ((u-um)*dbasis[0][i]+(v-vm)*dbasis[1][i]+(w-wm)*dbasis[2][i])*((u-um)*dbasis[0][j]+(v-vm)*dbasis[1][j]+(w-wm)*dbasis[2][j]);
+				}
+			}
+			if(reCast<bool,IssmDouble>(dt)){
+				for(i=0;i<numdof;i++){
+					for(j=0;j<numdof;j++){
+						Ke->values[i*numdof+j]+=tau_parameter*D_scalar_trans*L[j]*((u-um)*dbasis[0][i]+(v-vm)*dbasis[1][i]+(w-wm)*dbasis[2][i]);
+					}
+				}
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixThermalShelf {{{*/
+ElementMatrix* Penta::CreateKMatrixThermalShelf(void){
+
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int       i,j,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(reCast<bool,IssmDouble>(dt)) D_scalar=dt*D_scalar;
+
+		TripleMultiply(&basis[0],numdof,1,0,
+					&D_scalar,1,1,0,
+					&basis[0],1,numdof,0,
+					&Ke->values[0],1);
+	}
+	
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorEnthalpy {{{*/
+ElementVector* Penta::CreatePVectorEnthalpy(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorEnthalpyVolume();
+	ElementVector* pe2=CreatePVectorEnthalpySheet();
+	ElementVector* pe3=CreatePVectorEnthalpyShelf();
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorEnthalpyVolume {{{*/
+ElementVector* Penta::CreatePVectorEnthalpyVolume(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries*/
+	int    i,j,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(reCast<bool,IssmDouble>(dt)){
+		enthalpy_input=inputs->GetInput(EnthalpyEnum); _assert_(enthalpy_input);
+	}
+	if (stabilization==2){
+		diameter=MinEdgeLength(xyz_list);
+		enthalpypicard_input=inputs->GetInput(EnthalpyPicardEnum); _assert_(enthalpypicard_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,3);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(&L[0], gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		GetPhi(&phi, &epsilon[0], viscosity);
+
+		scalar_def=phi/rho_ice*Jdet*gauss->weight;
+		if(reCast<bool,IssmDouble>(dt)) scalar_def=scalar_def*dt;
+
+		for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_def*L[i];
+
+		/* Build transient now */
+		if(reCast<bool,IssmDouble>(dt)){
+			enthalpy_input->GetInputValue(&enthalpy, gauss);
+			scalar_transient=enthalpy*Jdet*gauss->weight;
+			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_transient*L[i];
+		}
+
+		if(stabilization==2){
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+
+			vx_input->GetInputValue(&u, gauss);
+			vy_input->GetInputValue(&v, gauss);
+			vz_input->GetInputValue(&w, gauss);
+			pressure_input->GetInputValue(&pressure, gauss);
+			enthalpypicard_input->GetInputValue(&enthalpypicard, gauss);
+			kappa=matpar->GetEnthalpyDiffusionParameter(enthalpy,pressure);
+			tau_parameter=GetStabilizationParameter(u,v,w,diameter,kappa);
+
+			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_def*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
+			if(reCast<bool,IssmDouble>(dt)){
+				for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_transient*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorEnthalpyShelf {{{*/
+ElementVector* Penta::CreatePVectorEnthalpyShelf(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j,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(reCast<bool,IssmDouble>(dt)) scalar_ocean=dt*scalar_ocean;
+
+		for(i=0;i<numdof;i++) pe->values[i]+=scalar_ocean*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorEnthalpySheet {{{*/
+ElementVector* Penta::CreatePVectorEnthalpySheet(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j,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(reCast<bool,IssmDouble>(dt)) scalar=dt*scalar;
+
+			for(i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
+//		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	delete gaussup;
+	delete friction;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorMelting {{{*/
+ElementVector* Penta::CreatePVectorMelting(void){
+	return NULL;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorThermal {{{*/
+ElementVector* Penta::CreatePVectorThermal(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorThermalVolume();
+	ElementVector* pe2=CreatePVectorThermalSheet();
+	ElementVector* pe3=CreatePVectorThermalShelf();
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorThermalVolume {{{*/
+ElementVector* Penta::CreatePVectorThermalVolume(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries*/
+	int    i,j,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 (reCast<bool,IssmDouble>(dt)) temperature_input=inputs->GetInput(TemperatureEnum); _assert_(inputs);
+	if (stabilization==2) diameter=MinEdgeLength(xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(2,3);
+	for (ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(&L[0], gauss);
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		GetPhi(&phi, &epsilon[0], viscosity);
+
+		scalar_def=phi/(rho_ice*heatcapacity)*Jdet*gauss->weight;
+		if(reCast<bool,IssmDouble>(dt)) scalar_def=scalar_def*dt;
+
+		for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_def*L[i];
+
+		/* Build transient now */
+		if(reCast<bool,IssmDouble>(dt)){
+			temperature_input->GetInputValue(&temperature, gauss);
+			scalar_transient=temperature*Jdet*gauss->weight;
+			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=scalar_transient*L[i];
+		}
+
+		if(stabilization==2){
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
+
+			vx_input->GetInputValue(&u, gauss);
+			vy_input->GetInputValue(&v, gauss);
+			vz_input->GetInputValue(&w, gauss);
+
+			tau_parameter=GetStabilizationParameter(u,v,w,diameter,kappa);
+
+			for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_def*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
+			if(reCast<bool,IssmDouble>(dt)){
+				for(i=0;i<NUMVERTICES;i++)  pe->values[i]+=tau_parameter*scalar_transient*(u*dbasis[0][i]+v*dbasis[1][i]+w*dbasis[2][i]);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorThermalShelf {{{*/
+ElementVector* Penta::CreatePVectorThermalShelf(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j,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(reCast<bool,IssmDouble>(dt)) scalar_ocean=dt*scalar_ocean;
+
+		for(i=0;i<numdof;i++) pe->values[i]+=scalar_ocean*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorThermalSheet {{{*/
+ElementVector* Penta::CreatePVectorThermalSheet(void){
+
+	/*Constants*/
+	const int  numdof=NUMVERTICES*NDOF1;
+
+	/*Intermediaries */
+	int        i,j,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(reCast<bool,IssmDouble>(dt)) scalar=dt*scalar;
+
+			for(i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsThermal{{{*/
+void  Penta::GetSolutionFromInputsThermal(Vector<IssmDouble>* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int         i;
+	int        *doflist = NULL;
+	IssmDouble  values[numdof];
+	IssmDouble  temp;
+	GaussPenta *gauss = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* t_input=inputs->GetInput(TemperatureEnum); _assert_(t_input);
+
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover temperature*/
+		gauss->GaussVertex(i);
+		t_input->GetInputValue(&temp,gauss);
+		values[i]=temp;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsEnthalpy{{{*/
+void  Penta::GetSolutionFromInputsEnthalpy(Vector<IssmDouble>* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	IssmDouble       values[numdof];
+	IssmDouble       enthalpy;
+	GaussPenta   *gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* h_input=inputs->GetInput(EnthalpyEnum); _assert_(h_input);
+
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover temperature*/
+		gauss->GaussVertex(i);
+		h_input->GetInputValue(&enthalpy,gauss);
+		values[i]=enthalpy;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionThermal {{{*/
+void  Penta::InputUpdateFromSolutionThermal(IssmDouble* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	bool   converged;
+	int    i,rheology_law;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble values[numdof];
+	IssmDouble B[numdof];
+	IssmDouble B_average,s_average;
+	int*   doflist=NULL;
+	//IssmDouble pressure[numdof];
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		//GetInputListOnVertices(&pressure[0],PressureEnum);
+		//if(values[i]>matpar->TMeltingPoint(pressure[i])) values[i]=matpar->TMeltingPoint(pressure[i]);
+		//if(values[i]<matpar->TMeltingPoint(pressure[i])-50) values[i]=matpar->TMeltingPoint(pressure[i])-50;
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+		//if(values[i]<0)      _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->material->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				break;
+			case ArrheniusEnum:
+				surface_input->GetInputAverage(&s_average);
+				B_average=Arrhenius((values[0]+values[1]+values[2]+values[3]+values[4]+values[5])/6.0,
+							s_average-((xyz_list[0][2]+xyz_list[1][2]+xyz_list[2][2]+xyz_list[3][2]+xyz_list[4][2]+xyz_list[5][2])/6.0),
+							material->GetN());
+				for(i=0;i<numdof;i++) B[i]=B_average;
+				this->material->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				break;
+			default:
+				_error_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
+
+		}
+	}
+	else{
+		this->inputs->AddInput(new PentaP1Input(TemperaturePicardEnum,values));
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionEnthalpy {{{*/
+void  Penta::InputUpdateFromSolutionEnthalpy(IssmDouble* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	bool   converged=false;
+	int    i,rheology_law;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble values[numdof];
+	IssmDouble pressure[NUMVERTICES];
+	IssmDouble temperatures[numdof];
+	IssmDouble waterfraction[numdof];
+	IssmDouble B[numdof];
+	IssmDouble B_average,s_average;
+	int*   doflist=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], 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) _error_("Negative water fraction found in solution vector");
+			//if(waterfraction[i]>1) _error_("Water fraction >1 found in solution vector");
+		}
+			
+		this->inputs->AddInput(new PentaP1Input(EnthalpyEnum,values));
+		this->inputs->AddInput(new PentaP1Input(WaterfractionEnum,waterfraction));
+		this->inputs->AddInput(new PentaP1Input(TemperatureEnum,temperatures));
+
+		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
+		 * otherwise the rheology could be negative*/
+		this->parameters->FindParam(&rheology_law,MaterialsRheologyLawEnum);
+		switch(rheology_law){
+			case NoneEnum:
+				/*Do nothing: B is not temperature dependent*/
+				break;
+			case PatersonEnum:
+				B_average=Paterson((temperatures[0]+temperatures[1]+temperatures[2]+temperatures[3]+temperatures[4]+temperatures[5])/6.0);
+				for(i=0;i<numdof;i++) B[i]=B_average;
+				this->material->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				break;
+			case ArrheniusEnum:
+				surface_input->GetInputAverage(&s_average);
+				B_average=Arrhenius((temperatures[0]+temperatures[1]+temperatures[2]+temperatures[3]+temperatures[4]+temperatures[5])/6.0,
+							s_average-((xyz_list[0][2]+xyz_list[1][2]+xyz_list[2][2]+xyz_list[3][2]+xyz_list[4][2]+xyz_list[5][2])/6.0),
+							material->GetN());
+				for(i=0;i<numdof;i++) B[i]=B_average;
+				this->material->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				break;
+			default:
+				_error_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
+
+		}
+	}
+	else{
+		this->inputs->AddInput(new PentaP1Input(EnthalpyPicardEnum,values));
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_CONTROL_
+/*FUNCTION Penta::ControlInputGetGradient{{{*/
+void Penta::ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){
+
+	int doflist1[NUMVERTICES];
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		if(!IsOnBed()) return;
+		input=(Input*)material->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else if(enum_type==MaterialsRheologyZbarEnum){
+		if(!IsOnBed()) return;
+		input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum);
+	}
+		
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&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*)material->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else if(enum_type==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	((ControlInput*)input)->ScaleGradient(scale);
+}/*}}}*/
+/*FUNCTION Penta::ControlInputSetGradient{{{*/
+void Penta::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){
+
+	int    doflist1[NUMVERTICES];
+	IssmDouble grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)material->inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else if(enum_type==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&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:
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixAdjointMacAyeal2d{{{*/
+ElementMatrix* Penta::CreateKMatrixAdjointMacAyeal2d(void){
+
+	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
+	  bedrock, in which case we spawn a tria element using the 3 first nodes, and use it to build 
+	  the stiffness matrix. */
+	if (!IsOnBed()) return NULL;
+
+	/*Depth average some fields*/
+	switch(this->material->ObjectEnum()){
+		case MaticeEnum:
+			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+			break;
+		case MatdamageiceEnum:
+			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+			this->InputDepthAverageAtBase(MaterialsRheologyZEnum,MaterialsRheologyZbarEnum,MaterialsEnum);
+			break;
+		default:
+			_error_("material "<<EnumToStringx(this->material->ObjectEnum())<<" not supported");
+	}
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixAdjointMacAyeal();
+	delete tria->material; delete tria;
+
+	/*Delete averaged fields*/
+	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+	this->material->inputs->DeleteInput(MaterialsRheologyZbarEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixAdjointPattyn{{{*/
+ElementMatrix* Penta::CreateKMatrixAdjointPattyn(void){
+
+	/*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);
+		material->GetViscosityDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=2*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
+		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
+		eps1[2]=epsilon[3];                eps2[2]=epsilon[4];
+
+		for(i=0;i<6;i++){
+			for(j=0;j<6;j++){
+				eps1dotdphii=eps1[0]*dphi[0][i]+eps1[1]*dphi[1][i]+eps1[2]*dphi[2][i];
+				eps1dotdphij=eps1[0]*dphi[0][j]+eps1[1]*dphi[1][j]+eps1[2]*dphi[2][j];
+				eps2dotdphii=eps2[0]*dphi[0][i]+eps2[1]*dphi[1][i]+eps2[2]*dphi[2][i];
+				eps2dotdphij=eps2[0]*dphi[0][j]+eps2[1]*dphi[1][j]+eps2[2]*dphi[2][j];
+
+				Ke->values[12*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[12*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[12*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[12*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixAdjointStokes{{{*/
+ElementMatrix* Penta::CreateKMatrixAdjointStokes(void){
+
+	/*Constants*/
+	const int    numdof=NDOF4*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,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);
+		material->GetViscosityDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=epsilon[0];   eps2[0]=epsilon[2];   eps3[0]=epsilon[3];
+		eps1[1]=epsilon[2];   eps2[1]=epsilon[1];   eps3[1]=epsilon[4];
+		eps1[2]=epsilon[3];   eps2[2]=epsilon[4];   eps3[2]= -epsilon[0] -epsilon[1];
+
+		for(i=0;i<6;i++){
+			for(j=0;j<6;j++){
+				eps1dotdphii=eps1[0]*dphi[0][i]+eps1[1]*dphi[1][i]+eps1[2]*dphi[2][i];
+				eps1dotdphij=eps1[0]*dphi[0][j]+eps1[1]*dphi[1][j]+eps1[2]*dphi[2][j];
+				eps2dotdphii=eps2[0]*dphi[0][i]+eps2[1]*dphi[1][i]+eps2[2]*dphi[2][i];
+				eps2dotdphij=eps2[0]*dphi[0][j]+eps2[1]*dphi[1][j]+eps2[2]*dphi[2][j];
+				eps3dotdphii=eps3[0]*dphi[0][i]+eps3[1]*dphi[1][i]+eps3[2]*dphi[2][i];
+				eps3dotdphij=eps3[0]*dphi[0][j]+eps3[1]*dphi[1][j]+eps3[2]*dphi[2][j];
+
+				Ke->values[numdof*(4*i+0)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[numdof*(4*i+0)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[numdof*(4*i+0)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps1dotdphii;
+
+				Ke->values[numdof*(4*i+1)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[numdof*(4*i+1)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
+				Ke->values[numdof*(4*i+1)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps2dotdphii;
+
+				Ke->values[numdof*(4*i+2)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps3dotdphii;
+				Ke->values[numdof*(4*i+2)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps3dotdphii;
+				Ke->values[numdof*(4*i+2)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps3dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorAdjointHoriz{{{*/
+ElementVector* Penta::CreatePVectorAdjointHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case MacAyealApproximationEnum:
+			return CreatePVectorAdjointMacAyeal();
+		case PattynApproximationEnum:
+			return CreatePVectorAdjointPattyn();
+		case NoneApproximationEnum:
+			return NULL;
+		case StokesApproximationEnum:
+			return CreatePVectorAdjointStokes();
+		default:
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorAdjointMacAyeal{{{*/
+ElementVector* Penta::CreatePVectorAdjointMacAyeal(){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorAdjointHoriz();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorAdjointPattyn{{{*/
+ElementVector* Penta::CreatePVectorAdjointPattyn(void){
+
+	if (!IsOnSurface()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+	ElementVector* pe=tria->CreatePVectorAdjointHoriz();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorAdjointStokes{{{*/
+ElementVector* Penta::CreatePVectorAdjointStokes(void){
+
+	if (!IsOnSurface()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+	ElementVector* pe=tria->CreatePVectorAdjointStokes();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::GradientIndexing{{{*/
+void Penta::GradientIndexing(int* indexing,int control_index){
+
+	/*Get some parameters*/
+	int num_controls;
+	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+
+	/*get gradient indices*/
+	for(int i=0;i<NUMVERTICES;i++){
+		indexing[i]=num_controls*this->nodes[i]->GetVertexDof() + control_index;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Penta::Gradj {{{*/
+void  Penta::Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index){
+	/*dJ/dalpha = ∂L/∂alpha = ∂J/∂alpha + ∂/∂alpha(KU-F)*/
+
+	int              i,approximation;
+	Tria*            tria=NULL;
+
+	/*If on water, skip grad (=0): */
+	if(IsOnWater())return;
+
+	/*First deal with ∂/∂alpha(KU-F)*/
+	switch(control_type){
+
+		case FrictionCoefficientEnum:
+			inputs->GetInputValue(&approximation,ApproximationEnum);
+			switch(approximation){
+				case MacAyealApproximationEnum:
+					GradjDragMacAyeal(gradient,control_index);
+					break;
+				case PattynApproximationEnum:
+					GradjDragPattyn(gradient,control_index);
+					break;
+				case StokesApproximationEnum:
+					GradjDragStokes(gradient,control_index);
+					break;
+				case NoneApproximationEnum:
+					/*Gradient is 0*/
+					break;
+				default:
+					_error_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
+
+		case MaterialsRheologyBbarEnum:
+			inputs->GetInputValue(&approximation,ApproximationEnum);
+			switch(approximation){
+				case MacAyealApproximationEnum:
+					GradjBbarMacAyeal(gradient,control_index);
+					break;
+				case PattynApproximationEnum:
+					GradjBbarPattyn(gradient,control_index);
+					break;
+				case StokesApproximationEnum:
+					GradjBbarStokes(gradient,control_index);
+					break;
+				case NoneApproximationEnum:
+					/*Gradient is 0*/
+					break;
+				default:
+					_error_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
+
+		default:
+			_error_("control type " << EnumToStringx(control_type) << " not supported yet: ");
+	}
+
+	/*Now deal with ∂J/∂alpha*/
+	int        *responses = NULL;
+	int         num_responses,resp;
+	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+
+	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+
+		case ThicknessAbsMisfitEnum:
+		case SurfaceAbsVelMisfitEnum:
+		case SurfaceRelVelMisfitEnum:
+		case SurfaceLogVelMisfitEnum:
+		case SurfaceLogVxVyMisfitEnum:
+		case SurfaceAverageVelMisfitEnum:
+			/*Nothing, J does not depends on the parameter being inverted for*/
+			break;
+		case DragCoefficientAbsGradientEnum:
+			if (!IsOnBed()) return;
+			tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+			tria->GradjDragGradient(gradient,resp,control_index);
+			delete tria->material; delete tria;
+			break;
+		case RheologyBbarAbsGradientEnum:
+			if (!IsOnBed()) return;
+			tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+			tria->GradjBGradient(gradient,resp,control_index);
+			delete tria->material; delete tria;
+			break;
+		default:
+			_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+	}
+	xDelete<int>(responses);
+}
+/*}}}*/
+/*FUNCTION Penta::GradjDragMacAyeal {{{*/
+void  Penta::GradjDragMacAyeal(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Gradient is 0 if on shelf or not on bed*/
+	if(IsFloating() || !IsOnBed()) return;
+
+	/*Spawn tria*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	tria->GradjDragMacAyeal(gradient,control_index);
+	delete tria->material; delete tria;
+
+} /*}}}*/
+/*FUNCTION Penta::GradjDragPattyn {{{*/
+void  Penta::GradjDragPattyn(Vector<IssmDouble>* gradient,int control_index){
+
+	int        i,j,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<IssmDouble>* 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<IssmDouble>* gradient,int control_index){
+
+	/*This element should be collapsed into a tria element at its base*/
+	if (!IsOnBed()) return; 
+
+	/*Depth Average B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*Collapse element to the base*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+	tria->GradjBMacAyeal(gradient,control_index);
+	delete tria->material; delete tria;
+
+	/*delete Average B*/
+	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+
+} /*}}}*/
+/*FUNCTION Penta::GradjBbarPattyn {{{*/
+void  Penta::GradjBbarPattyn(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Gradient is computed on bed only (Bbar)*/
+	if (!IsOnBed()) return;
+
+	/*Depth Average B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*Collapse element to the base*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2);
+	tria->GradjBMacAyeal(gradient,control_index);    //We use MacAyeal as an estimate for now
+	delete tria->material; delete tria;
+
+	/*delete Average B*/
+	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+} /*}}}*/
+/*FUNCTION Penta::GradjBbarStokes {{{*/
+void  Penta::GradjBbarStokes(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Gradient is computed on bed only (Bbar)*/
+	if (!IsOnBed()) return;
+
+	/*Depth Average B*/
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+
+	/*Collapse element to the base*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2);
+	tria->GradjBMacAyeal(gradient,control_index);    //We use MacAyeal as an estimate for now
+	delete tria->material; delete tria;
+
+	/*delete Average B*/
+	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+} /*}}}*/
+/*FUNCTION Penta::InputControlUpdate{{{*/
+void  Penta::InputControlUpdate(IssmDouble scalar,bool save_parameter){
+
+	/*Intermediary*/
+	int    num_controls;
+	int*   control_type=NULL;
+	Input* input=NULL;
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+	for(int i=0;i<num_controls;i++){
+
+		if(control_type[i]==MaterialsRheologyBbarEnum){
+			if (!IsOnBed()) goto cleanup_and_return;
+			input=(Input*)material->inputs->GetInput(MaterialsRheologyBEnum); _assert_(input);
+		}
+		else if(control_type[i]==MaterialsRheologyZbarEnum){
+			if (!IsOnBed()) goto cleanup_and_return;
+			input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum); _assert_(input);
+		}
+		else{
+			input=(Input*)this->inputs->GetInput(control_type[i]); _assert_(input);
+		}
+
+		if (input->ObjectEnum()!=ControlInputEnum) _error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
+
+		((ControlInput*)input)->UpdateValue(scalar);
+		((ControlInput*)input)->Constrain();
+		if (save_parameter) ((ControlInput*)input)->SaveValue();
+
+		if(control_type[i]==MaterialsRheologyBbarEnum){
+			this->InputExtrude(MaterialsRheologyBEnum,MaterialsEnum);
+		}
+		else if(control_type[i]==MaterialsRheologyZbarEnum){
+			this->InputExtrude(MaterialsRheologyZEnum,MaterialsEnum);
+		}
+	}
+
+	/*Clean up and return*/
+cleanup_and_return:
+	xDelete<int>(control_type);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionAdjointStokes {{{*/
+void  Penta::InputUpdateFromSolutionAdjointStokes(IssmDouble* solution){
+
+	const int    numdof=NDOF4*NUMVERTICES;
+
+	int    i;
+	IssmDouble values[numdof];
+	IssmDouble lambdax[NUMVERTICES];
+	IssmDouble lambday[NUMVERTICES];
+	IssmDouble lambdaz[NUMVERTICES];
+	IssmDouble lambdap[NUMVERTICES];
+	int*   doflist=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		lambdax[i]=values[i*NDOF4+0];
+		lambday[i]=values[i*NDOF4+1];
+		lambdaz[i]=values[i*NDOF4+2];
+		lambdap[i]=values[i*NDOF4+3];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambdaz[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambdap[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(AdjointxEnum,lambdax));
+	this->inputs->AddInput(new PentaP1Input(AdjointyEnum,lambday));
+	this->inputs->AddInput(new PentaP1Input(AdjointzEnum,lambdaz));
+	this->inputs->AddInput(new PentaP1Input(AdjointpEnum,lambdap));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionAdjointHoriz {{{*/
+void  Penta::InputUpdateFromSolutionAdjointHoriz(IssmDouble* solution){
+
+	const int numdof=NDOF2*NUMVERTICES;
+
+	int    i;
+	IssmDouble values[numdof];
+	IssmDouble lambdax[NUMVERTICES];
+	IssmDouble lambday[NUMVERTICES];
+	int*   doflist=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		lambdax[i]=values[i*NDOF2+0];
+		lambday[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(lambdax[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambday[i]))       _error_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(AdjointxEnum,lambdax));
+	this->inputs->AddInput(new PentaP1Input(AdjointyEnum,lambday));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::SurfaceAverageVelMisfit {{{*/
+IssmDouble Penta::SurfaceAverageVelMisfit(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->material; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceAverageVelMisfit(process_units,weight_index);
+		delete tria->material; 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->material; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceAbsVelMisfit(process_units,weight_index);
+		delete tria->material; 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->material; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceLogVelMisfit(process_units,weight_index);
+		delete tria->material; 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->material; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceLogVxVyMisfit(process_units,weight_index);
+		delete tria->material; 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->material; delete tria;
+		return J;
+	}
+	else{
+
+		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		J=tria->SurfaceRelVelMisfit(process_units,weight_index);
+		delete tria->material; delete tria;
+		return J;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::ThicknessAbsGradient{{{*/
+IssmDouble Penta::ThicknessAbsGradient(bool process_units,int weight_index){
+
+	_error_("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;
+	_error_("Not implemented yet");
+
+	tria=(Tria*)SpawnTria(0,1,2);
+	J=tria->ThicknessAbsMisfit(process_units,weight_index);
+	delete tria->material; 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->material; 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->material; delete tria;
+	return J;
+}
+/*}}}*/
+/*FUNCTION Penta::GetVectorFromControlInputs{{{*/
+void  Penta::GetVectorFromControlInputs(Vector<IssmDouble>* 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) _error_("Input " << EnumToStringx(control_enum) << " not found in element");
+
+	/*Check that it is a ControlInput*/
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->GetVectorFromInputs(vector,&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*)material->inputs->GetInput(control_enum); _assert_(input);
+	}
+	else{
+		input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	}
+
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->SetInput(new_input);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_DAKOTA_
+/*FUNCTION Penta::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);{{{*/
+void  Penta::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
+	
+	int i,j;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			/*New PentaP1Input*/
+			IssmDouble values[6];
+
+			/*Get values on the 6 vertices*/
+			for (i=0;i<6;i++){
+				values[i]=vector[this->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:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromVectorDakota(int* vector, int name, int type);{{{*/
+void  Penta::InputUpdateFromVectorDakota(int* vector, int name, int type){
+	_error_("not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromVectorDakota(bool* vector, int name, int type);{{{*/
+void  Penta::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+	_error_("not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type);{{{*/
+void  Penta::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){
+	
+	int i,j,t;
+	TransientInput* transientinput=NULL;
+	IssmDouble values[6];
+	IssmDouble time;
+	int row;
+	IssmDouble yts;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+			
+			/*Create transient input: */
+						
+			parameters->FindParam(&yts,ConstantsYtsEnum);
+
+			for(t=0;t<ncols;t++){ //ncols is the number of times
+
+				/*create input values: */
+				for(i=0;i<6;i++){
+					row=this->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:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_DIAGNOSTIC_
+/*FUNCTION Penta::CreateDVectorDiagnosticHoriz {{{*/
+ElementVector* Penta::CreateDVectorDiagnosticHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case StokesApproximationEnum:
+			return CreateDVectorDiagnosticStokes();
+		default:
+			return NULL; //no need for doftypes outside of stokes approximation
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateDVectorDiagnosticStokes{{{*/
+ElementVector* Penta::CreateDVectorDiagnosticStokes(void){
+
+	/*output: */
+	ElementVector* De=NULL;
+	/*intermediary: */
+	int approximation;
+	int i;
+
+	/*Initialize Element vector and return if necessary*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=StokesApproximationEnum) return NULL;
+
+	De=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	for (i=0;i<NUMVERTICES;i++){
+		De->values[i*4+0]=VelocityEnum;
+		De->values[i*4+1]=VelocityEnum;
+		De->values[i*4+2]=VelocityEnum;
+		De->values[i*4+3]=PressureEnum;
+	}
+
+	return De;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattyn{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattyn(void){
+	
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixCouplingMacAyealPattynViscous();
+	ElementMatrix* Ke2=CreateKMatrixCouplingMacAyealPattynFriction();
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+	
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattynViscous{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattynViscous(void){
+
+	/*Constants*/
+	const int numnodes    = 2 *NUMVERTICES;
+	const int numdofm     = NDOF2 *NUMVERTICES2D;
+	const int numdofp     = NDOF2 *NUMVERTICES;
+	const int numdoftotal = 2 *NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int         i,j,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);
+		material->GetViscosity3d(&viscosity, &epsilon[0]);
+		material->GetViscosity3d(&oldviscosity, &oldepsilon[0]);
+
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],3,numdofp,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdofm,0,
+					&Ke_gg_gaussian[0][0],0);
+
+		for( i=0; i<numdofp; i++) for(j=0;j<numdofm; j++) Ke_gg[i][j]+=Ke_gg_gaussian[i][j];
+	} 
+	for(i=0;i<numdofp;i++) for(j=0;j<numdofm;j++) Ke->values[(i+2*numdofm)*numdoftotal+j]+=Ke_gg[i][j];
+	for(i=0;i<numdofm;i++) for(j=0;j<numdofp;j++) Ke->values[i*numdoftotal+(j+2*numdofm)]+=Ke_gg[j][i];
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean-up and return*/
+	delete tria->material; delete tria;
+	delete gauss;
+	delete gauss_tria;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattynFriction{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattynFriction(void){
+
+	/*Constants*/
+	const int numnodes    = 2 *NUMVERTICES;
+	const int numdof      = NDOF2 *NUMVERTICES;
+	const int numdoftotal = NDOF4 *NUMVERTICES;
+	
+	/*Intermediaries */
+	int       i,j,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);
+		material->GetViscosity3dStokes(&viscosity, &epsilon[0]);
+
+		D_scalar=2*viscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+		D[3][3]=-gauss->weight*Jdet*stokesreconditioning;
+		for (i=0;i<3;i++) D2[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],4,numdofs+3,1,
+					&D[0][0],4,4,0,
+					&Bprime[0][0],4,numdofm,0,
+					&Ke_gg_gaussian[0][0],0);
+
+		TripleMultiply( &B2[0][0],3,numdofm,1,
+					&D2[0][0],3,3,0,
+					&Bprime2[0][0],3,numdofs+3,0,
+					&Ke_gg_gaussian2[0][0],0);
+
+		for( i=0; i<numdofs; i++) for(j=0;j<numdofm; j++) Ke_gg[i][j]+=Ke_gg_gaussian[i][j];
+		for( i=0; i<numdofm; i++) for(j=0;j<numdofs; j++) Ke_gg2[i][j]+=Ke_gg_gaussian2[i][j];
+	} 
+	for(i=0;i<numdofs;i++) for(j=0;j<numdofm;j++) Ke->values[(i+2*numdofm)*numdoftotal+j]+=Ke_gg[i][j];
+	for(i=0;i<numdofm;i++) for(j=0;j<numdofs;j++) Ke->values[i*numdoftotal+(j+2*numdofm)]+=Ke_gg2[i][j];
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean-up and return*/
+	delete tria->material; delete tria;
+	delete gauss;
+	delete gauss_tria;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingMacAyealStokesFriction {{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingMacAyealStokesFriction(void){
+
+	/*Constants*/
+	const int numnodes  = 2 *NUMVERTICES;
+	const int numdof    = NUMVERTICES *NDOF4;
+	const int numdofm   = NUMVERTICES *NDOF2;
+	const int numdof2d  = NUMVERTICES2D *NDOF4;
+	const int numdof2dm = NUMVERTICES2D *NDOF2;
+	const int numdoftot = numdof+numdofm;
+
+	/*Intermediaries */
+	int        i,j,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);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+
+		BedNormal(&bed_normal[0],xyz_list_tria);
+		friction->GetAlpha2(&alpha2_gauss, gauss,VxEnum,VyEnum,VzEnum);
+
+		DLMacAyealStokes[0][0]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLMacAyealStokes[1][1]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLMacAyealStokes[2][2]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[0]*bed_normal[2];
+		DLMacAyealStokes[3][3]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[1]*bed_normal[2];
+		DLMacAyealStokes[4][4]=-2*viscosity*gauss->weight*Jdet2d*bed_normal[0];
+		DLMacAyealStokes[5][5]=-2*viscosity*gauss->weight*Jdet2d*bed_normal[1];
+		DLMacAyealStokes[6][6]=stokesreconditioning*gauss->weight*Jdet2d*bed_normal[0];
+		DLMacAyealStokes[7][7]=stokesreconditioning*gauss->weight*Jdet2d*bed_normal[1];
+
+		DLStokesMacAyeal[0][0]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLStokesMacAyeal[1][1]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLStokesMacAyeal[2][2]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[0]*bed_normal[2];
+		DLStokesMacAyeal[3][3]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[1]*bed_normal[2];
+		
+		TripleMultiply( &LMacAyealStokes[0][0],8,numdof2dm,1,
+					&DLMacAyealStokes[0][0],8,8,0,
+					&LprimeMacAyealStokes[0][0],8,numdof2d,0,
+					&Ke_drag_gaussian[0][0],0);
+
+		TripleMultiply( &LStokesMacAyeal[0][0],4,numdof2d,1,
+					&DLStokesMacAyeal[0][0],4,4,0,
+					&LprimeStokesMacAyeal[0][0],4,numdof2dm,0,
+					&Ke_drag_gaussian2[0][0],0);
+
+		for(i=0;i<numdof2dm;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdoftot+j+numdofm]+=Ke_drag_gaussian[i][j];
+		for(i=0;i<numdof2d;i++) for(j=0;j<numdof2dm;j++) Ke->values[(i+numdofm)*numdoftot+j]+=Ke_drag_gaussian2[i][j];
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixCouplingPattynStokes{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingPattynStokes(void){
+
+	/*Constants*/
+	const int numnodes  = 2 *NUMVERTICES;
+	const int numdofp     = NDOF2 *NUMVERTICES;
+	const int numdofs     = NDOF4 *NUMVERTICES;
+	const int numdoftotal = (NDOF2+NDOF4) *NUMVERTICES;
+
+	/*Intermediaries*/
+	Node     *node_list[numnodes];
+	int       cs_list[numnodes];
+	int       i,j;
+
+	/*Prepare node list*/
+	for(i=0;i<NUMVERTICES;i++){
+		node_list[i+0*NUMVERTICES] = this->nodes[i];
+		node_list[i+1*NUMVERTICES] = this->nodes[i];
+		cs_list[i+0*NUMVERTICES] = XYEnum;
+		cs_list[i+1*NUMVERTICES] = XYZPEnum;
+	}
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=new ElementMatrix(this->nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
+	ElementMatrix* Ke2=new ElementMatrix(this->nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+	delete Ke1;
+	delete Ke2;
+	Ke1=CreateKMatrixDiagnosticPattyn(); TransformInvStiffnessMatrixCoord(Ke1,this->nodes,NUMVERTICES,XYEnum);
+	Ke2=CreateKMatrixDiagnosticStokes(); TransformInvStiffnessMatrixCoord(Ke2,this->nodes,NUMVERTICES,XYZPEnum);
+
+	for(i=0;i<numdofs;i++) for(j=0;j<NUMVERTICES;j++){
+		Ke->values[(i+numdofp)*numdoftotal+NDOF2*j+0]+=Ke2->values[i*numdofs+NDOF4*j+0];
+		Ke->values[(i+numdofp)*numdoftotal+NDOF2*j+1]+=Ke2->values[i*numdofs+NDOF4*j+1];
+	}
+	for(i=0;i<numdofp;i++) for(j=0;j<NUMVERTICES;j++){
+		Ke->values[i*numdoftotal+numdofp+NDOF4*j+0]+=Ke1->values[i*numdofp+NDOF2*j+0];
+		Ke->values[i*numdoftotal+numdofp+NDOF4*j+1]+=Ke1->values[i*numdofp+NDOF2*j+1];
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticHoriz {{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case MacAyealApproximationEnum:
+			return CreateKMatrixDiagnosticMacAyeal2d();
+		case L1L2ApproximationEnum:
+			return CreateKMatrixDiagnosticL1L2();
+		case PattynApproximationEnum:
+			return CreateKMatrixDiagnosticPattyn();
+		case StokesApproximationEnum:
+			return CreateKMatrixDiagnosticStokes();
+		case HutterApproximationEnum:
+			return NULL;
+		case NoneApproximationEnum:
+			return NULL;
+		case MacAyealPattynApproximationEnum:
+			return CreateKMatrixDiagnosticMacAyealPattyn();
+		case MacAyealStokesApproximationEnum:
+			return CreateKMatrixDiagnosticMacAyealStokes();
+		case PattynStokesApproximationEnum:
+			return CreateKMatrixDiagnosticPattynStokes();
+		default:
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticHutter{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticHutter(void){
+
+	/*Constants*/
+	const int numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries*/
+	int         connectivity[2];
+	int         i,i0,i1,j0,j1;
+	IssmDouble  one0,one1;
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Spawn 3 beam elements: */
+	for(i=0;i<3;i++){
+		/*2 dofs of first node*/
+		i0=2*i;
+		i1=2*i+1;
+		/*2 dofs of second node*/
+		j0=2*(i+3);
+		j1=2*(i+3)+1;
+
+		/*Find connectivity for the two nodes*/
+		connectivity[0]=nodes[i]->GetConnectivity();
+		connectivity[1]=nodes[i+3]->GetConnectivity();
+		one0=1/(IssmDouble)connectivity[0];
+		one1=1/(IssmDouble)connectivity[1];
+
+		/*Create matrix for these two nodes*/
+		if (IsOnBed() && IsOnSurface()){
+			Ke->values[i0*numdof+i0]=one0;
+			Ke->values[i1*numdof+i1]=one0;
+			Ke->values[j0*numdof+i0]=-one1;
+			Ke->values[j0*numdof+j0]=one1;
+			Ke->values[j1*numdof+i1]=-one1;
+			Ke->values[j1*numdof+j1]=one1;
+		}
+		else if (IsOnBed()){
+			Ke->values[i0*numdof+i0]=one0;
+			Ke->values[i1*numdof+i1]=one0;
+			Ke->values[j0*numdof+i0]=-2*one1;
+			Ke->values[j0*numdof+j0]=2*one1;
+			Ke->values[j1*numdof+i1]=-2*one1;
+			Ke->values[j1*numdof+j1]=2*one1;
+		}
+		else if (IsOnSurface()){
+			Ke->values[j0*numdof+i0]=-one1;
+			Ke->values[j0*numdof+j0]=one1;
+			Ke->values[j1*numdof+i1]=-one1;
+			Ke->values[j1*numdof+j1]=one1;
+		}
+		else{ //node is on two horizontal layers and beams include the values only once, so the have to use half of the connectivity
+			Ke->values[j0*numdof+i0]=-2*one1;
+			Ke->values[j0*numdof+j0]=2*one1;
+			Ke->values[j1*numdof+i1]=-2*one1;
+			Ke->values[j1*numdof+j1]=2*one1;
+		}
+	}
+
+	/*Clean up and return*/
+	return Ke;
+}/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal2d{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal2d(void){
+
+	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
+	  bedrock, in which case we spawn a tria element using the 3 first nodes, and use it to build 
+	  the stiffness matrix. */
+	if (!IsOnBed()) return NULL;
+
+	/*Depth average some fields*/
+	switch(this->material->ObjectEnum()){
+		case MaticeEnum:
+			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+			break;
+		case MatdamageiceEnum:
+			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+			this->InputDepthAverageAtBase(MaterialsRheologyZEnum,MaterialsRheologyZbarEnum,MaterialsEnum);
+			break;
+		default:
+			_error_("material "<<EnumToStringx(this->material->ObjectEnum())<<" not supported");
+	}
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixDiagnosticMacAyeal();
+	delete tria->material; delete tria;
+
+	/*Delete averaged fields*/
+	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+	this->material->inputs->DeleteInput(MaterialsRheologyZbarEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal3d{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal3d(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyeal3dViscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticMacAyeal3dFriction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal3dViscous{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal3dViscous(void){
+
+	/*Constants*/
+	const int    numdof2d=2*NUMVERTICES2D;
+
+	/*Intermediaries */
+	int         i,j,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];
+	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);
+			material->GetViscosity3d(&viscosity, &epsilon[0]);
+			material->GetViscosity3d(&oldviscosity, &oldepsilon[0]);
+
+			newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		}
+		else if (approximation==MacAyealStokesApproximationEnum){
+			this->GetStrainRate3d(&epsilons[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+			material->GetViscosity3dStokes(&newviscosity,&epsilons[0]);
+		}
+		else _error_("approximation " << approximation << " (" << EnumToStringx(approximation) << ") not supported yet");
+
+		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],3,numdof2d,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdof2d,0,
+					&Ke_gg_gaussian[0][0],0);
+
+		for(i=0;i<numdof2d;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdof2d+j]+=Ke_gg_gaussian[i][j];
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,tria->nodes,NUMVERTICES2D,XYEnum);
+
+	/*Clean up and return*/
+	delete tria->material;
+	delete tria;
+	delete gauss_tria;
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal3dFriction{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal3dFriction(void){
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating() || !IsOnBed()) return NULL;
+
+	/*Build a tria element using the 3 nodes of the base of the penta. Then use 
+	 * the tria functionality to build a friction stiffness matrix on these 3
+	 * nodes: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixDiagnosticMacAyealFriction();
+	delete tria->material; delete tria;
+
+	/*clean-up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyealPattyn{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyealPattyn(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyeal3d();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticPattyn();
+	ElementMatrix* Ke3=CreateKMatrixCouplingMacAyealPattyn();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyealStokes{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyealStokes(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyeal3d();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticStokes();
+	ElementMatrix* Ke3=CreateKMatrixCouplingMacAyealStokes();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticL1L2{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticL1L2(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticL1L2Viscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticL1L2Friction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticL1L2Viscous{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticL1L2Viscous(void){
+
+	/*Constants*/
+	const int    numdof2d=2*NUMVERTICES2D;
+
+	/*Intermediaries */
+	int         i,j;
+	IssmDouble  Jdet,viscosity;
+	IssmDouble  epsilon[5];       /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  B[3][numdof2d];
+	IssmDouble  Bprime[3][numdof2d];
+	IssmDouble  Ke_gg_gaussian[numdof2d][numdof2d];
+	IssmDouble  D[3][3]= {0.0};                 // material matrix, simple scalar matrix.
+	Tria       *tria       = NULL;
+	Penta      *pentabase  = NULL;
+	GaussPenta *gauss      = NULL;
+	GaussTria  *gauss_tria = NULL;
+
+	/*Find penta on bed as this is a macayeal elements: */
+	pentabase=GetBasalElement();
+	tria=pentabase->SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=new ElementMatrix(tria->nodes,NUMVERTICES2D,this->parameters,L1L2ApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], nodes,NUMVERTICES);
+	Input* vx_input=inputs->GetInput(VxEnum);        _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);        _assert_(vy_input);
+	Input* surf_input=inputs->GetInput(SurfaceEnum); _assert_(surf_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	gauss_tria=new GaussTria();
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussTria(gauss_tria);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		tria->GetBMacAyeal(&B[0][0], &xyz_list[0][0], gauss_tria);
+		tria->GetBprimeMacAyeal(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
+
+		/*Get viscosity for L1L2 model*/
+		GetL1L2Viscosity(&viscosity,&xyz_list[0][0],gauss,vx_input,vy_input,surf_input);
+
+		for(i=0;i<3;i++) D[i][i]=2*viscosity*gauss->weight*Jdet;
+
+		TripleMultiply( &B[0][0],3,numdof2d,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdof2d,0,
+					&Ke_gg_gaussian[0][0],0);
+		for(i=0;i<numdof2d;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdof2d+j]+=Ke_gg_gaussian[i][j];
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,tria->nodes,NUMVERTICES2D,XYEnum);
+
+	/*Clean up and return*/
+	delete tria->material;
+	delete tria;
+	delete gauss_tria;
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticL1L2Friction{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticL1L2Friction(void){
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating() || !IsOnBed()) return NULL;
+
+	/*Build a tria element using the 3 nodes of the base of the penta. Then use 
+	 * the tria functionality to build a friction stiffness matrix on these 3
+	 * nodes: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixDiagnosticMacAyealFriction();
+	delete tria->material; delete tria;
+
+	/*clean-up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticPattyn{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticPattyn(void){
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticPattynViscous();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticPattynFriction();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticPattynViscous{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticPattynViscous(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,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);
+		material->GetViscosity3d(&viscosity, &epsilon[0]);
+		material->GetViscosity3d(&oldviscosity, &oldepsilon[0]);
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+
+		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		for (i=0;i<5;i++) D[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],5,numdof,1,
+					&D[0][0],5,5,0,
+					&Bprime[0][0],5,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticPattynFriction{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticPattynFriction(void){
+
+	/*Constants*/
+	const int numdof   = NDOF2*NUMVERTICES;
+	
+	/*Intermediaries */
+	int       i,j,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);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+
+		D_scalar=gauss->weight*Jdet;
+		for (i=0;i<6;i++) D[i][i]=D_scalar*2*viscosity;
+		for (i=6;i<8;i++) D[i][i]=-D_scalar*stokesreconditioning;
+
+		TripleMultiply( &B[0][0],8,27,1,
+					&D[0][0],8,8,0,
+					&B_prime[0][0],8,27,0,
+					&Ke_temp[0][0],1);
+	}
+
+	/*Condensation*/
+	ReduceMatrixStokes(Ke->values, &Ke_temp[0][0]);
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticStokesFriction{{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticStokesFriction(void){
+
+	/*Constants*/
+	const int numdof=NUMVERTICES*NDOF4;
+	const int numdof2d=NUMVERTICES2D*NDOF4;
+
+	/*Intermediaries */
+	int        i,j,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);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+
+		friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum);
+
+		DLStokes[0][0] = +alpha2*gauss->weight*Jdet2d; //taub_x = -alpha2 vx
+		DLStokes[1][1] = +alpha2*gauss->weight*Jdet2d; //taub_y = -alpha2 vy
+
+		TripleMultiply( &LStokes[0][0],2,numdof2d,1,
+					&DLStokes[0][0],2,2,0,
+					&LStokes[0][0],2,numdof2d,0,
+					&Ke_drag_gaussian[0][0],0);
+
+		for(i=0;i<numdof2d;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdof+j]+=Ke_drag_gaussian[i][j];
+	}
+
+	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
+	//TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+	
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticVert {{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticVert(void){
+	
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixDiagnosticVertVolume();
+	ElementMatrix* Ke2=CreateKMatrixDiagnosticVertSurface();
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixDiagnosticVertVolume {{{*/
+ElementMatrix* Penta::CreateKMatrixDiagnosticVertVolume(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	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);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+
+		for(i=0;i<NUMVERTICES;i++){
+			pe->values[i*NDOF4+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
+			pe->values[i*NDOF4+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
+			pe->values[i*NDOF4+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
+			pe->values[i*NDOF4+3]+=Jdet*gauss->weight*stokesreconditioning*dw[2]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingMacAyealStokesFriction{{{*/
+ElementVector* Penta::CreatePVectorCouplingMacAyealStokesFriction(void){
+
+	/*Constants*/
+	const int numdof=NUMVERTICES*NDOF4;
+
+	/*Intermediaries*/
+	int         i,j,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);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		friction->GetAlpha2(&alpha2_gauss, gauss,VxEnum,VyEnum,VzEnum);
+
+		for(i=0;i<NUMVERTICES2D;i++){
+			pe->values[i*NDOF4+0]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[0]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[0])*basis[i];
+			pe->values[i*NDOF4+1]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[1]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[1])*basis[i];
+			pe->values[i*NDOF4+2]+=Jdet2d*gauss->weight*2*viscosity*(dw[0]*bed_normal[0]+dw[1]*bed_normal[1]+dw[2]*bed_normal[2])*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingPattynStokes {{{*/
+ElementVector* Penta::CreatePVectorCouplingPattynStokes(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorCouplingPattynStokesViscous();
+	ElementVector* pe2=CreatePVectorCouplingPattynStokesFriction();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingPattynStokesViscous {{{*/
+ElementVector* Penta::CreatePVectorCouplingPattynStokesViscous(void){
+
+	/*Constants*/
+	const int   numdof=NUMVERTICES*NDOF4;
+
+	/*Intermediaries */
+	int         i,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);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+
+		for(i=0;i<NUMVERTICES;i++){
+			pe->values[i*NDOF4+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
+			pe->values[i*NDOF4+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
+			pe->values[i*NDOF4+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
+			pe->values[i*NDOF4+3]+=Jdet*gauss->weight*stokesreconditioning*dw[2]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorCouplingPattynStokesFriction{{{*/
+ElementVector* Penta::CreatePVectorCouplingPattynStokesFriction(void){
+
+	/*Constants*/
+	const int numdof=NUMVERTICES*NDOF4;
+
+	/*Intermediaries*/
+	int         i,j,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);
+		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		friction->GetAlpha2(&alpha2_gauss, gauss,VxEnum,VyEnum,VzEnum);
+
+		for(i=0;i<NUMVERTICES2D;i++){
+			pe->values[i*NDOF4+0]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[0]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[0])*basis[i];
+			pe->values[i*NDOF4+1]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[1]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[1])*basis[i];
+			pe->values[i*NDOF4+2]+=Jdet2d*gauss->weight*2*viscosity*(dw[0]*bed_normal[0]+dw[1]*bed_normal[1]+dw[2]*bed_normal[2])*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticHoriz{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticHoriz(void){
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	switch(approximation){
+		case MacAyealApproximationEnum:
+			return CreatePVectorDiagnosticMacAyeal();
+		case PattynApproximationEnum:
+			return CreatePVectorDiagnosticPattyn();
+		case L1L2ApproximationEnum:
+			return CreatePVectorDiagnosticL1L2();
+		case HutterApproximationEnum:
+			return NULL;
+		case NoneApproximationEnum:
+			return NULL;
+		case StokesApproximationEnum:
+			return CreatePVectorDiagnosticStokes();
+		case MacAyealPattynApproximationEnum:
+			return CreatePVectorDiagnosticMacAyealPattyn();
+		case MacAyealStokesApproximationEnum:
+			return CreatePVectorDiagnosticMacAyealStokes();
+		case PattynStokesApproximationEnum:
+			return CreatePVectorDiagnosticPattynStokes();
+		default:
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticMacAyealPattyn{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticMacAyealPattyn(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorDiagnosticMacAyeal();
+	ElementVector* pe2=CreatePVectorDiagnosticPattyn();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticMacAyealStokes{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticMacAyealStokes(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorDiagnosticMacAyeal();
+	ElementVector* pe2=CreatePVectorDiagnosticStokes();
+	ElementVector* pe3=CreatePVectorCouplingMacAyealStokes();
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticPattynStokes{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticPattynStokes(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorDiagnosticPattyn();
+	ElementVector* pe2=CreatePVectorDiagnosticStokes();
+	ElementVector* pe3=CreatePVectorCouplingPattynStokes();
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticHutter{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticHutter(void){
+
+	/*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=material->GetN();
+	B=material->GetB();
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);  _assert_(thickness_input);
+	Input* surface_input=inputs->GetInput(SurfaceEnum);      _assert_(surface_input);
+	Input* slopex_input=inputs->GetInput(SurfaceSlopeXEnum); _assert_(slopex_input);
+	Input* slopey_input=inputs->GetInput(SurfaceSlopeYEnum); _assert_(slopey_input);
+	for(i=0;i<NUMVERTICES;i++)z_list[i]=xyz_list[i][2];
+
+	/*Loop on the three segments*/
+	for(i=0;i<3;i++){
+		node0=i;
+		node1=i+3;
+
+		for(j=0;j<3;j++){
+			xyz_list_segment[0][j]=xyz_list[node0][j];
+			xyz_list_segment[1][j]=xyz_list[node1][j];
+		}
+
+		connectivity[0]=nodes[node0]->GetConnectivity();
+		connectivity[1]=nodes[node1]->GetConnectivity();
+
+		/*Loop on the Gauss points: */
+		gauss=new GaussPenta(node0,node1,3);
+		for(ig=gauss->begin();ig<gauss->end();ig++){
+			gauss->GaussPoint(ig);
+
+			slopex_input->GetInputValue(&slope[0],gauss);
+			slopey_input->GetInputValue(&slope[1],gauss);
+			surface_input->GetInputValue(&surface,gauss);
+			thickness_input->GetInputValue(&thickness,gauss);
+
+			slope2=pow(slope[0],2)+pow(slope[1],2);
+			constant_part=-2*pow(rho_ice*gravity,n)*pow(slope2,((n-1)/2));
+
+			PentaRef::GetInputValue(&z_g,&z_list[0],gauss);
+			GetSegmentJacobianDeterminant(&Jdet,&xyz_list_segment[0][0],gauss);
+
+			if (IsOnSurface()){
+				for(j=0;j<NDOF2;j++) pe->values[2*node1+j]+=constant_part*pow((surface-z_g)/B,n)*slope[j]*Jdet*gauss->weight/(IssmDouble)connectivity[1];
+			}
+			else{//connectivity is too large, should take only half on it
+				for(j=0;j<NDOF2;j++) pe->values[2*node1+j]+=constant_part*pow((surface-z_g)/B,n)*slope[j]*Jdet*gauss->weight*2/(IssmDouble)connectivity[1];
+			}
+		}
+		delete gauss;
+
+		//Deal with lower surface
+		if (IsOnBed()){
+			constant_part=-1.58*pow((IssmDouble)10.0,-(IssmDouble)10.0)*rho_ice*gravity*thickness;
+			ub=constant_part*slope[0];
+			vb=constant_part*slope[1];
+
+			pe->values[2*node0]+=ub/(IssmDouble)connectivity[0];
+			pe->values[2*node0+1]+=vb/(IssmDouble)connectivity[0];
+		}
+	}
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticMacAyeal{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticMacAyeal(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorDiagnosticMacAyeal();
+	delete tria->material; delete tria;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticL1L2{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticL1L2(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorDiagnosticMacAyeal();
+	delete tria->material; delete tria;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorDiagnosticPattyn{{{*/
+ElementVector* Penta::CreatePVectorDiagnosticPattyn(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries*/
+	int         i,j,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);
+		material->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:
+			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateJacobianDiagnosticMacayeal2d{{{*/
+ElementMatrix* Penta::CreateJacobianDiagnosticMacayeal2d(void){
+
+	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
+	  bedrock, in which case we spawn a tria element using the 3 first nodes, and use it to build 
+	  the stiffness matrix. */
+	if (!IsOnBed()) return NULL;
+
+	/*Depth average some fields*/
+	switch(this->material->ObjectEnum()){
+		case MaticeEnum:
+			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+			break;
+		case MatdamageiceEnum:
+			this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum,MaterialsEnum);
+			this->InputDepthAverageAtBase(MaterialsRheologyZEnum,MaterialsRheologyZbarEnum,MaterialsEnum);
+			break;
+		default:
+			_error_("material "<<EnumToStringx(this->material->ObjectEnum())<<" not supported");
+	}
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateJacobianDiagnosticMacayeal();
+	delete tria->material; delete tria;
+
+	/*Delete averaged inputs*/
+	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+	this->material->inputs->DeleteInput(MaterialsRheologyZbarEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateJacobianDiagnosticPattyn{{{*/
+ElementMatrix* Penta::CreateJacobianDiagnosticPattyn(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,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);
+		material->GetViscosityDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=2*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
+		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
+		eps1[2]=epsilon[3];                eps2[2]=epsilon[4];
+
+		for(i=0;i<6;i++){
+			for(j=0;j<6;j++){
+				eps1dotdphii=eps1[0]*dphi[0][i]+eps1[1]*dphi[1][i]+eps1[2]*dphi[2][i];
+				eps1dotdphij=eps1[0]*dphi[0][j]+eps1[1]*dphi[1][j]+eps1[2]*dphi[2][j];
+				eps2dotdphii=eps2[0]*dphi[0][i]+eps2[1]*dphi[1][i]+eps2[2]*dphi[2][i];
+				eps2dotdphij=eps2[0]*dphi[0][j]+eps2[1]*dphi[1][j]+eps2[2]*dphi[2][j];
+
+				Ke->values[12*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[12*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[12*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[12*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateJacobianDiagnosticStokes{{{*/
+ElementMatrix* Penta::CreateJacobianDiagnosticStokes(void){
+
+	/*Constants*/
+	const int    numdof=NDOF4*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,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);
+		material->GetViscosityDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=epsilon[0];   eps2[0]=epsilon[2];   eps3[0]=epsilon[3];
+		eps1[1]=epsilon[2];   eps2[1]=epsilon[1];   eps3[1]=epsilon[4];
+		eps1[2]=epsilon[3];   eps2[2]=epsilon[4];   eps3[2]= -epsilon[0] -epsilon[1];
+
+		for(i=0;i<6;i++){
+			for(j=0;j<6;j++){
+				eps1dotdphii=eps1[0]*dphi[0][i]+eps1[1]*dphi[1][i]+eps1[2]*dphi[2][i];
+				eps1dotdphij=eps1[0]*dphi[0][j]+eps1[1]*dphi[1][j]+eps1[2]*dphi[2][j];
+				eps2dotdphii=eps2[0]*dphi[0][i]+eps2[1]*dphi[1][i]+eps2[2]*dphi[2][i];
+				eps2dotdphij=eps2[0]*dphi[0][j]+eps2[1]*dphi[1][j]+eps2[2]*dphi[2][j];
+				eps3dotdphii=eps3[0]*dphi[0][i]+eps3[1]*dphi[1][i]+eps3[2]*dphi[2][i];
+				eps3dotdphij=eps3[0]*dphi[0][j]+eps3[1]*dphi[1][j]+eps3[2]*dphi[2][j];
+
+				Ke->values[numdof*(4*i+0)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[numdof*(4*i+0)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[numdof*(4*i+0)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps1dotdphii;
+
+				Ke->values[numdof*(4*i+1)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[numdof*(4*i+1)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
+				Ke->values[numdof*(4*i+1)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps2dotdphii;
+
+				Ke->values[numdof*(4*i+2)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps3dotdphii;
+				Ke->values[numdof*(4*i+2)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps3dotdphii;
+				Ke->values[numdof*(4*i+2)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps3dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsDiagnosticHoriz{{{*/
+void  Penta::GetSolutionFromInputsDiagnosticHoriz(Vector<IssmDouble>* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int         i;
+	int         approximation;
+	int        *doflist        = NULL;
+	IssmDouble  vx,vy;
+	IssmDouble  values[numdof];
+	GaussPenta *gauss;
+
+	/*Get approximation enum and dof list: */
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*If the element is a coupling, do nothing: every node is also on an other elements 
+	 * (as coupling is between MacAyeal and Pattyn) so the other element will take care of it*/
+	GetDofList(&doflist,approximation,GsetEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	/*P1 element only for now*/
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+
+		/*Recover vx and vy*/
+		gauss->GaussVertex(i);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		values[i*NDOF2+0]=vx;
+		values[i*NDOF2+1]=vy;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsDiagnosticHutter{{{*/
+void  Penta::GetSolutionFromInputsDiagnosticHutter(Vector<IssmDouble>* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	IssmDouble       vx,vy;
+	IssmDouble       values[numdof];
+	GaussPenta*  gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	/*P1 element only for now*/
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover vx and vy*/
+		gauss->GaussVertex(i);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		values[i*NDOF2+0]=vx;
+		values[i*NDOF2+1]=vy;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsDiagnosticVert{{{*/
+void  Penta::GetSolutionFromInputsDiagnosticVert(Vector<IssmDouble>* solution){
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	IssmDouble       vz;
+	IssmDouble       values[numdof];
+	GaussPenta*  gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* vz_input=inputs->GetInput(VzEnum); _assert_(vz_input);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	/*P1 element only for now*/
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover vz */
+		gauss->GaussVertex(i);
+		vz_input->GetInputValue(&vz,gauss);
+		values[i]=vz;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetSolutionFromInputsDiagnosticStokes{{{*/
+void  Penta::GetSolutionFromInputsDiagnosticStokes(Vector<IssmDouble>* solution){
+
+	const int    numdof=NDOF4*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	IssmDouble       vx,vy,vz,p;
+	IssmDouble       stokesreconditioning;
+	IssmDouble       values[numdof];
+	GaussPenta   *gauss;
+
+	/*Get dof list: */
+	GetDofList(&doflist,StokesApproximationEnum,GsetEnum);
+	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);       _assert_(vz_input);
+	Input* p_input =inputs->GetInput(PressureEnum); _assert_(p_input);
+
+	/*Recondition pressure: */
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+
+	/*Ok, we have vx vy vz and P in values, fill in vx vy vz P arrays: */
+	/*P1 element only for now*/
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		gauss->GaussVertex(i);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vz_input->GetInputValue(&vz,gauss);
+		p_input ->GetInputValue(&p ,gauss);
+		values[i*NDOF4+0]=vx;
+		values[i*NDOF4+1]=vy;
+		values[i*NDOF4+2]=vz;
+		values[i*NDOF4+3]=p/stokesreconditioning;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::GetL1L2Viscosity{{{*/
+void Penta::GetL1L2Viscosity(IssmDouble* pviscosity,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input,Input* surface_input){
+	/*Compute the L1L2 viscosity
+	 *
+	 *      1
+	 * mu = - A^-1 (sigma'_e)^(1-n)
+	 *      2
+	 *
+	 * sigma'_e^2 = |sigma'_//|^2 + |sigma'_perp|^2 (see Perego 2012 eq. 17,18)
+	 *
+	 * L1L2 assumptions:
+	 *
+	 * (1) |eps_b|_// = A (|sigma'_//|^2 + |sigma'_perp|^2)^((n-1)/2) |sigma'_//|
+	 * (2) |sigma'_perp|^2 = |rho g (s-z) grad(s)|^2
+	 *
+	 * Assuming that n = 3, we have a polynom of degree 3 to solve (the only unkown is X=|sigma'_//|)
+	 *
+	 * A X^3 + A |rho g (s-z) grad(s)|^2 X - |eps_b|_// = 0     */
+
+	int        i;
+	IssmDouble z,s,viscosity,p,q,delta;
+	IssmDouble tau_perp,tau_par,eps_b,A;
+	IssmDouble epsilonvx[5]; /*exx eyy exy exz eyz*/
+	IssmDouble epsilonvy[5]; /*exx eyy exy exz eyz*/
+	IssmDouble epsilon[5];   /*exx eyy exy exz eyz*/
+	IssmDouble z_list[NUMVERTICES];
+	IssmDouble slope[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input || !surface_input) _error_("Input missing");
+
+	/*Get tau_perp*/
+	for(i=0;i<NUMVERTICES;i++) z_list[i]=xyz_list[3*i+2];
+	surface_input->GetInputValue(&s,gauss);
+	surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+	PentaRef::GetInputValue(&z,&z_list[0],gauss);
+	tau_perp = matpar->GetRhoIce() * matpar->GetG() * fabs(s-z)*sqrt(slope[0]*slope[0]+slope[1]*slope[1]);
+
+	/* Get eps_b*/
+	vx_input->GetVxStrainRate3dPattyn(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate3dPattyn(epsilonvy,xyz_list,gauss);
+	for(i=0;i<5;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i];
+	eps_b = sqrt(epsilon[0]*epsilon[0] + epsilon[1]*epsilon[1] + epsilon[0]*epsilon[1] + epsilon[2]*epsilon[2]);
+	if(eps_b==0.){
+		*pviscosity = 2.5e+17;
+		return;
+	}
+
+	/*Get A*/
+	_assert_(material->GetN()==3.0);
+	A=material->GetA();
+
+	/*Solve for tau_perp (http://fr.wikipedia.org/wiki/Méthode_de_Cardan)*/
+	p     = tau_perp *tau_perp;
+	q     = - eps_b/A;
+	delta = q *q + p*p*p*4./27.;
+	_assert_(delta>0);
+	tau_par = pow(0.5*(-q+sqrt(delta)),1./3.) - pow(0.5*(q+sqrt(delta)),1./3.);
+
+	/*Viscosity*/
+	viscosity = 1./(2.*A*(tau_par*tau_par + tau_perp*tau_perp));
+	_assert_(!isnan(viscosity));
+	_assert_(viscosity > 0.);
+
+	/*Assign output pointer*/
+	*pviscosity = viscosity;
+	return; 
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticHoriz {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticHoriz(IssmDouble* solution){
+
+	int  approximation;
+
+	/*Recover inputs*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	/*MacAyeal, everything is done by the element on bed*/
+	if (approximation==MacAyealApproximationEnum){
+		if (!IsOnBed()){
+			/*Do nothing. Element on bed will take care of it*/
+			return;
+		}
+		else{
+			InputUpdateFromSolutionDiagnosticMacAyeal(solution);
+			return;
+		}
+	}
+	if (approximation==L1L2ApproximationEnum){
+		if (!IsOnBed()) return;
+		InputUpdateFromSolutionDiagnosticL1L2(solution);
+		return;
+	}
+	else if (approximation==PattynApproximationEnum){
+		InputUpdateFromSolutionDiagnosticPattyn(solution);
+	}
+	else if (approximation==PattynStokesApproximationEnum){
+		InputUpdateFromSolutionDiagnosticPattynStokes(solution);
+	}
+	else if (approximation==MacAyealStokesApproximationEnum){
+		InputUpdateFromSolutionDiagnosticMacAyealStokes(solution);
+	}
+	else if (approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
+		InputUpdateFromSolutionDiagnosticStokes(solution);
+	}
+	else if (approximation==MacAyealPattynApproximationEnum){
+		InputUpdateFromSolutionDiagnosticMacAyealPattyn(solution);
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticMacAyeal {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticMacAyeal(IssmDouble* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int     i;
+	IssmDouble  rho_ice,g;
+	IssmDouble  values[numdof];
+	IssmDouble  vx[NUMVERTICES];
+	IssmDouble  vy[NUMVERTICES];
+	IssmDouble  vz[NUMVERTICES];
+	IssmDouble  vel[NUMVERTICES];
+	IssmDouble  pressure[NUMVERTICES];
+	IssmDouble  surface[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	int    *doflist = NULL;
+	Penta  *penta   = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,MacAyealApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&values[0],nodes,NUMVERTICES2D,XYEnum); /*2D: only the first 3 nodes are taken*/
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays and extrude */
+	for(i=0;i<3;i++){
+		vx[i]  =values[i*NDOF2+0];
+		vy[i]  =values[i*NDOF2+1];
+		vx[i+3]=vx[i];
+		vy[i+3]=vy[i];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get parameters fro pressure computation*/
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	for(;;){
+
+		/*Get node data: */
+		GetVerticesCoordinates(&xyz_list[0][0],penta->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])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Now Compute vel*/
+	GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
+	 *so the pressure is just the pressure at the z elevation: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	GetInputListOnVertices(&surface[0],SurfaceEnum);
+	for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xDelete<int>(doflistp);
+	xDelete<int>(doflistm);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticMacAyealStokes {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticMacAyealStokes(IssmDouble* solution){
+
+	const int    numdofm=NDOF2*NUMVERTICES;
+	const int    numdofs=NDOF4*NUMVERTICES;
+	const int    numdof2d=NDOF2*NUMVERTICES2D;
+
+	int     i;
+	IssmDouble  stokesreconditioning;
+	IssmDouble  macayeal_values[numdofm];
+	IssmDouble  stokes_values[numdofs];
+	IssmDouble  vx[NUMVERTICES];
+	IssmDouble  vy[NUMVERTICES];
+	IssmDouble  vz[NUMVERTICES];
+	IssmDouble  vzmacayeal[NUMVERTICES];
+	IssmDouble  vzstokes[NUMVERTICES];
+	IssmDouble  vel[NUMVERTICES];
+	IssmDouble  pressure[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	int*    doflistm        = NULL;
+	int*    doflists        = NULL;
+	Penta   *penta          = NULL;
+
+	/*OK, we have to add results of this element for macayeal 
+	 * and results from the penta at base for macayeal. Now recover results*/
+	penta=GetBasalElement();
+
+	/*Get dof listof this element (macayeal dofs) and of the penta at base (macayeal dofs): */
+	penta->GetDofList(&doflistm,MacAyealApproximationEnum,GsetEnum);
+	GetDofList(&doflists,StokesApproximationEnum,GsetEnum);
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+
+	/*Get node data: */
+	GetVerticesCoordinates(&xyz_list[0][0], 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]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vzstokes[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz*/
+	Input* vzmacayeal_input=inputs->GetInput(VzMacAyealEnum);
+	if (vzmacayeal_input){
+		if (vzmacayeal_input->ObjectEnum()!=PentaP1InputEnum){
+			_error_("Cannot compute Vel as VzMacAyeal is of type " << EnumToStringx(vzmacayeal_input->ObjectEnum()));
+		}
+		GetInputListOnVertices(&vzmacayeal[0],VzMacAyealEnum);
+	}
+	else{
+		_error_("Cannot update solution as VzMacAyeal is not present");
+	}
+
+	/*Now Compute vel*/
+	for(i=0;i<NUMVERTICES;i++) {
+		vz[i]=vzmacayeal[i]+vzstokes[i];
+		vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+	}
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(VzEnum,VzPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new PentaP1Input(VzEnum,vz));
+	this->inputs->AddInput(new PentaP1Input(VzStokesEnum,vzstokes));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xDelete<int>(doflistm);
+	xDelete<int>(doflists);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticL1L2 {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticL1L2(IssmDouble* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int     i;
+	IssmDouble  rho_ice,g;
+	IssmDouble  values[numdof];
+	IssmDouble  vx[NUMVERTICES];
+	IssmDouble  vy[NUMVERTICES];
+	IssmDouble  vz[NUMVERTICES];
+	IssmDouble  vel[NUMVERTICES];
+	IssmDouble  pressure[NUMVERTICES];
+	IssmDouble  surface[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	int    *doflist = NULL;
+	Penta  *penta   = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,L1L2ApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&values[0],nodes,NUMVERTICES2D,XYEnum); /*2D: only the first 3 nodes are taken*/
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays and extrude */
+	for(i=0;i<3;i++){
+		vx[i]  =values[i*NDOF2+0];
+		vy[i]  =values[i*NDOF2+1];
+		vx[i+3]=vx[i];
+		vy[i+3]=vy[i];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get parameters fro pressure computation*/
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	for(;;){
+
+		/*Get node data: */
+		GetVerticesCoordinates(&xyz_list[0][0],penta->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::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])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz*/
+	Input* vz_input=inputs->GetInput(VzEnum);
+	if (vz_input){
+		GetInputListOnVertices(&vz[0],VzEnum);
+	}
+	else{
+		for(i=0;i<NUMVERTICES;i++) vz[i]=0.0;
+	}
+
+	/*Now Compute vel*/
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
+	 *so the pressure is just the pressure at the z elevation: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	GetInputListOnVertices(&surface[0],SurfaceEnum);
+	for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticPattynStokes {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticPattynStokes(IssmDouble* solution){
+
+	const int    numdofp=NDOF2*NUMVERTICES;
+	const int    numdofs=NDOF4*NUMVERTICES;
+
+	int    i;
+	IssmDouble pattyn_values[numdofp];
+	IssmDouble stokes_values[numdofs];
+	IssmDouble vx[NUMVERTICES];
+	IssmDouble vy[NUMVERTICES];
+	IssmDouble vz[NUMVERTICES];
+	IssmDouble vzpattyn[NUMVERTICES];
+	IssmDouble vzstokes[NUMVERTICES];
+	IssmDouble vel[NUMVERTICES];
+	IssmDouble pressure[NUMVERTICES];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble stokesreconditioning;
+	int*   doflistp      = NULL;
+	int*   doflists      = NULL;
+	Penta  *penta        = NULL;
+
+	/*OK, we have to add results of this element for pattyn 
+	 * and results from the penta at base for macayeal. Now recover results*/
+	penta=GetBasalElement();
+
+	/*Get dof listof this element (pattyn dofs) and of the penta at base (macayeal dofs): */
+	GetDofList(&doflistp,PattynApproximationEnum,GsetEnum);
+	GetDofList(&doflists,StokesApproximationEnum,GsetEnum);
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+
+	/*Get node data: */
+	GetVerticesCoordinates(&xyz_list[0][0], 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]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vzstokes[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz*/
+	Input* vzpattyn_input=inputs->GetInput(VzPattynEnum);
+	if (vzpattyn_input){
+		if (vzpattyn_input->ObjectEnum()!=PentaP1InputEnum){
+			_error_("Cannot compute Vel as VzPattyn is of type " << EnumToStringx(vzpattyn_input->ObjectEnum()));
+		}
+		GetInputListOnVertices(&vzpattyn[0],VzPattynEnum);
+	}
+	else{
+		_error_("Cannot update solution as VzPattyn is not present");
+	}
+
+	/*Now Compute vel*/
+	for(i=0;i<NUMVERTICES;i++) {
+		vz[i]=vzpattyn[i]+vzstokes[i];
+		vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+	}
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(VzEnum,VzPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new PentaP1Input(VzEnum,vz));
+	this->inputs->AddInput(new PentaP1Input(VzStokesEnum,vzstokes));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xDelete<int>(doflistp);
+	xDelete<int>(doflists);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticHutter {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticHutter(IssmDouble* solution){
+	
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int     i;
+	IssmDouble  rho_ice,g;
+	IssmDouble  values[numdof];
+	IssmDouble  vx[NUMVERTICES];
+	IssmDouble  vy[NUMVERTICES];
+	IssmDouble  vz[NUMVERTICES];
+	IssmDouble  vel[NUMVERTICES];
+	IssmDouble  pressure[NUMVERTICES];
+	IssmDouble  surface[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	int*    doflist = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Get node data: */
+	GetVerticesCoordinates(&xyz_list[0][0], 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])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Now Compute vel*/
+	GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
+	 *so the pressure is just the pressure at the z elevation: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	GetInputListOnVertices(&surface[0],SurfaceEnum);
+	for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticVert {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticVert(IssmDouble* solution){
+
+	const int numdof=NDOF1*NUMVERTICES;
+	
+	int      i;
+	int      approximation;
+	IssmDouble   rho_ice,g;
+	IssmDouble   values[numdof];
+	IssmDouble   vx[NUMVERTICES];
+	IssmDouble   vy[NUMVERTICES];
+	IssmDouble   vz[NUMVERTICES];
+	IssmDouble   vzmacayeal[NUMVERTICES];
+	IssmDouble   vzpattyn[NUMVERTICES];
+	IssmDouble   vzstokes[NUMVERTICES];
+	IssmDouble   vel[NUMVERTICES];
+	IssmDouble   pressure[NUMVERTICES];
+	IssmDouble   surface[NUMVERTICES];
+	IssmDouble   xyz_list[NUMVERTICES][3];
+	int*     doflist      = NULL;
+
+
+	/*Get the approximation and do nothing if the element in Stokes or None*/
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
+		return;
+	}
+
+	/*Get dof list and vertices coordinates: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	GetVerticesCoordinates(&xyz_list[0][0], 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])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vx and Vy*/
+	GetInputListOnVertices(&vx[0],VxEnum,0.0); //default is 0
+	GetInputListOnVertices(&vy[0],VyEnum,0.0); //default is 0
+
+	/*Do some modifications if we actually have a PattynStokes or MacAyealStokes element*/
+	if(approximation==PattynStokesApproximationEnum){
+		Input* vzstokes_input=inputs->GetInput(VzStokesEnum);
+		if (vzstokes_input){
+			if (vzstokes_input->ObjectEnum()!=PentaP1InputEnum) _error_("Cannot compute Vel as VzStokes is of type " << EnumToStringx(vzstokes_input->ObjectEnum()));
+			GetInputListOnVertices(&vzstokes[0],VzStokesEnum);
+		}
+		else _error_("Cannot compute Vz as VzStokes in not present in PattynStokes element");
+		for(i=0;i<NUMVERTICES;i++){
+			vzpattyn[i]=vz[i];
+			vz[i]=vzpattyn[i]+vzstokes[i];
+		}
+	}
+	else if(approximation==MacAyealStokesApproximationEnum){
+		Input* vzstokes_input=inputs->GetInput(VzStokesEnum);
+		if (vzstokes_input){
+			if (vzstokes_input->ObjectEnum()!=PentaP1InputEnum) _error_("Cannot compute Vel as VzStokes is of type " << EnumToStringx(vzstokes_input->ObjectEnum()));
+			GetInputListOnVertices(&vzstokes[0],VzStokesEnum);
+		}
+		else _error_("Cannot compute Vz as VzStokes in not present in MacAyealStokes element");
+		for(i=0;i<NUMVERTICES;i++){
+			vzmacayeal[i]=vz[i];
+			vz[i]=vzmacayeal[i]+vzstokes[i];
+		}
+	}
+
+	/*Now Compute vel*/
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
+	 *so the pressure is just the pressure at the z elevation: except it this is a PattynStokes element */
+	if(approximation!=PattynStokesApproximationEnum &&  approximation!=MacAyealStokesApproximationEnum){
+		rho_ice=matpar->GetRhoIce();
+		g=matpar->GetG();
+		GetInputListOnVertices(&surface[0],SurfaceEnum);
+		for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
+	}
+
+	/*Now, we have to move the previous Vz inputs to old 
+	 * status, otherwise, we'll wipe them off and add the new inputs: */
+	this->inputs->ChangeEnum(VzEnum,VzPicardEnum);
+
+	if(approximation!=PattynStokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum){
+		this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+		this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+	}
+	else if(approximation==PattynStokesApproximationEnum){
+		this->inputs->AddInput(new PentaP1Input(VzPattynEnum,vzpattyn));
+	}
+	else if(approximation==MacAyealStokesApproximationEnum){
+		this->inputs->AddInput(new PentaP1Input(VzMacAyealEnum,vzmacayeal));
+	}
+	this->inputs->AddInput(new PentaP1Input(VzEnum,vz));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticStokes {{{*/
+void  Penta::InputUpdateFromSolutionDiagnosticStokes(IssmDouble* solution){
+	
+	const int numdof=NDOF4*NUMVERTICES;
+
+	int     i;
+	IssmDouble  values[numdof];
+	IssmDouble  vx[NUMVERTICES];
+	IssmDouble  vy[NUMVERTICES];
+	IssmDouble  vz[NUMVERTICES];
+	IssmDouble  vel[NUMVERTICES];
+	IssmDouble  pressure[NUMVERTICES];
+	IssmDouble  stokesreconditioning;
+	int*    doflist=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,StokesApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&values[0],nodes,NUMVERTICES,XYZPEnum);
+
+	/*Ok, we have vx and vy in values, fill in all arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		vx[i]=values[i*NDOF4+0];
+		vy[i]=values[i*NDOF4+1];
+		vz[i]=values[i*NDOF4+2];
+		pressure[i]=values[i*NDOF4+3];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vz[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Recondition pressure and compute vel: */
+	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	for(i=0;i<NUMVERTICES;i++) pressure[i]=pressure[i]*stokesreconditioning;
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+	
+	/*Now, we have to move the previous inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(VzEnum,VzPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
+	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
+	this->inputs->AddInput(new PentaP1Input(VzEnum,vz));
+	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_BALANCED_
+/*FUNCTION Penta::CreateKMatrixBalancethickness {{{*/
+ElementMatrix* Penta::CreateKMatrixBalancethickness(void){
+
+	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
+	  bedrock, in which case we spawn a tria element using the 3 first nodes, and use it to build 
+	  the stiffness matrix. */
+	if (!IsOnBed()) return NULL;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Spawn Tria element from the base of the Penta: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementMatrix* Ke=tria->CreateKMatrixBalancethickness();
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorBalancethickness {{{*/
+ElementVector* Penta::CreatePVectorBalancethickness(void){
+
+	if (!IsOnBed()) return NULL;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	ElementVector* pe=tria->CreatePVectorBalancethickness();
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+#endif
+
Index: /issm/trunk/src/c/classes/objects/Elements/Penta.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/Penta.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/Penta.h	(revision 13395)
@@ -0,0 +1,325 @@
+/*! \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 Material;
+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
+		Material    *material;       // 1 material ice
+		Matpar      *matpar;       // 1 material parameter
+		Penta      **verticalneighbors;   // 2 neighbors: first one under, second one above
+		int          horizontalneighborsids[3];
+
+		Parameters  *parameters;   //pointer to solution parameters
+		Inputs      *inputs;
+		Results      *results;
+
+		/*Penta constructors and destructor: {{{*/
+		Penta();
+		Penta(int penta_id,int penta_sid,int i, IoModel* iomodel,int nummodels);
+		~Penta();
+		/*}}}*/
+		/*Object virtual functions definitions: {{{*/
+		Object*   copy();
+		void	  DeepEcho();
+		void	  Echo();
+		int		  ObjectEnum();
+		int		  Id(); 
+		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<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
+		void   BasalFrictionCreateInput(void);
+		void   ComputeBasalStress(Vector<IssmDouble>* sigma_b);
+		void   ComputeStrainRate(Vector<IssmDouble>* 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<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,Vector<IssmDouble>* df);
+		void   CreatePVector(Vector<IssmDouble>* pf);
+		void   CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
+		void   Delta18oParameterization(void);
+		void   DeleteResults(void);
+		int    GetNodeIndex(Node* node);
+		void   GetSolutionFromInputs(Vector<IssmDouble>* solution);
+		IssmDouble GetZcoord(GaussPenta* gauss);
+		void   GetVectorFromInputs(Vector<IssmDouble>* vector,int name_enum);
+		void   GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int name_enum,int interp);
+		
+		int    Sid();
+		void   InputArtificialNoise(int enum_type,IssmDouble min, IssmDouble max);
+		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<IssmDouble>* 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<IssmDouble>* 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<IssmDouble>* 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<IssmDouble>* gradient,int control_type,int control_index);
+		void   GradjDragMacAyeal(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjDragPattyn(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjDragStokes(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjBbarMacAyeal(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjBbarPattyn(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjBbarStokes(Vector<IssmDouble>* gradient,int control_index);
+		void   GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data);
+		void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
+		void   ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index);
+		void   ControlInputScaleGradient(int enum_type,IssmDouble scale);
+		void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
+		IssmDouble RheologyBbarAbsGradient(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);
+		IssmDouble ThicknessAlongGradient( bool process_units,int weight_index){_error_("not supported");};
+		IssmDouble ThicknessAcrossGradient(bool process_units,int weight_index){_error_("not supported");};
+		void   InputControlUpdate(IssmDouble scalar,bool save_parameter);
+		#endif
+		/*}}}*/
+		/*Penta specific routines:{{{*/
+		void	  BedNormal(IssmDouble* bed_normal, IssmDouble xyz_list[3][3]);
+		ElementMatrix* CreateBasalMassMatrix(void);
+		ElementMatrix* CreateKMatrixPrognostic(void);
+		ElementVector* CreatePVectorPrognostic(void);
+		ElementVector* CreatePVectorSlope(void);
+		void	  GetDofList(int** pdoflist,int approximation_enum,int setenum);
+		void	  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<IssmDouble>* solutiong);
+		IssmDouble  GetStabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa);
+		void    GetStrainRate3dPattyn(IssmDouble* epsilon,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input);
+		void    GetStrainRate3d(IssmDouble* epsilon,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input, Input* vz_input);
+		Penta*  GetUpperElement(void);
+		Penta*  GetLowerElement(void);
+		Penta*  GetBasalElement(void);
+		void	  InputExtrude(int enum_type,int object_type);
+		void    InputUpdateFromSolutionPrognostic(IssmDouble* solutiong);
+		void    InputUpdateFromSolutionOneDof(IssmDouble* solutiong,int enum_type);
+		void    InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solutiong,int enum_type);
+		bool	  IsInput(int name);
+		bool	  IsOnSurface(void);
+		bool	  IsOnBed(void);
+		bool    IsFloating(void); 
+		bool    IsNodeOnShelf(); 
+		bool    IsNodeOnShelfFromFlags(IssmDouble* flags);
+		bool    IsOnWater(void); 
+		IssmDouble  MinEdgeLength(IssmDouble xyz_list[6][3]);
+		void	  ReduceMatrixStokes(IssmDouble* Ke_reduced, IssmDouble* Ke_temp);
+		void	  ReduceVectorStokes(IssmDouble* Pe_reduced, IssmDouble* Ke_temp, IssmDouble* Pe_temp);
+		void	  SetClone(int* minranks);
+		Tria*	  SpawnTria(int g0, int g1, int g2);
+		void	  SurfaceNormal(IssmDouble* surface_normal, IssmDouble xyz_list[3][3]);
+
+		#ifdef _HAVE_DIAGNOSTIC_
+		ElementMatrix* CreateKMatrixCouplingMacAyealPattyn(void);
+		ElementMatrix* CreateKMatrixCouplingMacAyealPattynViscous(void);
+		ElementMatrix* CreateKMatrixCouplingMacAyealPattynFriction(void);
+		ElementMatrix* CreateKMatrixCouplingMacAyealStokes(void);
+		ElementMatrix* CreateKMatrixCouplingMacAyealStokesViscous(void);
+		ElementMatrix* CreateKMatrixCouplingMacAyealStokesFriction(void);
+		ElementMatrix* CreateKMatrixCouplingPattynStokes(void);
+		ElementMatrix* CreateKMatrixDiagnosticHoriz(void);
+		ElementMatrix* CreateKMatrixAdjointHoriz(void);
+		ElementVector* CreateDVectorDiagnosticHoriz(void);
+		ElementVector* CreateDVectorDiagnosticStokes(void);
+		ElementMatrix* CreateKMatrixDiagnosticHutter(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyeal2d(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyeal3d(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyeal3dViscous(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyeal3dFriction(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyealPattyn(void);
+		ElementMatrix* CreateKMatrixDiagnosticMacAyealStokes(void);
+		ElementMatrix* CreateKMatrixDiagnosticL1L2(void);
+		ElementMatrix* CreateKMatrixDiagnosticL1L2Viscous(void);
+		ElementMatrix* CreateKMatrixDiagnosticL1L2Friction(void);
+		ElementMatrix* CreateKMatrixDiagnosticPattyn(void);
+		ElementMatrix* CreateKMatrixDiagnosticPattynViscous(void);
+		ElementMatrix* CreateKMatrixDiagnosticPattynFriction(void);
+		ElementMatrix* CreateKMatrixDiagnosticPattynStokes(void);
+		ElementMatrix* CreateKMatrixDiagnosticStokes(void);
+		ElementMatrix* CreateKMatrixDiagnosticStokesViscous(void);
+		ElementMatrix* CreateKMatrixDiagnosticStokesFriction(void);
+		ElementMatrix* CreateKMatrixDiagnosticVert(void);
+		ElementMatrix* CreateKMatrixDiagnosticVertVolume(void);
+		ElementMatrix* CreateKMatrixDiagnosticVertSurface(void);
+		ElementMatrix* CreateJacobianDiagnosticHoriz(void);
+		ElementMatrix* CreateJacobianDiagnosticMacayeal2d(void);
+		ElementMatrix* CreateJacobianDiagnosticPattyn(void);
+		ElementMatrix* CreateJacobianDiagnosticStokes(void);
+		void           InputUpdateFromSolutionDiagnosticHoriz( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticMacAyeal( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticMacAyealPattyn( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticMacAyealStokes( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticL1L2( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticPattyn( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticPattynStokes( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticHutter( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticVert( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionDiagnosticStokes( IssmDouble* solutiong);
+		void	         GetSolutionFromInputsDiagnosticHoriz(Vector<IssmDouble>* solutiong);
+		void	         GetSolutionFromInputsDiagnosticHutter(Vector<IssmDouble>* solutiong);
+		void	         GetSolutionFromInputsDiagnosticStokes(Vector<IssmDouble>* solutiong);
+		void	         GetSolutionFromInputsDiagnosticVert(Vector<IssmDouble>* solutiong);
+		ElementVector* CreatePVectorCouplingMacAyealStokes(void);
+		ElementVector* CreatePVectorCouplingMacAyealStokesViscous(void);
+		ElementVector* CreatePVectorCouplingMacAyealStokesFriction(void);
+		ElementVector* CreatePVectorCouplingPattynStokes(void);
+		ElementVector* CreatePVectorCouplingPattynStokesViscous(void);
+		ElementVector* CreatePVectorCouplingPattynStokesFriction(void);
+		ElementVector* CreatePVectorDiagnosticHoriz(void);
+		ElementVector* CreatePVectorDiagnosticHutter(void);
+		ElementVector* CreatePVectorDiagnosticMacAyeal(void);
+		ElementVector* CreatePVectorDiagnosticMacAyealPattyn(void);
+		ElementVector* CreatePVectorDiagnosticMacAyealStokes(void);
+		ElementVector* CreatePVectorDiagnosticL1L2(void);
+		ElementVector* CreatePVectorDiagnosticPattyn(void);
+		ElementVector* CreatePVectorDiagnosticPattynStokes(void);
+		ElementVector* CreatePVectorDiagnosticStokes(void);
+		ElementVector* CreatePVectorDiagnosticStokesViscous(void);
+		ElementVector* CreatePVectorDiagnosticStokesShelf(void);
+		ElementVector* CreatePVectorDiagnosticVert(void);
+		ElementVector* CreatePVectorDiagnosticVertVolume(void);
+		ElementVector* CreatePVectorDiagnosticVertBase(void);
+		void GetL1L2Viscosity(IssmDouble*, IssmDouble*, GaussPenta*, Input*, Input*, Input*);
+		#endif
+
+		#ifdef _HAVE_CONTROL_
+		ElementVector* CreatePVectorAdjointHoriz(void);
+		ElementMatrix* CreateKMatrixAdjointMacAyeal2d(void);
+		ElementMatrix* CreateKMatrixAdjointPattyn(void);
+		ElementMatrix* CreateKMatrixAdjointStokes(void);
+		ElementVector* CreatePVectorAdjointMacAyeal(void);
+		ElementVector* CreatePVectorAdjointPattyn(void);
+		ElementVector* CreatePVectorAdjointStokes(void);
+		void    InputUpdateFromSolutionAdjointHoriz( IssmDouble* solutiong);
+		void    InputUpdateFromSolutionAdjointStokes( IssmDouble* solutiong);
+		#endif
+
+		#ifdef _HAVE_HYDROLOGY_
+		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<IssmDouble>* solutiong);
+		void           InputUpdateFromSolutionThermal( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionEnthalpy( IssmDouble* solutiong);
+		#endif
+		#ifdef _HAVE_BALANCED_
+		ElementMatrix* CreateKMatrixBalancethickness(void);
+		ElementVector* CreatePVectorBalancethickness(void);
+		#endif
+		/*}}}*/
+};
+#endif  /* _PENTA_H */
Index: /issm/trunk/src/c/classes/objects/Elements/PentaHook.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/PentaHook.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/PentaHook.cpp	(revision 13395)
@@ -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->hmaterial=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 hmaterial;
+	delete hmatpar;
+	delete hneighbors;
+}
+/*}}}*/
+/*FUNCTION PentaHook::PentaHook(int in_numanalyses,int material_id, int matpar_id){{{*/
+PentaHook::PentaHook(int in_numanalyses,int material_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->hmaterial=new Hook(&material_id,1);
+	this->hmatpar=new Hook(&matpar_id,1);
+	this->hneighbors=NULL; 
+
+	//Initialize hnodes as NULL
+	for(int i=0;i<this->numanalyses;i++){
+		this->hnodes[i]=NULL;
+	}
+
+}
+/*}}}*/
+
+/*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 hmaterial. material will be taken care of by Penta
+	triahook->hmaterial=NULL;
+	triahook->hmatpar=(Hook*)this->hmatpar->copy();
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Elements/PentaHook.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/PentaHook.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/PentaHook.h	(revision 13395)
@@ -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*  hmaterial; // 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 material_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/trunk/src/c/classes/objects/Elements/PentaRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/PentaRef.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/PentaRef.cpp	(revision 13395)
@@ -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) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetTriaJacobianDeterminant{{{*/
+void PentaRef::GetTriaJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussPenta* gauss){
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble x1,x2,x3,y1,y2,y3,z1,z2,z3;
+
+	x1=*(xyz_list+3*0+0);
+	y1=*(xyz_list+3*0+1);
+	z1=*(xyz_list+3*0+2);
+	x2=*(xyz_list+3*1+0);
+	y2=*(xyz_list+3*1+1);
+	z2=*(xyz_list+3*1+2);
+	x3=*(xyz_list+3*2+0);
+	y3=*(xyz_list+3*2+1);
+	z3=*(xyz_list+3*2+2);
+
+	/*Jdet = norm( AB ^ AC ) / (2 * area of the reference triangle), with areaRef=sqrt(3) */
+	*Jdet=SQRT3/6.0*pow(pow(((y2-y1)*(z3-z1)-(z2-z1)*(y3-y1)),2.0)+pow(((z2-z1)*(x3-x1)-(x2-x1)*(z3-z1)),2.0)+pow(((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)),2.0),0.5);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetSegmentJacobianDeterminant{{{*/
+void PentaRef::GetSegmentJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussPenta* gauss){
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble x1,x2,y1,y2,z1,z2;
+
+	x1=*(xyz_list+3*0+0);
+	y1=*(xyz_list+3*0+1);
+	z1=*(xyz_list+3*0+2);
+	x2=*(xyz_list+3*1+0);
+	y2=*(xyz_list+3*1+1);
+	z2=*(xyz_list+3*1+2);
+
+	*Jdet=1.0/2.0*sqrt(pow(x2-x1,2.) + pow(y2-y1,2.) + pow(z2-z1,2.));
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetJacobianInvert {{{*/
+void PentaRef::GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussPenta* gauss){
+
+	/*Jacobian*/
+	IssmDouble J[3][3];
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J[0][0], xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	Matrix3x3Invert(Jinv,&J[0][0]);
+}
+/*}}}*/
+/*FUNCTION PentaRef::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) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetInputValue{{{*/
+void PentaRef::GetInputValue(IssmDouble* pvalue,IssmDouble* plist,GaussPenta* gauss){
+	/*P1 interpolation on Gauss point*/
+
+	/*intermediary*/
+	IssmDouble l1l6[6];
+
+	/*nodal functions: */
+	GetNodalFunctionsP1(&l1l6[0],gauss);
+
+	/*Assign output pointers:*/
+	*pvalue=l1l6[0]*plist[0]+l1l6[1]*plist[1]+l1l6[2]*plist[2]+l1l6[3]*plist[3]+l1l6[4]*plist[4]+l1l6[5]*plist[5];
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetInputDerivativeValue{{{*/
+void PentaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussPenta* gauss){
+	/*From node values of parameter p (p_list[0], p_list[1], p_list[2], p_list[3], p_list[4] and p_list[4]), return parameter derivative value at gaussian point specified by gauss_coord:
+	 *   dp/dx=p_list[0]*dh1/dx+p_list[1]*dh2/dx+p_list[2]*dh3/dx+p_list[3]*dh4/dx+p_list[4]*dh5/dx+p_list[5]*dh6/dx;
+	 *   dp/dy=p_list[0]*dh1/dy+p_list[1]*dh2/dy+p_list[2]*dh3/dy+p_list[3]*dh4/dy+p_list[4]*dh5/dy+p_list[5]*dh6/dy;
+	 *   dp/dz=p_list[0]*dh1/dz+p_list[1]*dh2/dz+p_list[2]*dh3/dz+p_list[3]*dh4/dz+p_list[4]*dh5/dz+p_list[5]*dh6/dz;
+	 *
+	 *   p is a vector of size 3x1 already allocated.
+	 */
+	IssmDouble dh1dh6[3][NUMNODESP1];
+
+	/*Get nodal funnctions derivatives in actual coordinate system: */
+	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list, gauss);
+
+	/*Assign output*/
+	p[0]=plist[0]*dh1dh6[0][0]+plist[1]*dh1dh6[0][1]+plist[2]*dh1dh6[0][2]+plist[3]*dh1dh6[0][3]+plist[4]*dh1dh6[0][4]+plist[5]*dh1dh6[0][5];
+	p[1]=plist[0]*dh1dh6[1][0]+plist[1]*dh1dh6[1][1]+plist[2]*dh1dh6[1][2]+plist[3]*dh1dh6[1][3]+plist[4]*dh1dh6[1][4]+plist[5]*dh1dh6[1][5];
+	p[2]=plist[0]*dh1dh6[2][0]+plist[1]*dh1dh6[2][1]+plist[2]*dh1dh6[2][2]+plist[3]*dh1dh6[2][3]+plist[4]*dh1dh6[2][4]+plist[5]*dh1dh6[2][5];
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Elements/PentaRef.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/PentaRef.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/PentaRef.h	(revision 13395)
@@ -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){_error_("only PentaGauss are supported");};
+		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, GaussTria* gauss){_error_("only PentaGauss are supported");};
+
+};
+#endif
Index: /issm/trunk/src/c/classes/objects/Elements/Tria.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/Tria.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/Tria.cpp	(revision 13395)
@@ -0,0 +1,5965 @@
+/*!\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->material=NULL;
+	this->matpar=NULL;
+	for(i=0;i<3;i++)this->horizontalneighborsids[i]=UNDEF;
+	this->inputs=NULL;
+	this->parameters=NULL;
+	this->results=NULL;
+
+}
+/*}}}*/
+/*FUNCTION Tria::Tria(int id, int sid,int index, IoModel* iomodel,int nummodels){{{*/
+Tria::Tria(int tria_id, int tria_sid, int index, IoModel* iomodel,int nummodels)
+	:TriaRef(nummodels)
+	,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->material=NULL;
+		this->matpar=NULL;
+
+}
+/*}}}*/
+/*FUNCTION Tria::~Tria(){{{*/
+Tria::~Tria(){
+	delete inputs;
+	delete results;
+	this->parameters=NULL;
+}
+/*}}}*/
+/*FUNCTION Tria::copy {{{*/
+Object* Tria::copy() {
+
+	int i;
+	Tria* tria=NULL;
+
+	tria=new Tria();
+
+	//deal with TriaRef mother class
+	tria->element_type_list=xNew<int>(this->numanalyses);
+	for(i=0;i<this->numanalyses;i++) tria->element_type_list[i]=this->element_type_list[i];
+
+	//deal with 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->hmaterial=(Hook*)this->hmaterial->copy();
+	tria->hmatpar=(Hook*)this->hmatpar->copy();
+
+	/*deal with Tria fields: */
+	tria->id=this->id;
+	tria->sid=this->sid;
+	if(this->inputs){
+		tria->inputs=(Inputs*)this->inputs->Copy();
+	}
+	else{
+		tria->inputs=new Inputs();
+	}
+	if(this->results){
+		tria->results=(Results*)this->results->Copy();
+	}
+	else{
+		tria->results=new Results();
+	}
+	/*point parameters: */
+	tria->parameters=this->parameters;
+
+	/*recover objects: */
+	tria->nodes=xNew<Node*>(3); //we cannot rely on an analysis_counter to tell us which analysis_type we are running, so we just copy the nodes.
+	for(i=0;i<3;i++)tria->nodes[i]=this->nodes[i];
+	tria->material=(Material*)tria->hmaterial->delivers();
+	tria->matpar=(Matpar*)tria->hmatpar->delivers();
+
+	/*neighbors: */
+	for(i=0;i<3;i++)tria->horizontalneighborsids[i]=this->horizontalneighborsids[i];
+
+	return tria;
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION Tria::AverageOntoPartition {{{*/
+void  Tria::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){
+
+	bool      already=false;
+	int       i,j;
+	int       partition[NUMVERTICES];
+	int       offsetsid[NUMVERTICES];
+	int       offsetdof[NUMVERTICES];
+	IssmDouble    area;
+	IssmDouble    mean;
+	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<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,Vector<IssmDouble>* df){
+
+	/*retreive parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging mode{{{*/
+	_assert_(this->nodes && this->material && this->matpar && this->parameters && this->inputs);
+	/*}}}*/
+	
+	/*Skip if water element*/
+	if(IsOnWater()) return;
+
+	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum:
+			Ke=CreateKMatrixDiagnosticMacAyeal();
+			break;
+		case AdjointHorizAnalysisEnum:
+			Ke=CreateKMatrixAdjointMacAyeal();
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			Ke=CreateKMatrixDiagnosticHutter();
+			break;
+		 #endif
+		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+			Ke=CreateMassMatrix();
+			break;
+		case PrognosticAnalysisEnum:
+			Ke=CreateKMatrixPrognostic();
+			break;
+		#ifdef _HAVE_HYDROLOGY_
+		case HydrologyAnalysisEnum:
+			Ke=CreateKMatrixHydrology();
+			break;
+		#endif
+		#ifdef _HAVE_BALANCED_
+		case BalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixBalancethickness();
+			break;
+		#endif
+		#ifdef _HAVE_CONTROL_
+		case AdjointBalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixAdjointBalancethickness();
+			break;
+		#endif
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::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:
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixPrognostic_CG {{{*/
+ElementMatrix* Tria::CreateKMatrixPrognostic_CG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        stabilization;
+	int        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(vx*vx+vy*vy)+1.e-8;
+			K[0][0]=h/(2*vel)*vx*vx;
+			K[1][0]=h/(2*vel)*vy*vx;
+			K[0][1]=h/(2*vel)*vx*vy;
+			K[1][1]=h/(2*vel)*vy*vy;
+		}
+		else if(stabilization==1){
+			/*MacAyeal*/
+			vxaverage_input->GetInputAverage(&vx);
+			vyaverage_input->GetInputAverage(&vy);
+			K[0][0]=h/2.0*fabs(vx);
+			K[0][1]=0.;
+			K[1][0]=0.;
+			K[1][1]=h/2.0*fabs(vy);
+		}
+		if(stabilization==1 || stabilization==2){
+			KDL[0][0]=DL_scalar*K[0][0];
+			KDL[1][0]=DL_scalar*K[1][0];
+			KDL[0][1]=DL_scalar*K[0][1];
+			KDL[1][1]=DL_scalar*K[1][1];
+			TripleMultiply( &Bprime[0][0],2,numdof,1,
+						&KDL[0][0],2,2,0,
+						&Bprime[0][0],2,numdof,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixPrognostic_DG {{{*/
+ElementMatrix* Tria::CreateKMatrixPrognostic_DG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        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::CreateMassMatrix {{{*/
+ElementMatrix* Tria::CreateMassMatrix(void){
+
+	/*constants: */
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/* Intermediaries */
+	IssmDouble  D,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(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		
+		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
+		D=gauss->weight*Jdet;
+
+		GetL(&L[0][0], &xyz_list[0][0], gauss,NDOF1);
+
+		TripleMultiply(&L[0][0],1,3,1,
+					&D,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<IssmDouble>* pf){
+
+	/*retrive parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*asserts: {{{*/
+	/*if debugging mode, check that all pointers exist*/
+	_assert_(this->nodes && this->material && this->matpar && this->parameters && this->inputs);
+	/*}}}*/
+	
+	/*Skip if water element*/
+	if(IsOnWater()) return;
+
+	/*Just branch to the correct load generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum:
+			pe=CreatePVectorDiagnosticMacAyeal();
+			break;
+		case DiagnosticHutterAnalysisEnum:
+			pe=CreatePVectorDiagnosticHutter();
+			break;
+		#endif
+		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
+			pe=CreatePVectorSlope();
+			break;
+		case PrognosticAnalysisEnum:
+			pe=CreatePVectorPrognostic();
+			break;
+		#ifdef _HAVE_HYDROLOGY_
+		case 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:
+			_error_("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:
+			_error_("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<IssmDouble>* Jff){
+
+	/*retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Checks in debugging {{{*/
+	_assert_(this->nodes && this->material && this->matpar && this->parameters && this->inputs);
+	/*}}}*/
+
+	/*Skip if water element*/
+	if(IsOnWater()) return;
+
+	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum:
+			Ke=CreateJacobianDiagnosticMacayeal();
+			break;
+#endif
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Jff);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::ComputeBasalStress {{{*/
+void  Tria::ComputeBasalStress(Vector<IssmDouble>* eps){
+	_error_("Not Implemented yet");
+}
+/*}}}*/
+/*FUNCTION Tria::ComputeStrainRate {{{*/
+void  Tria::ComputeStrainRate(Vector<IssmDouble>* eps){
+	_error_("Not Implemented yet");
+}
+/*}}}*/
+/*FUNCTION Tria::ComputeStressTensor {{{*/
+void  Tria::ComputeStressTensor(){
+
+	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);
+		material->GetViscosity2d(&viscosity,&epsilon[0]);
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*Compute Stress*/
+		sigma_xx[iv]=2*viscosity*epsilon[0]-pressure; // sigma = nu eps - pressure
+		sigma_yy[iv]=2*viscosity*epsilon[1]-pressure;
+		sigma_xy[iv]=2*viscosity*epsilon[2];
+	}
+	
+	/*Add Stress tensor components into inputs*/
+	this->inputs->AddInput(new 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->hmaterial->configure(materialsin);
+	this->hmatpar->configure(materialsin);
+
+	/*Now, go pick up the objects inside the hooks: */
+	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+	this->material=(Material*)this->hmaterial->delivers();
+	this->matpar=(Matpar*)this->hmatpar->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+	/*get inputs configured too: */
+	this->inputs->Configure(parameters);
+
+}
+/*}}}*/
+/*FUNCTION Tria::DeepEcho{{{*/
+void Tria::DeepEcho(void){
+
+	_printLine_("Tria:");
+	_printLine_("   id: " << id);
+	if(nodes){
+		nodes[0]->DeepEcho();
+		nodes[1]->DeepEcho();
+		nodes[2]->DeepEcho();
+	}
+	else _printLine_("nodes = NULL");
+
+	if (material) material->DeepEcho();
+	else _printLine_("material = 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 tmp[NUMVERTICES];
+	IssmDouble Delta18oPresent,Delta18oLgm,Delta18oTime;
+	IssmDouble Delta18oSurfacePresent,Delta18oSurfaceLgm,Delta18oSurfaceTime;
+	IssmDouble time,yts,finaltime;
+
+	/*Recover parameters*/
+	this->parameters->FindParam(&time,TimeEnum);
+	this->parameters->FindParam(&yts,ConstantsYtsEnum);
+	this->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
+
+	/*Recover present day temperature and precipitation*/
+	Input* input=inputs->GetInput(SurfaceforcingsTemperaturesPresentdayEnum);    _assert_(input);
+	Input* input2=inputs->GetInput(SurfaceforcingsTemperaturesLgmEnum);          _assert_(input2);
+	Input* input3=inputs->GetInput(SurfaceforcingsPrecipitationsPresentdayEnum); _assert_(input3);
+	GaussTria* gauss=new GaussTria();
+	for(int month=0;month<12;month++){
+		for(int iv=0;iv<NUMVERTICES;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&TemperaturesPresentday[iv][month],gauss,month/12.*yts);
+			input2->GetInputValue(&TemperaturesLgm[iv][month],gauss,month/12.*yts);
+			input3->GetInputValue(&PrecipitationsPresentday[iv][month],gauss,month/12.*yts);
+			PrecipitationsPresentday[iv][month]=PrecipitationsPresentday[iv][month]/yts; // converion in m/sec
+		}
+	}
+
+	/*Recover delta18o and Delta18oSurface at present day, lgm and at time t*/
+	this->parameters->FindParam(&Delta18oPresent,SurfaceforcingsDelta18oEnum,finaltime);
+	this->parameters->FindParam(&Delta18oLgm,SurfaceforcingsDelta18oEnum,(finaltime-(21000*yts)));
+	this->parameters->FindParam(&Delta18oTime,SurfaceforcingsDelta18oEnum,time);
+	this->parameters->FindParam(&Delta18oSurfacePresent,SurfaceforcingsDelta18oSurfaceEnum,finaltime);
+	this->parameters->FindParam(&Delta18oSurfaceLgm,SurfaceforcingsDelta18oSurfaceEnum,(finaltime-(21000*yts)));
+	this->parameters->FindParam(&Delta18oSurfaceTime,SurfaceforcingsDelta18oSurfaceEnum,time);
+	
+	/*Compute the temperature and precipitation*/
+	for(int iv=0;iv<NUMVERTICES;iv++){
+		ComputeDelta18oTemperaturePrecipitation(Delta18oSurfacePresent, Delta18oSurfaceLgm, Delta18oSurfaceTime, 
+					Delta18oPresent, Delta18oLgm, Delta18oTime,
+					&PrecipitationsPresentday[iv][0], 
+					&TemperaturesLgm[iv][0], &TemperaturesPresentday[iv][0], 
+					&monthlytemperatures[iv][0], &monthlyprec[iv][0]);
+	}
+
+	/*Update inputs*/ 
+	TransientInput* NewTemperatureInput = new TransientInput(SurfaceforcingsMonthlytemperaturesEnum);
+	TransientInput* NewPrecipitationInput = new TransientInput(SurfaceforcingsPrecipitationEnum);
+	for (int imonth=0;imonth<12;imonth++) {
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlytemperatures[i][imonth];
+		TriaP1Input* newmonthinput1 = new TriaP1Input(SurfaceforcingsMonthlytemperaturesEnum,&tmp[0]);
+		NewTemperatureInput->AddTimeInput(newmonthinput1,time+imonth/12.*yts);
+
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlyprec[i][imonth];
+		TriaP1Input* newmonthinput2 = new TriaP1Input(SurfaceforcingsPrecipitationEnum,&tmp[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 (material) material->Echo();
+	else _printLine_("material = 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;
+	}
+	_error_("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) _error_("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) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+
+	GaussTria* gauss=new GaussTria();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::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<IssmDouble>* solution){
+
+	/*retrive parameters: */
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Just branch to the correct InputUpdateFromSolution generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+	#ifdef _HAVE_DIAGNOSTIC_
+	case DiagnosticHorizAnalysisEnum:
+		GetSolutionFromInputsDiagnosticHoriz(solution);
+		break;
+	case DiagnosticHutterAnalysisEnum:
+		GetSolutionFromInputsDiagnosticHutter(solution);
+		break;
+	#endif
+	#ifdef _HAVE_HYDROLOGY_
+	case HydrologyAnalysisEnum:
+		GetSolutionFromInputsHydrology(solution);
+		break;
+	#endif
+	default:
+		_error_("analysis: " << EnumToStringx(analysis_type) << " not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::GetStrainRate2d(IssmDouble* epsilon,IssmDouble* xyz_list, GaussTria* gauss, Input* vx_input, Input* vy_input){{{*/
+void Tria::GetStrainRate2d(IssmDouble* epsilon,IssmDouble* xyz_list, GaussTria* gauss, Input* vx_input, Input* vy_input){
+	/*Compute the 2d Strain Rate (3 components):
+	 * epsilon=[exx eyy exy] */
+
+	int i;
+	IssmDouble epsilonvx[3];
+	IssmDouble epsilonvy[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetVxStrainRate2d(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate2d(epsilonvy,xyz_list,gauss);
+
+	/*Sum all contributions*/
+	for(i=0;i<3;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i];
+}
+/*}}}*/
+/*FUNCTION Tria::GetVectorFromInputs{{{*/
+void  Tria::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
+
+	int 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) _error_("Input " << EnumToStringx(input_enum) << " not found in element");
+
+	/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
+	input->GetVectorFromInputs(vector,&doflist1[0]);
+}
+/*}}}*/
+/*FUNCTION Tria::GetVectorFromResults{{{*/
+void  Tria::GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int enum_in,int interp){
+
+	/*Get result*/
+	ElementResult* elementresult=(ElementResult*)this->results->GetObjectByOffset(offset);
+	if(elementresult->InstanceEnum()!=enum_in){
+		_error_("Results of offset "<<offset<<" is "<<EnumToStringx(elementresult->InstanceEnum())<<" when "<<EnumToStringx(enum_in)<<" was expected");
+	}
+	if(interp==P1Enum){
+		int 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)_error_("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])_error_("could not find input with enum " << EnumToStringx(enums[2*i+0]));
+		if(!old_inputs[i])_error_("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->material->inputs->GetInput(enum_type);
+	else
+	 _error_("object " << EnumToStringx(object_enum) << " not supported yet");
+	if(!oldinput)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
+	newinput=(Input*)oldinput->copy();
+
+	/*Assign new name (average)*/
+	newinput->ChangeEnum(average_enum_type);
+
+	/*Add new input to current element*/
+	if (object_enum==MeshElementsEnum)
+	 this->inputs->AddInput((Input*)newinput);
+	else if (object_enum==MaterialsEnum)
+	 this->material->inputs->AddInput((Input*)newinput);
+	else
+	 _error_("object " << EnumToStringx(object_enum) << " not supported yet");
+}
+/*}}}*/
+/*FUNCTION Tria::InputDuplicate{{{*/
+void  Tria::InputDuplicate(int original_enum,int new_enum){
+
+	/*Call inputs method*/
+	if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputScale{{{*/
+void  Tria::InputScale(int enum_type,IssmDouble scale_factor){
+
+	Input* input=NULL;
+
+	/*Make a copy of the original input: */
+	input=(Input*)this->inputs->GetInput(enum_type);
+	if(!input)_error_("could not find old input with enum: " << EnumToStringx(enum_type));
+
+	/*Scale: */
+	input->Scale(scale_factor);
+}
+/*}}}*/
+/*FUNCTION Tria::InputToResult{{{*/
+void  Tria::InputToResult(int enum_type,int step,IssmDouble time){
+
+	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 || enum_type==MaterialsRheologyZbarEnum) input=this->material->inputs->GetInput(enum_type);
+	else input=this->inputs->GetInput(enum_type);
+	//if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found in tria->inputs");
+	if(!input)return;
+
+	/*If we don't find it, no big deal, just don't do the transfer. Otherwise, build a new Result 
+	 * object out of the input, with the additional step and time information: */
+	this->results->AddObject((Object*)input->SpawnResult(step,time));
+	
+	#ifdef _HAVE_CONTROL_
+	if(input->ObjectEnum()==ControlInputEnum){
+		if(((ControlInput*)input)->gradient!=NULL) this->results->AddObject((Object*)((ControlInput*)input)->SpawnGradient(step,time));
+	}
+	#endif
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromConstant(int value, int name);{{{*/
+void  Tria::InputUpdateFromConstant(int constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new IntInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromConstant(IssmDouble value, int name);{{{*/
+void  Tria::InputUpdateFromConstant(IssmDouble constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new DoubleInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromConstant(bool value, int name);{{{*/
+void  Tria::InputUpdateFromConstant(bool constant, int name){
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	/*update input*/
+	this->inputs->AddInput(new BoolInput(name,constant));
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromIoModel{{{*/
+void Tria::InputUpdateFromIoModel(int index, IoModel* iomodel){ //i is the element index
+
+	/*Intermediaries*/
+	int        i,j;
+	int        tria_vertex_ids[3];
+	IssmDouble nodeinputs[3];
+	IssmDouble cmmininputs[3];
+	IssmDouble cmmaxinputs[3];
+	bool       control_analysis   = false;
+	int        num_control_type;
+	IssmDouble yts;
+	int        num_cm_responses;
+   
+	/*Get parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum); 
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+	if(control_analysis) iomodel->Constant(&num_cm_responses,InversionNumCostFunctionsEnum);
+
+	/*Recover vertices ids needed to initialize inputs*/
+	for(i=0;i<3;i++){ 
+		tria_vertex_ids[i]=reCast<int>(iomodel->Data(MeshElementsEnum)[3*index+i]); //ids for vertices are in the elements array from Matlab
+	}
+
+	/*Control Inputs*/
+	#ifdef _HAVE_CONTROL_
+	if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+		for(i=0;i<num_control_type;i++){
+			switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
+				case BalancethicknessThickeningRateEnum:
+					if (iomodel->Data(BalancethicknessThickeningRateEnum)){
+						for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(BalancethicknessThickeningRateEnum)[tria_vertex_ids[j]-1]/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:
+				case MaterialsRheologyZbarEnum:
+					/*Material will take care of it*/ break;
+				default:
+					_error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
+			}
+		}
+	}
+	#endif
+
+	/*DatasetInputs*/
+	if (control_analysis && iomodel->Data(InversionCostFunctionsCoefficientsEnum)){
+
+		/*Create inputs and add to DataSetInput*/
+		DatasetInput* datasetinput=new DatasetInput(InversionCostFunctionsCoefficientsEnum);
+		for(i=0;i<num_cm_responses;i++){
+			for(j=0;j<3;j++)nodeinputs[j]=iomodel->Data(InversionCostFunctionsCoefficientsEnum)[(tria_vertex_ids[j]-1)*num_cm_responses+i];
+			datasetinput->inputs->AddObject(new 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:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionOneDof{{{*/
+void  Tria::InputUpdateFromSolutionOneDof(IssmDouble* solution,int enum_type){
+
+	const int numdof          = NDOF1*NUMVERTICES;
+
+	int*      doflist=NULL;
+	IssmDouble    values[numdof];
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new 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])) _error_("NaN found in solution vector");
+		/*Constrain thickness to be at least 1m*/
+		if(newthickness[i]<minthickness) newthickness[i]=minthickness;
+	}
+
+	/*Get previous bed, thickness and surface*/
+	GetInputListOnVertices(&oldbed[0],BedEnum);
+	GetInputListOnVertices(&oldsurface[0],SurfaceEnum);
+	GetInputListOnVertices(&oldthickness[0],ThicknessEnum);
+
+	/*Fing PrognosticHydrostaticAdjustment to figure out how to update the geometry:*/
+	this->parameters->FindParam(&hydroadjustment,PrognosticHydrostaticAdjustmentEnum);
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	for(i=0;i<numdof;i++) {
+		/*If shelf: hydrostatic equilibrium*/
+		if (this->nodes[i]->IsGrounded()){
+			newsurface[i]=oldbed[i]+newthickness[i]; //surface = oldbed + newthickness
+			newbed[i]=oldbed[i];               //same bed: do nothing
+		}
+		else{ //this is an ice shelf
+
+			if(hydroadjustment==AbsoluteEnum){
+				newsurface[i]=newthickness[i]*(1-rho_ice/rho_water);
+				newbed[i]=newthickness[i]*(-rho_ice/rho_water);
+			}
+			else if(hydroadjustment==IncrementalEnum){
+				newsurface[i]=oldsurface[i]+(1.0-rho_ice/rho_water)*(newthickness[i]-oldthickness[i]); //surface = oldsurface + (1-di) * dH 
+				newbed[i]=oldbed[i]-rho_ice/rho_water*(newthickness[i]-oldthickness[i]); //bed = oldbed + di * dH
+			}
+			else _error_("Hydrostatic adjustment " << hydroadjustment << " (" << EnumToStringx(hydroadjustment) << ") not supported yet");
+		}
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new 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 || name==MaterialsRheologyZEnum || name==MaterialsRheologyZbarEnum){
+				material->inputs->AddInput(new TriaP1Input(name,values));
+			}
+			else{
+				this->inputs->AddInput(new TriaP1Input(name,values));
+			}
+			return;
+		}
+		default:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVector(int* vector, int name, int type);{{{*/
+void  Tria::InputUpdateFromVector(int* vector, int name, int type){
+	_error_("not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVector(bool* vector, int name, int type);{{{*/
+void  Tria::InputUpdateFromVector(bool* vector, int name, int type){
+	_error_("not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Tria::InputCreate(IssmDouble scalar,int enum,int code);{{{*/
+void Tria::InputCreate(IssmDouble scalar,int name,int code){
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+	
+	if ((code==5) || (code==1)){ //boolean
+		this->inputs->AddInput(new BoolInput(name,reCast<bool>(scalar)));
+	}
+	else if ((code==6) || (code==2)){ //integer
+		this->inputs->AddInput(new IntInput(name,reCast<int>(scalar)));
+	}
+	else if ((code==7) || (code==3)){ //IssmDouble
+		this->inputs->AddInput(new DoubleInput(name,reCast<int>(scalar)));
+	}
+	else _error_("could not recognize nature of vector from code " << code);
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputCreate(IssmDouble* vector,int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){{{*/
+void Tria::InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code){//index into elements
+
+	/*Intermediaries*/
+	int    i,j,t;
+	int    tria_vertex_ids[3];
+	int    row;
+	IssmDouble nodeinputs[3];
+	IssmDouble time;
+	TransientInput* transientinput=NULL;
+	int    numberofvertices;
+	int    numberofelements;
+	IssmDouble yts;
+
+
+	/*Fetch parameters: */
+	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+
+	/*Branch on type of vector: nodal or elementary: */
+	if(vector_type==1){ //nodal vector
+
+		/*Recover vertices ids needed to initialize inputs*/
+		for(i=0;i<3;i++){ 
+			_assert_(iomodel->Data(MeshElementsEnum));
+			tria_vertex_ids[i]=reCast<int>(iomodel->Data(MeshElementsEnum)[3*index+i]); //ids for vertices are in the elements array from Matlab
+		}
+
+		/*Are we in transient or static? */
+		if(M==numberofvertices){
+
+			/*create input values: */
+			for(i=0;i<3;i++)nodeinputs[i]=(IssmDouble)vector[tria_vertex_ids[i]-1];
+
+			/*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 _error_("nodal vector is either numberofnodes or numberofnodes+1 long. Field provided (" << EnumToStringx(vector_enum) << ") is " << M << " long");
+	}
+	else if(vector_type==2){ //element vector
+		/*Are we in transient or static? */
+		if(M==numberofelements){
+
+			/*static mode: create an input out of the element value: */
+
+			if (code==5){ //boolean
+				this->inputs->AddInput(new BoolInput(vector_enum,reCast<bool>(vector[index])));
+			}
+			else if (code==6){ //integer
+				this->inputs->AddInput(new IntInput(vector_enum,reCast<int>(vector[index])));
+			}
+			else if (code==7){ //IssmDouble
+				this->inputs->AddInput(new DoubleInput(vector_enum,vector[index]));
+			}
+			else _error_("could not recognize nature of vector from code " << code);
+		}
+		else {
+			_error_("transient elementary inputs not supported yet!");
+		}
+	}
+	else{
+		_error_("Cannot add input for vector type " << vector_type << " (not supported)");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::IsInput{{{*/
+bool Tria::IsInput(int name){
+	if (
+				name==ThicknessEnum ||
+				name==SurfaceEnum ||
+				name==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==MaterialsRheologyZbarEnum ||
+				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<IssmDouble>* 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();
+
+   /*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){
+
+	_error_("not implemented yet");
+}
+/*}}}*/
+/*FUNCTION Tria::SmearFunction {{{*/
+void  Tria::SmearFunction(Vector<IssmDouble>*  smearedvector,IssmDouble (*WeightFunction)(IssmDouble distance,IssmDouble radius),IssmDouble radius){
+	_error_("not implemented yet");
+
+}
+/*}}}*/
+/*FUNCTION Tria::SmbGradients{{{*/
+void Tria::SmbGradients(void){
+
+	int i;
+
+	// input
+   IssmDouble h[NUMVERTICES];					// ice thickness (m)		
+	IssmDouble s[NUMVERTICES];					// surface elevation (m)
+	IssmDouble 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){
+
+	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(int i=0;i<3;i++){
+		v13[i]=xyz_list[0][i]-xyz_list[2][i];
+		v23[i]=xyz_list[1][i]-xyz_list[2][i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+
+	S = 0.5 * sqrt(normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]);
+
+	/*Return: */
+	return S;
+}
+/*}}}*/
+/*FUNCTION Tria::SurfaceNormal{{{*/
+void Tria::SurfaceNormal(IssmDouble* surface_normal, IssmDouble xyz_list[3][3]){
+
+	IssmDouble v13[3],v23[3];
+	IssmDouble normal[3];
+	IssmDouble normal_norm;
+
+	for(int i=0;i<3;i++){
+		v13[i]=xyz_list[0][i]-xyz_list[2][i];
+		v23[i]=xyz_list[1][i]-xyz_list[2][i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+
+	normal_norm=sqrt( normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]);
+
+	*(surface_normal+0) = normal[0]/normal_norm;
+	*(surface_normal+1) = normal[1]/normal_norm;
+	*(surface_normal+2) = normal[2]/normal_norm;
+}
+/*}}}*/
+/*FUNCTION Tria::TimeAdapt{{{*/
+IssmDouble  Tria::TimeAdapt(void){
+
+	/*intermediary: */
+	int    i;
+	IssmDouble C,dt;
+	IssmDouble dx,dy;
+	IssmDouble maxx,minx;
+	IssmDouble maxy,miny;
+	IssmDouble maxabsvx,maxabsvy;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*get CFL coefficient:*/
+	this->parameters->FindParam(&C,TimesteppingCflCoefficientEnum);
+
+	/*Get for Vx and Vy, the max of abs value: */
+	#ifdef _HAVE_RESPONSES_
+	this->MaxAbsVx(&maxabsvx,false);
+	this->MaxAbsVy(&maxabsvy,false);
+	#else
+		_error_("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<IssmDouble>* 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 (reCast<int>(*(segment+4))!=this->id)_error_("error message: segment with id " << reCast<int>(*(segment+4)) << " does not belong to element with id:" << this->id);
+
+	/*Recover segment node locations: */
+	x1=*(segment+0); y1=*(segment+1); x2=*(segment+2); y2=*(segment+3);
+
+	/*Get xyz list: */
+	GetVerticesCoordinates(&xyz_list[0][0], 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)+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->material->GetBbar();
+			break;
+		case MaterialsRheologyZbarEnum:
+			*presponse=this->material->GetZbar();
+			break;
+		case VelEnum:{
+
+			/*Get input:*/
+			IssmDouble vel;
+			Input* vel_input;
+
+			vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+			vel_input->GetInputAverage(&vel);
+
+			/*process units if requested: */
+			if(process_units) vel=UnitConversion(vel,IuToExtEnum,VelEnum);
+
+			/*Assign output pointers:*/
+			*presponse=vel;}
+			break;
+		default:  
+			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::TotalSmb {{{*/
+IssmDouble Tria::TotalSmb(void){
+
+	/*The smb[kg yr-1] of one element is area[m2] * smb [kg m^-2 yr^-1]*/
+	IssmDouble base,smb,rho_ice;
+	IssmDouble Total_Smb=0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetRhoIce();
+
+   if(IsOnWater())return 0;
+
+	GetVerticesCoordinates(&xyz_list[0][0], 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);
+		material->GetViscosity2d(&viscosity, &epsilon[0]);
+		material->GetViscosity2d(&oldviscosity, &oldepsilon[0]);
+		thickness_input->GetInputValue(&thickness, gauss);
+
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		D_scalar=2*newviscosity*thickness*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][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(slope[0]*slope[0]+slope[1]*slope[1]);
+		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=material->GetN();
+	B=material->GetBbar();
+	Input* slopex_input=inputs->GetInput(SurfaceSlopeXEnum); _assert_(slopex_input);
+	Input* slopey_input=inputs->GetInput(SurfaceSlopeYEnum); _assert_(slopey_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);  _assert_(thickness_input);
+
+	/*Spawn 3 sing elements: */
+	gauss=new GaussTria();
+	for(i=0;i<NUMVERTICES;i++){
+
+		gauss->GaussVertex(i);
+
+		connectivity=nodes[i]->GetConnectivity();
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		slopex_input->GetInputValue(&slope[0],gauss);
+		slopey_input->GetInputValue(&slope[1],gauss);
+		slope2=pow(slope[0],2)+pow(slope[1],2);
+
+		constant_part=-2*pow(rho_ice*gravity,n)*pow(slope2,((n-1)/2));
+
+		ub=-1.58*pow((IssmDouble)10.0,(IssmDouble)-10.0)*rho_ice*gravity*thickness*slope[0];
+		vb=-1.58*pow((IssmDouble)10.0,(IssmDouble)-10.0)*rho_ice*gravity*thickness*slope[1];
+
+		pe->values[2*i]  =(ub-2.0*pow(rho_ice*gravity,n)*pow(slope2,((n-1)/2.0))*pow(thickness,n)/(pow(B,n)*(n+1))*slope[0])/(IssmDouble)connectivity;
+		pe->values[2*i+1]=(vb-2.0*pow(rho_ice*gravity,n)*pow(slope2,((n-1)/2.0))*pow(thickness,n)/(pow(B,n)*(n+1))*slope[1])/(IssmDouble)connectivity;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateJacobianDiagnosticMacayeal{{{*/
+ElementMatrix* Tria::CreateJacobianDiagnosticMacayeal(void){
+
+	/*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);
+		material->GetViscosity2dDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=2*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
+		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
+
+		for(i=0;i<3;i++){
+			for(j=0;j<3;j++){
+				eps1dotdphii=eps1[0]*dphi[0][i]+eps1[1]*dphi[1][i];
+				eps1dotdphij=eps1[0]*dphi[0][j]+eps1[1]*dphi[1][j];
+				eps2dotdphii=eps2[0]*dphi[0][i]+eps2[1]*dphi[1][i];
+				eps2dotdphij=eps2[0]*dphi[0][j]+eps2[1]*dphi[1][j];
+
+				Ke->values[6*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*thickness*eps1dotdphij*eps1dotdphii;
+				Ke->values[6*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*thickness*eps2dotdphij*eps1dotdphii;
+				Ke->values[6*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*thickness*eps1dotdphij*eps2dotdphii;
+				Ke->values[6*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*thickness*eps2dotdphij*eps2dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::GetSolutionFromInputsDiagnosticHoriz{{{*/
+void  Tria::GetSolutionFromInputsDiagnosticHoriz(Vector<IssmDouble>* 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<IssmDouble>* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	int        i;
+	IssmDouble     vx,vy;
+	IssmDouble     values[numdof];
+	int       *doflist = NULL;
+	GaussTria *gauss   = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Get inputs*/
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	/*P1 element only for now*/
+	gauss=new GaussTria();
+	for(i=0;i<NUMVERTICES;i++){
+
+		gauss->GaussVertex(i);
+
+		/*Recover vx and vy*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		values[i*NDOF2+0]=vx;
+		values[i*NDOF2+1]=vy;
+	}
+
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionDiagnosticHoriz {{{*/
+void  Tria::InputUpdateFromSolutionDiagnosticHoriz(IssmDouble* solution){
+	
+	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])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz and compute vel*/
+	GetInputListOnVertices(&vz[0],VzEnum,0);
+	for(i=0;i<NUMVERTICES;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 2D, 
+	 *so the pressure is just the pressure at the bedrock: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	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])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Now Compute vel*/
+	GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
+	for(i=0;i<NUMVERTICES;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 2D, 
+	 *so the pressure is just the pressure at the bedrock: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	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 || control_type[i]==MaterialsRheologyZbarEnum){
+			input=(Input*)material->inputs->GetInput(control_type[i]); _assert_(input);
+		}
+		else{
+			input=(Input*)this->inputs->GetInput(control_type[i]);   _assert_(input);
+		}
+
+		if (input->ObjectEnum()!=ControlInputEnum){
+			_error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
+		}
+
+		((ControlInput*)input)->UpdateValue(scalar);
+		((ControlInput*)input)->Constrain();
+		if (save_parameter) ((ControlInput*)input)->SaveValue();
+
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(control_type);
+}
+/*}}}*/
+/*FUNCTION Tria::ControlInputGetGradient{{{*/
+void Tria::ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){
+
+	int doflist1[NUMVERTICES];
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(enum_type);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&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 || enum_type==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(enum_type);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	((ControlInput*)input)->ScaleGradient(scale);
+}/*}}}*/
+/*FUNCTION Tria::ControlInputSetGradient{{{*/
+void Tria::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){
+
+	int    doflist1[NUMVERTICES];
+	IssmDouble grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(enum_type);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&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<IssmDouble>* gradient,int control_type,int control_index){
+	/*dJ/dalpha = ∂L/∂alpha = ∂J/∂alpha + ∂/∂alpha(KU-F)*/
+
+	/*If on water, grad = 0: */
+	if(IsOnWater()) return;
+
+	/*First deal with ∂/∂alpha(KU-F)*/
+	switch(control_type){
+		case FrictionCoefficientEnum:
+			GradjDragMacAyeal(gradient,control_index);
+			break;
+		case MaterialsRheologyBbarEnum:
+			GradjBMacAyeal(gradient,control_index);
+			break;
+		case MaterialsRheologyZbarEnum:
+			GradjZMacAyeal(gradient,control_index);
+			break;
+		case BalancethicknessThickeningRateEnum:
+			GradjDhDtBalancedthickness(gradient,control_index);
+			break;
+		case VxEnum:
+			GradjVxBalancedthickness(gradient,control_index);
+			break;
+		case VyEnum:
+			GradjVyBalancedthickness(gradient,control_index);
+			break;
+		default:
+			_error_("control type not supported yet: " << control_type);
+	}
+
+	/*Now deal with ∂J/∂alpha*/
+	int        *responses = NULL;
+	int         num_responses,resp;
+	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+
+	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+		//FIXME: the control type should be checked somewhere (with respect to what variable are we taking the gradient!)
+
+		case ThicknessAbsMisfitEnum:
+		case ThicknessAbsGradientEnum:
+		case ThicknessAlongGradientEnum:
+		case ThicknessAcrossGradientEnum:
+		case SurfaceAbsVelMisfitEnum:
+		case SurfaceRelVelMisfitEnum:
+		case SurfaceLogVelMisfitEnum:
+		case SurfaceLogVxVyMisfitEnum:
+		case SurfaceAverageVelMisfitEnum:
+			/*Nothing, J does not depends on the parameter being inverted for*/
+			break;
+		case DragCoefficientAbsGradientEnum:
+			GradjDragGradient(gradient,resp,control_index);
+			break;
+		case RheologyBbarAbsGradientEnum:
+			GradjBGradient(gradient,resp,control_index);
+			break;
+		default:
+			_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+	}
+
+	xDelete<int>(responses);
+}
+/*}}}*/
+/*FUNCTION Tria::GradjBGradient{{{*/
+void  Tria::GradjBGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index){
+
+	int        i,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=material->inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (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::GradjZGradient{{{*/
+void  Tria::GradjZGradient(Vector<IssmDouble>* 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* rheologyz_input=material->inputs->GetInput(MaterialsRheologyZbarEnum); _assert_(rheologyz_input);
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (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: */
+		rheologyz_input->GetInputDerivativeValue(&dk[0],&xyz_list[0][0],gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for (i=0;i<NUMVERTICES;i++) grade_g[i]+=-weight*Jdet*gauss->weight*(dbasis[0][i]*dk[0]+dbasis[1][i]*dk[1]);
+	}
+	gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Tria::GradjBMacAyeal{{{*/
+void  Tria::GradjBMacAyeal(Vector<IssmDouble>* gradient,int control_index){
+
+	/*Intermediaries*/
+	int        i,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=material->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);
+		material->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::GradjZMacAyeal{{{*/
+void  Tria::GradjZMacAyeal(Vector<IssmDouble>* 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],dZ[NDOF2]; 
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     basis[3],epsilon[3];
+	IssmDouble     grad[NUMVERTICES]={0.0};
+	GaussTria *gauss = NULL;
+
+	/* Get node coordinates and dof list: */
+	GetVerticesCoordinates(&xyz_list[0][0], 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* rheologyz_input=material->inputs->GetInput(MaterialsRheologyZbarEnum); _assert_(rheologyz_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);
+		rheologyz_input->GetInputDerivativeValue(&dZ[0],&xyz_list[0][0],gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],&xyz_list[0][0],gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
+		adjointx_input->GetInputDerivativeValue(&dadjx[0],&xyz_list[0][0],gauss);
+		adjointy_input->GetInputDerivativeValue(&dadjy[0],&xyz_list[0][0],gauss);
+
+		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		material->GetViscosityZComplement(&viscosity_complement,&epsilon[0]);
+
+		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<IssmDouble>* 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<IssmDouble>* 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<IssmDouble>* 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<IssmDouble>* 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<IssmDouble>* 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=material->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*sqrt( 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::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*(dp[0]*dp[0]+dp[1]*dp[1])*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::ThicknessAlongGradient{{{*/
+IssmDouble Tria::ThicknessAlongGradient(bool process_units,int weight_index){
+
+	/* Intermediaries */
+	int         ig;
+	IssmDouble  Jelem = 0;
+	IssmDouble  weight;
+	IssmDouble  Jdet;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  dp[NDOF2];
+	IssmDouble  vx,vy,vel;
+	GaussTria  *gauss                    = NULL;
+
+	/*retrieve parameters and inputs*/
+
+	/*If on water, return 0: */
+	if(IsOnWater()) return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* weights_input  = inputs->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* thickness_input= inputs->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+	Input* vx_input       = inputs->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input       = inputs->GetInput(VyEnum);                                 _assert_(vy_input);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (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);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel = sqrt(vx*vx+vy*vy);
+		vx  = vx/(vel+1.e-9);
+		vy  = vy/(vel+1.e-9);
+
+		/*J = 1/2 ( vx*dH/dx + vy*dH/dy )^2 */
+		Jelem+=weight*1/2*(vx*dp[0] + vy*dp[1])*(vx*dp[0] + vy*dp[1])*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::ThicknessAcrossGradient{{{*/
+IssmDouble Tria::ThicknessAcrossGradient(bool process_units,int weight_index){
+
+	/* Intermediaries */
+	int         ig;
+	IssmDouble  Jelem = 0;
+	IssmDouble  weight;
+	IssmDouble  Jdet;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  dp[NDOF2];
+	IssmDouble  vx,vy,vel;
+	GaussTria  *gauss                    = NULL;
+
+	/*retrieve parameters and inputs*/
+
+	/*If on water, return 0: */
+	if(IsOnWater()) return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
+	Input* weights_input  = inputs->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* thickness_input= inputs->GetInput(ThicknessEnum);                          _assert_(thickness_input);
+	Input* vx_input       = inputs->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input       = inputs->GetInput(VyEnum);                                 _assert_(vy_input);
+
+	/* Start looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for (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);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel = sqrt(vx*vx+vy*vy);
+		vx  = vx/(vel+1.e-9);
+		vy  = vy/(vel+1.e-9);
+
+		/*J = 1/2 ( -vy*dH/dx + vx*dH/dy )^2 */
+		Jelem+=weight*1/2*(-vy*dp[0] + vx*dp[1])*(-vy*dp[0] + vx*dp[1])*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::ThicknessAbsMisfit {{{*/
+IssmDouble Tria::ThicknessAbsMisfit(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*(thickness-thicknessobs)*(thickness-thicknessobs)*weight*Jdet*gauss->weight;
+	}
+
+	/* clean up and Return: */
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorAdjointBalancethickness{{{*/
+ElementVector* Tria::CreatePVectorAdjointBalancethickness(void){
+
+	/*Constants*/
+	const int    numdof=1*NUMVERTICES;
+
+	/*Intermediaries */
+	int         i,ig,resp;
+	IssmDouble  Jdet;
+	IssmDouble  thickness,thicknessobs,weight;
+	int         num_responses;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  basis[3];
+	IssmDouble  dbasis[NDOF2][NUMVERTICES];
+	IssmDouble  dH[2];
+	IssmDouble  vx,vy,vel;
+	GaussTria *gauss     = NULL;
+	int       *responses = NULL;
+
+	/*Initialize Element vector*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], 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);
+	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(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis, gauss);
+		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dH[0],&xyz_list[0][0],gauss);
+		thicknessobs_input->GetInputValue(&thicknessobs, gauss);
+
+		/*Loop over all requested responses*/
+		for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
+
+			case ThicknessAbsMisfitEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				for(i=0;i<numdof;i++) pe->values[i]+=(thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
+				break;
+			case ThicknessAbsGradientEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				for(i=0;i<numdof;i++) pe->values[i]+= - weight*dH[0]*dbasis[0][i]*Jdet*gauss->weight;
+				for(i=0;i<numdof;i++) pe->values[i]+= - weight*dH[1]*dbasis[1][i]*Jdet*gauss->weight;
+				break;
+			case ThicknessAlongGradientEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				vx_input->GetInputValue(&vx,gauss);
+				vy_input->GetInputValue(&vy,gauss);
+				vel = sqrt(vx*vx+vy*vy);
+				vx  = vx/(vel+1.e-9);
+				vy  = vy/(vel+1.e-9);
+				for(i=0;i<numdof;i++) pe->values[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0][i]*vx+dbasis[1][i]*vy)*Jdet*gauss->weight;
+				break;
+			case ThicknessAcrossGradientEnum:
+				weights_input->GetInputValue(&weight, gauss,resp);
+				vx_input->GetInputValue(&vx,gauss);
+				vy_input->GetInputValue(&vy,gauss);
+				vel = sqrt(vx*vx+vy*vy);
+				vx  = vx/(vel+1.e-9);
+				vy  = vy/(vel+1.e-9);
+				for(i=0;i<numdof;i++) pe->values[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0][i]*(-vy)+dbasis[1][i]*vx)*Jdet*gauss->weight;
+				break;
+			default:
+				_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(responses);
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorAdjointHoriz{{{*/
+ElementVector* Tria::CreatePVectorAdjointHoriz(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,resp,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 = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+						duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
+						pe->values[i*NDOF2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case DragCoefficientAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAlongGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAcrossGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(responses);
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorAdjointStokes{{{*/
+ElementVector* Tria::CreatePVectorAdjointStokes(void){
+
+	/*Intermediaries */
+	int        i,resp,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 = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+						duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
+						pe->values[i*NDOF4+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						pe->values[i*NDOF4+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+					}
+					break;
+				case DragCoefficientAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAcrossGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAlongGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(responses);
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::DragCoefficientAbsGradient{{{*/
+IssmDouble Tria::DragCoefficientAbsGradient(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*(dp[0]*dp[0]+dp[1]*dp[1])*Jdet*gauss->weight;
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Jelem;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixAdjointBalancethickness {{{*/
+ElementMatrix* Tria::CreateKMatrixAdjointBalancethickness(void){
+
+	ElementMatrix* Ke=NULL;
+
+	/*Get Element Matrix of the forward model*/
+	switch(GetElementType()){
+		case P1Enum:
+			Ke=CreateKMatrixBalancethickness_CG();
+			break;
+		case P1DGEnum:
+			Ke=CreateKMatrixBalancethickness_DG();
+			break;
+		default:
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+	}
+
+	/*Transpose and return Ke*/
+	Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixAdjointMacAyeal{{{*/
+ElementMatrix* Tria::CreateKMatrixAdjointMacAyeal(void){
+
+	/*Constants*/
+	const int    numdof=NDOF2*NUMVERTICES;
+
+	/*Intermediaries */
+	int        i,j,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);
+		material->GetViscosity2dDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=2*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
+		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
+
+		for(i=0;i<3;i++){
+			for(j=0;j<3;j++){
+				eps1dotdphii=eps1[0]*dphi[0][i]+eps1[1]*dphi[1][i];
+				eps1dotdphij=eps1[0]*dphi[0][j]+eps1[1]*dphi[1][j];
+				eps2dotdphii=eps2[0]*dphi[0][i]+eps2[1]*dphi[1][i];
+				eps2dotdphij=eps2[0]*dphi[0][j]+eps2[1]*dphi[1][j];
+
+				Ke->values[6*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*thickness*eps1dotdphij*eps1dotdphii;
+				Ke->values[6*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*thickness*eps2dotdphij*eps1dotdphii;
+				Ke->values[6*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*thickness*eps1dotdphij*eps2dotdphii;
+				Ke->values[6*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*thickness*eps2dotdphij*eps2dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	//Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionAdjointHoriz {{{*/
+void  Tria::InputUpdateFromSolutionAdjointHoriz(IssmDouble* solution){
+
+	const int numdof=NDOF2*NUMVERTICES;
+
+	int       i;
+	int*      doflist=NULL;
+	IssmDouble    values[numdof];
+	IssmDouble    lambdax[NUMVERTICES];
+	IssmDouble    lambday[NUMVERTICES];
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		lambdax[i]=values[i*NDOF2+0];
+		lambday[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new 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])) _error_("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<IssmDouble>* 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 || control_enum==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(control_enum); _assert_(input);
+	}
+	else{
+		input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	}
+
+	/*Check that it is a ControlInput*/
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->GetVectorFromInputs(vector,&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 || control_enum==MaterialsRheologyZbarEnum){
+		input=(Input*)material->inputs->GetInput(control_enum); _assert_(input);
+	}
+	else{
+		input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	}
+
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->SetInput(new_input);
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_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*CR*CR*rho_water*g/mu_water;
+	
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+		surfaceslopex_input->GetInputValue(&dsdx,gauss);
+		surfaceslopey_input->GetInputValue(&dsdy,gauss);
+		bedslopex_input->GetInputValue(&dbdx,gauss);
+		bedslopey_input->GetInputValue(&dbdy,gauss);
+		watercolumn_input->GetInputValue(&w,gauss);
+
+		/* Water velocity x and y components */
+	//	vx[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
+	//	vy[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
+		vx[iv]= - w*w/(VelocityFactor* mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
+		vy[iv]= - w*w/(VelocityFactor* mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
+	}
+
+	/*clean-up*/
+	delete gauss;
+
+	/*Add to inputs*/
+	this->inputs->AddInput(new 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(vx*vx+vy*vy);
+		K[0][0]=diffusivity*h/(2*vel)*vx*vx;
+		K[1][0]=diffusivity*h/(2*vel)*vy*vx;
+		K[0][1]=diffusivity*h/(2*vel)*vx*vy;
+		K[1][1]=diffusivity*h/(2*vel)*vy*vy;
+		KDL[0][0]=DL_scalar*K[0][0];
+		KDL[1][0]=DL_scalar*K[1][0];
+		KDL[0][1]=DL_scalar*K[0][1];
+		KDL[1][1]=DL_scalar*K[1][1];
+
+		TripleMultiply( &Bprime[0][0],2,numdof,1,
+					&KDL[0][0],2,2,0,
+					&Bprime[0][0],2,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::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(reCast<int,IssmDouble>(dt))for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(old_watercolumn_g+dt*basal_melting_g)*basis[i];
+		else  for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*basal_melting_g*basis[i];
+	}
+		
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::GetSolutionFromInputsHydrology{{{*/
+void  Tria::GetSolutionFromInputsHydrology(Vector<IssmDouble>* 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        *doflist        = NULL;
+	IssmDouble  values[numdof];
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numdof;i++){
+		values[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+		if (values[i]<10e-10) values[i]=10e-10; //correcting the water column to positive values
+	}
+
+	/*Add input to the element: */
+	this->inputs->AddInput(new 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:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVectorDakota(int* vector, int name, int type);{{{*/
+void  Tria::InputUpdateFromVectorDakota(int* vector, int name, int type){
+	_error_("not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromVectorDakota(bool* vector, int name, int type);{{{*/
+void  Tria::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+	_error_("not supported yet!");
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type);{{{*/
+void  Tria::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){
+	
+	int i,j,t;
+	TransientInput* transientinput=NULL;
+	IssmDouble values[3];
+	IssmDouble time;
+	int row;
+	IssmDouble yts;
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+			
+			/*Create transient input: */
+						
+			parameters->FindParam(&yts,ConstantsYtsEnum);
+			for(t=0;t<ncols;t++){ //ncols is the number of times
+
+				/*create input values: */
+				for(i=0;i<3;i++){
+					row=this->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:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
+#endif
+
+#ifdef _HAVE_BALANCED_
+/*FUNCTION Tria::CreateKMatrixBalancethickness {{{*/
+ElementMatrix* Tria::CreateKMatrixBalancethickness(void){
+
+	switch(GetElementType()){
+		case P1Enum:
+			return CreateKMatrixBalancethickness_CG();
+		case P1DGEnum:
+			return CreateKMatrixBalancethickness_DG();
+		default:
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixBalancethickness_CG {{{*/
+ElementMatrix* Tria::CreateKMatrixBalancethickness_CG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries */
+	int        stabilization;
+	int        i,j,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(vx*vx+vy*vy);
+			K[0][0]=h/(2*vel)*vx*vx;
+			K[1][0]=h/(2*vel)*vy*vx;
+			K[0][1]=h/(2*vel)*vx*vy;
+			K[1][1]=h/(2*vel)*vy*vy;
+		}
+		else if(stabilization==2){
+			/*MacAyeal*/
+			vxaverage_input->GetInputAverage(&vx);
+			vyaverage_input->GetInputAverage(&vy);
+			K[0][0]=h/2.0*fabs(vx);
+			K[0][1]=0.;
+			K[1][0]=0.;
+			K[1][1]=h/2.0*fabs(vy);
+		}
+		if(stabilization==1 || stabilization==2){
+			KDL[0][0]=DL_scalar*K[0][0];
+			KDL[1][0]=DL_scalar*K[1][0];
+			KDL[0][1]=DL_scalar*K[0][1];
+			KDL[1][1]=DL_scalar*K[1][1];
+			TripleMultiply( &Bprime[0][0],2,numdof,1,
+						&KDL[0][0],2,2,0,
+						&Bprime[0][0],2,numdof,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixBalancethickness_DG {{{*/
+ElementMatrix* Tria::CreateKMatrixBalancethickness_DG(void){
+
+	/*Constants*/
+	const int  numdof=NDOF1*NUMVERTICES;
+
+	/*Intermediaries*/
+	int        i,j,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:
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorBalancethickness_CG{{{*/
+ElementVector* Tria::CreatePVectorBalancethickness_CG(void){
+
+	/*Constants*/
+	const int    numdof=NDOF1*NUMVERTICES;
+	
+	/*Intermediaries */
+	int        i,j,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/trunk/src/c/classes/objects/Elements/Tria.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/Tria.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/Tria.h	(revision 13395)
@@ -0,0 +1,243 @@
+/*! \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 Material;
+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
+		Material  *material;   // 1 material ice
+		Matpar  *matpar;   // 1 material parameter
+		int      horizontalneighborsids[3];
+
+		Parameters *parameters;   //pointer to solution parameters
+		Inputs     *inputs;
+		Results    *results;
+
+		/*Tria constructors, destructors {{{*/
+		Tria();
+		Tria(int tria_id,int tria_sid,int i, IoModel* iomodel,int nummodels);
+		~Tria();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   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<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
+		void   ComputeBasalStress(Vector<IssmDouble>* sigma_b);
+		void   ComputeStrainRate(Vector<IssmDouble>* 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<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,Vector<IssmDouble>* df);
+		void   CreatePVector(Vector<IssmDouble>* pf);
+		void   CreateJacobianMatrix(Matrix<IssmDouble>* 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<IssmDouble>* solution);
+		void   GetVectorFromInputs(Vector<IssmDouble>* vector, int name_enum);
+		void   GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int enum_in,int interp);
+		void   InputArtificialNoise(int enum_type,IssmDouble min, IssmDouble max);
+		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){_error_("not implemented yet");};
+		void   MigrateGroundingLine(IssmDouble* oldfloating,IssmDouble* sheet_ungrounding);
+		int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum,bool process_units);
+		void   PotentialSheetUngrounding(Vector<IssmDouble>* 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){_error_("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<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf);
+		IssmDouble TimeAdapt();
+		int*   GetHorizontalNeighboorSids(void);
+		void   SmearFunction(Vector<IssmDouble>* 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<IssmDouble>* gradient,int control_type,int control_index);
+		void   GradjBGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index);
+		void   GradjZGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index);
+		void   GradjBMacAyeal(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjZMacAyeal(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjDragMacAyeal(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjDragStokes(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjDragGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index);
+		void   GradjDhDtBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjVxBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjVyBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
+		void   GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data);
+		void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
+		void   ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index);
+		void   ControlInputScaleGradient(int enum_type,IssmDouble scale);
+		void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
+		IssmDouble RheologyBbarAbsGradient(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 ThicknessAlongGradient( bool process_units,int weight_index);
+		IssmDouble ThicknessAcrossGradient(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* CreateMassMatrix(void);
+		ElementVector* CreatePVectorBalancethickness(void);
+		ElementVector* CreatePVectorBalancethickness_DG(void);
+		ElementVector* CreatePVectorBalancethickness_CG(void);
+		ElementVector* CreatePVectorPrognostic(void);
+		ElementVector* CreatePVectorPrognostic_CG(void);
+		ElementVector* CreatePVectorPrognostic_DG(void);
+		ElementVector* CreatePVectorSlope(void);
+		IssmDouble         GetArea(void);
+		int            GetElementType(void);
+		void	         GetDofList(int** pdoflist,int approximation_enum,int setenum);
+		void	         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<IssmDouble>* solution);
+		void	  GetSolutionFromInputsDiagnosticHutter(Vector<IssmDouble>* solution);
+		void	  InputUpdateFromSolutionDiagnosticHoriz( IssmDouble* solution);
+		void	  InputUpdateFromSolutionDiagnosticHutter( IssmDouble* solution);
+		#endif
+
+		#ifdef _HAVE_CONTROL_
+		ElementMatrix* CreateKMatrixAdjointBalancethickness(void);
+		ElementMatrix* CreateKMatrixAdjointMacAyeal(void);
+		ElementVector* CreatePVectorAdjointHoriz(void);
+		ElementVector* CreatePVectorAdjointStokes(void);
+		ElementVector* CreatePVectorAdjointBalancethickness(void);
+		void	  InputUpdateFromSolutionAdjointBalancethickness( IssmDouble* solution);
+		void	  InputUpdateFromSolutionAdjointHoriz( IssmDouble* solution);
+		#endif
+
+		#ifdef _HAVE_HYDROLOGY_
+		ElementMatrix* CreateKMatrixHydrology(void);
+		ElementVector* CreatePVectorHydrology(void);
+		void      CreateHydrologyWaterVelocityInput(void);
+		void	  GetSolutionFromInputsHydrology(Vector<IssmDouble>* solution);
+		void	  InputUpdateFromSolutionHydrology(IssmDouble* solution);
+		#endif
+		#ifdef _HAVE_BALANCED_
+		#endif
+
+		/*}}}*/
+
+};
+#endif  /* _TRIA_H */
Index: /issm/trunk/src/c/classes/objects/Elements/TriaHook.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/TriaHook.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/TriaHook.cpp	(revision 13395)
@@ -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->hmaterial=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 hmaterial;
+	delete hmatpar;
+
+}
+/*}}}*/
+/*FUNCTION TriaHook::TriaHook(int in_numanalyses,int material_id, int matpar_id){{{*/
+TriaHook::TriaHook(int in_numanalyses,int material_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->hmaterial=new Hook(&material_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/trunk/src/c/classes/objects/Elements/TriaHook.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/TriaHook.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/TriaHook.h	(revision 13395)
@@ -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*  hmaterial; // 1 ice material
+		Hook*  hmatpar; // 1 material parameter
+
+
+		/*FUNCTION constructors, destructors {{{*/
+		TriaHook();
+		TriaHook(int in_numanalyses,int material_id, IoModel* iomodel);
+		~TriaHook();
+		void SetHookNodes(int* node_ids,int analysis_counter);
+		/*}}}*/
+
+};
+
+
+#endif //ifndef _TRIAHOOK_H_
+
Index: /issm/trunk/src/c/classes/objects/Elements/TriaRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/TriaRef.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/TriaRef.cpp	(revision 13395)
@@ -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) _error_("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) _error_("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) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetJacobianInvert{{{*/
+void TriaRef::GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,GaussTria* gauss){
+
+	/*Jacobian*/
+	IssmDouble J[2][2];
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J[0][0], xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	Matrix2x2Invert(Jinv,&J[0][0]);
+
+}
+/*}}}*/
+/*FUNCTION TriaRef::GetNodalFunctions{{{*/
+void TriaRef::GetNodalFunctions(IssmDouble* basis,GaussTria* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	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/trunk/src/c/classes/objects/Elements/TriaRef.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/TriaRef.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Elements/TriaRef.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects/ExternalResults/ExternalResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ExternalResults/ExternalResult.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/ExternalResults/ExternalResult.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects/ExternalResults/GenericExternalResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ExternalResults/GenericExternalResult.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/ExternalResults/GenericExternalResult.h	(revision 13395)
@@ -0,0 +1,326 @@
+/*! \file GenericExternalResult.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _GENERIC_EXTERNAL_RESULT_
+#define _GENERIC_EXTERNAL_RESULT_
+
+/*Headers:{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstring>
+
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../shared/Numerics/recast.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "./ExternalResult.h"
+/*}}}*/
+
+template <class ResultType> 
+class GenericExternalResult: public ExternalResult {
+
+	private: 
+		int id;
+		int enum_type;
+		ResultType value;
+		int M;
+		int N;
+		int step;
+		IssmDouble time;
+	
+	public:
+		/*Diverse: must be in front, as it is used in what follows*/
+		void GenericEcho(void){/*{{{*/
+			_printLine_("   id: " << this->id);
+			_printLine_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+			_printLine_("   step: " << this->step);
+			_printLine_("   time: " << this->time);
+		}
+		/*}}}*/
+		void GenericWriteData(FILE* fid){/*{{{*/ 
+
+			int     length;
+			IssmPDouble  passiveDouble;
+			char*   name = NULL;
+
+			/*First write enum: */
+			EnumToStringx(&name,this->enum_type);
+			length=(strlen(name)+1)*sizeof(char);
+			fwrite(&length,sizeof(int),1,fid);
+			fwrite(name,length,1,fid);
+			xDelete<char>(name);
+
+			/*Now write time and step: */
+			passiveDouble=reCast<IssmPDouble>(time);
+			fwrite(&passiveDouble,sizeof(IssmPDouble),1,fid);
+			fwrite(&step,sizeof(int),1,fid);
+		} /*}}}*/
+
+		/*GenericExternalResult constructors and  destructors*/
+		GenericExternalResult(){ /*{{{*/
+			id  = 0;
+			enum_type = NoneEnum;
+			M=0;
+			N=0;
+			step=0;
+			time=0;
+		} /*}}}*/
+		GenericExternalResult(int in_id, int in_enum_type,ResultType in_values, int in_M,int in_N,int in_step,IssmDouble in_time){/*{{{*/
+			_error_("template GenericExternalResult(int in_id, int in_enum_type,double* in_values, int in_M,int in_N,int in_step,IssmDouble in_time) not implemented for this ResultType\n");
+		}
+/*}}}*/
+		GenericExternalResult(int in_id, int in_enum_type,ResultType in_value,int in_step, IssmDouble in_time){ /*{{{*/
+			id=in_id;
+			enum_type=in_enum_type;
+			value=in_value;
+			step=in_step;
+			time=in_time;
+		}
+		/*}}}*/
+		~GenericExternalResult(){ /*{{{*/
+		} /*}}}*/
+
+		/*Object virtual functions definitions:*/
+		void Echo(void){ /*{{{*/
+			this->DeepEcho();
+		}
+		/*}}}*/
+		void DeepEcho(void){ /*{{{*/
+			_error_("template DeepEcho not implemented for this ResultType\n");
+		}
+		/*}}}*/
+		int Id(void){ /*{{{*/ 
+			return -1; 
+		} /*}}}*/
+		int MyRank(void){ /*{{{*/
+			extern int my_rank;
+			return my_rank; 
+		} /*}}}*/
+		int ObjectEnum(void){ /*{{{*/
+			_error_("template ObjectEnum not implemented for this ResultType\n");
+		} /*}}}*/
+		Object* copy(void) { /*{{{*/
+			return new GenericExternalResult<ResultType>(this->id,this->enum_type,this->value,this->step,this->time);
+		} /*}}}*/
+
+		/*GenericExternalResult management: */
+void WriteData(FILE* fid,bool io_gather){ /*{{{*/
+			
+	extern  int my_rank;
+	int     type;
+	int     size;
+	IssmPDouble  passiveDouble;
+	
+	/*return if now on cpu 0: */
+	if(my_rank)return;
+
+	/*use generic part, same for all ResultTypes: */
+	this->GenericWriteData(fid);
+
+	/*writing a IssmPDouble for Matlab or Python to post-process, type is 1, size is 1: */
+	type=1;
+	size=1;
+	fwrite(&type,sizeof(int),1,fid);
+	fwrite(&size,sizeof(int),1,fid);
+
+	/*cast to a IssmPDouble: */
+	passiveDouble=reCast<IssmPDouble>(value);
+	fwrite(&passiveDouble,size*sizeof(IssmPDouble),1,fid);
+
+} /*}}}*/
+void GetResultName(char** pname){ /*{{{*/
+	EnumToStringx(pname,this->enum_type);
+} /*}}}*/
+int GetStep(void){ /*{{{*/
+	return this->step;
+} /*}}}*/
+int InstanceEnum(void){ /*{{{*/
+	return this->enum_type;
+} /*}}}*/
+};
+
+/*Specific instantiations for bool: */
+template <> inline void GenericExternalResult<bool>::DeepEcho(void){ /*{{{*/
+
+	_printLine_("GenericExternalResult<bool>:");
+	this->GenericEcho();
+	_printLine_("   value: " <<(this->value?"true":"false"));
+
+} /*}}}*/
+template <> inline int GenericExternalResult<bool>::ObjectEnum(void){ /*{{{*/
+	return BoolExternalResultEnum;
+} /*}}}*/
+
+/*Specific instantiations for int: */
+template <> inline void GenericExternalResult<int>::DeepEcho(void){ /*{{{*/
+
+	_printLine_("GenericExternalResult<int>:");
+	this->GenericEcho();
+	_printLine_("   value: " << this->value);
+
+} /*}}}*/
+template <> inline int GenericExternalResult<int>::ObjectEnum(void){ /*{{{*/
+	return IntExternalResultEnum;
+} /*}}}*/
+
+/*Specific instantiations for double: */
+template <> inline void GenericExternalResult<double>::DeepEcho(void){ /*{{{*/
+
+	_printLine_("GenericExternalResult<double>:");
+	this->GenericEcho();
+	_printLine_("   value: " << this->value);
+
+} /*}}}*/
+template <> inline int GenericExternalResult<double>::ObjectEnum(void){ /*{{{*/
+	return DoubleExternalResultEnum;
+} /*}}}*/
+
+/*Specific instantiations for char*: */
+template <> inline GenericExternalResult<char*>::GenericExternalResult(int in_id, int in_enum_type,char* in_value,int in_step, IssmDouble in_time){ /*{{{*/
+
+	id=in_id;
+	enum_type=in_enum_type;
+	value=xNew<char>(strlen(in_value)+1);
+	xMemCpy<char>(value,in_value,(strlen(in_value)+1));
+	step=in_step;
+	time=in_time;
+
+} /*}}}*/
+template <> inline GenericExternalResult<char*>::~GenericExternalResult(){ /*{{{*/
+	xDelete<char>(value);
+} /*}}}*/
+template <> inline void GenericExternalResult<char*>::DeepEcho(void){ /*{{{*/
+
+	_printLine_("GenericExternalResult<char*>:");
+	this->GenericEcho();
+	_printLine_("   value: " << this->value);
+
+} /*}}}*/
+template <> inline void GenericExternalResult<char*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
+
+	extern  int my_rank;
+	int     type;
+	int     length;
+
+	/*return if now on cpu 0: */
+	if(my_rank)return;
+
+	/*use generic part, same for all ResultTypes: */
+	this->GenericWriteData(fid);
+
+	/*writing a string, type is 2: */
+	type=2;
+	fwrite(&type,sizeof(int),1,fid);
+
+	length=(strlen(this->value)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(this->value,length,1,fid);
+}
+/*}}}*/
+template <> inline int GenericExternalResult<char*>::ObjectEnum(void){ /*{{{*/
+	return StringExternalResultEnum;
+} /*}}}*/
+
+/*Specific instantiations for IssmPDouble*: */
+template <> inline GenericExternalResult<IssmPDouble*>::GenericExternalResult(int in_id, int in_enum_type,IssmPDouble* in_values, int in_M,int in_N,int in_step,IssmDouble in_time){/*{{{*/
+
+	id=in_id;
+	enum_type=in_enum_type;
+	M=in_M;
+	N=in_N;
+	
+	step=in_step;
+	time=in_time;
+
+	/*Copy result in values*/
+	if(M*N){
+		value=xNew<IssmPDouble>(M*N);
+		xMemCpy<IssmPDouble>(value,in_values,M*N);
+	}
+	else value=NULL;
+}
+/*}}}*/
+template <> inline GenericExternalResult<IssmPDouble*>::GenericExternalResult(int in_id, int in_enum_type,IssmPDouble* in_value,int in_step, IssmDouble in_time){ /*{{{*/
+	_error_("you cannot initialize a GenericExternalResult<IssmPDouble*> without providing the dimensions of the matrix! Please use a more appropriate constructor!");
+} /*}}}*/
+template <> inline GenericExternalResult<IssmPDouble*>::~GenericExternalResult(){ /*{{{*/
+	xDelete<IssmPDouble>(value);
+} /*}}}*/
+template <> inline void GenericExternalResult<IssmPDouble*>::Echo(void){ /*{{{*/
+	
+	int i,j;
+
+	_printLine_("GenericExternalResult<IssmPDouble*>:");
+	this->GenericEcho();
+	_printLine_("   matrix size: " << this->M << "-" << this->N);
+
+} /*}}}*/
+template <> inline void GenericExternalResult<IssmPDouble*>::DeepEcho(void){ /*{{{*/
+	
+	int i,j;
+
+	_printLine_("GenericExternalResult<IssmPDouble*>:");
+	this->GenericEcho();
+	
+	_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->value[i*this->N+j]);
+		}  
+		_printLine_(" ]");
+	}  
+
+} /*}}}*/
+template <> inline Object* GenericExternalResult<IssmPDouble*>::copy(void){ /*{{{*/
+	return new GenericExternalResult<IssmPDouble*>(this->id,this->enum_type,this->value,this->M,this->N,this->step,this->time);
+} /*}}}*/
+template <> inline void GenericExternalResult<IssmPDouble*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
+	
+	extern  int my_rank;
+	int     length;
+	int     type;
+	int     rows,cols;
+	char   *name    = NULL;
+	extern  int my_rank;
+	IssmPDouble passiveDouble;
+
+	if(io_gather){
+		/*we are gathering the data on cpu 0, don't write on other cpus: */
+		if(my_rank) return;
+	}
+
+	/*First write enum: */
+	EnumToStringx(&name,this->enum_type);
+	length=(strlen(name)+1)*sizeof(char);
+	fwrite(&length,sizeof(int),1,fid);
+	fwrite(name,length,1,fid);
+	xDelete<char>(name);
+
+	/*Now write time and step: */
+	passiveDouble=reCast<IssmPDouble>(time);
+	fwrite(&passiveDouble,sizeof(IssmPDouble),1,fid);
+	fwrite(&step,sizeof(int),1,fid);
+
+	/*writing a IssmDouble array, type is 3:*/
+	type=3;
+	fwrite(&type,sizeof(int),1,fid);
+	rows=this->M;
+	fwrite(&rows,sizeof(int),1,fid);
+	cols=this->N;
+	fwrite(&cols,sizeof(int),1,fid);
+	fwrite(value,cols*rows*sizeof(IssmPDouble),1,fid);
+
+}
+/*}}}*/
+template <> inline int GenericExternalResult<IssmPDouble*>::ObjectEnum(void){ /*{{{*/
+	return DoubleMatExternalResultEnum;
+} /*}}}*/
+
+#endif  /* _EXTERNAL_RESULTOBJECT_H */
Index: /issm/trunk/src/c/classes/objects/Inputs/BoolInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/BoolInput.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/BoolInput.cpp	(revision 13395)
@@ -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){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue){{{*/
+void BoolInput::GetInputValue(IssmDouble* pvalue){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void BoolInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
+void BoolInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void BoolInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION BoolInput::ChangeEnum{{{*/
+void BoolInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION BoolInput::SquareMin{{{*/
+void BoolInput::SquareMin(IssmDouble* psquaremin, 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:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::Extrude{{{*/
+void BoolInput::Extrude(void){
+
+	/*do nothing*/
+	return;
+}
+/*}}}*/
+/*FUNCTION BoolInput::GetVectorFromInputs{{{*/
+void BoolInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+
+	_error_("not supporte yet!");
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::GetValuesPtr{{{*/
+void BoolInput::GetValuesPtr(IssmDouble** pvalues,int* pnum_values){
+
+	_error_("not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION BoolInput::Configure{{{*/
+void BoolInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Inputs/BoolInput.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/BoolInput.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/BoolInput.h	(revision 13395)
@@ -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){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		void Configure(Parameters* parameters);
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error_("InfinityNorm not implemented for booleans");};
+		IssmDouble Max(void){_error_("Max not implemented for booleans");};
+		IssmDouble MaxAbs(void){_error_("Max not implemented for booleans");};
+		IssmDouble Min(void){_error_("Min not implemented for booleans");};
+		IssmDouble MinAbs(void){_error_("Min not implemented for booleans");};
+		void Scale(IssmDouble scale_factor);
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("Constrain not implemented for booleans");};
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _BOOLINPUT_H */
Index: /issm/trunk/src/c/classes/objects/Inputs/ControlInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/ControlInput.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/ControlInput.cpp	(revision 13395)
@@ -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:
+			_error_("Input of Enum " << EnumToStringx(enum_input) << " not supported yet by ControlInput");
+	}
+	gradient   =NULL;
+}
+/*}}}*/
+/*FUNCTION ControlInput::~ControlInput(){{{*/
+ControlInput::~ControlInput(){
+	delete values;
+	delete savedvalues;
+	delete minvalues;
+	delete maxvalues;
+	delete gradient;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+		/*FUNCTION ControlInput::Echo {{{*/
+void ControlInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION ControlInput::DeepEcho{{{*/
+void ControlInput::DeepEcho(void){
+
+	_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<IssmDouble>* gradient_vec,int* doflist){
+	if(gradient) gradient->GetVectorFromInputs(gradient_vec,doflist);
+}/*}}}*/
+/*FUNCTION ControlInput::ScaleGradient{{{*/
+void ControlInput::ScaleGradient(IssmDouble scaling_factor){
+	if(!gradient) _error_("Gradient of ControlInput " << EnumToStringx(enum_type) << " not found");
+	gradient->Scale(scaling_factor);
+}/*}}}*/
+/*FUNCTION ControlInput::SetGradient{{{*/
+void ControlInput::SetGradient(Input* gradient_in){
+
+	/*Get enum for current gradient*/
+	switch(this->control_id){
+		case 1:
+			gradient_in->ChangeEnum(Gradient1Enum);
+			break;
+		case 2:
+			gradient_in->ChangeEnum(Gradient2Enum);
+			break;
+		case 3:
+			gradient_in->ChangeEnum(Gradient3Enum);
+			break;
+		default:
+			_error_("more than 3 controls not implemented yet (Gradient " << this->control_id << " was requested). EnumDefinitions.h needs to be updated.");
+	}
+
+	/*Delete old gradient and assign new gradient*/
+	if(gradient) delete gradient;
+	gradient=gradient_in;
+
+}/*}}}*/
+/*FUNCTION ControlInput::SetInput{{{*/
+void ControlInput::SetInput(Input* in_input){
+
+	delete values; this->values=in_input;
+	this->SaveValue(); //because this is what SpawnResult saves FIXME
+
+}/*}}}*/
+/*FUNCTION ControlInput::SpawnResult{{{*/
+ElementResult* ControlInput::SpawnResult(int step, IssmDouble time){
+	return savedvalues->SpawnResult(step,time);
+}/*}}}*/
+/*FUNCTION ControlInput::SpawnTriaInput{{{*/
+Input* ControlInput::SpawnTriaInput(int* indices){
+	return values->SpawnTriaInput(indices);
+}/*}}}*/
+/*FUNCTION ControlInput::SpawnGradient{{{*/
+ElementResult* ControlInput::SpawnGradient(int step, IssmDouble time){
+	_assert_(gradient);
+	return gradient->SpawnResult(step,time);
+}/*}}}*/
+/*FUNCTION ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){{{*/
+void ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+	values->GetVectorFromInputs(vector,doflist);
+}/*}}}*/
+/*FUNCTION ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data){{{*/
+void ControlInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data){
+	 if(strcmp(data,"value")==0){
+		 _assert_(values);
+		 values->GetVectorFromInputs(vector,doflist);
+	 }
+	 else if (strcmp(data,"lowerbound")==0){
+		 _assert_(minvalues);
+		 minvalues->GetVectorFromInputs(vector,doflist);
+	 }
+	 else if (strcmp(data,"upperbound")==0){
+		 _assert_(maxvalues);
+		 maxvalues->GetVectorFromInputs(vector,doflist);
+	 }
+	 else if (strcmp(data,"gradient")==0){
+		 _assert_(gradient);
+		 gradient->GetVectorFromInputs(vector,doflist);
+	 }
+	 else{
+		 _error_("Data " << data << " not supported yet");
+	 }
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputAverage(IssmDouble* pvalue){{{*/
+void ControlInput::GetInputAverage(IssmDouble* pvalue){
+	values->GetInputAverage(pvalue);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(bool* pvalue){{{*/
+void ControlInput::GetInputValue(bool* pvalue){
+	values->GetInputValue(pvalue);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(int* pvalue){{{*/
+void ControlInput::GetInputValue(int* pvalue){
+	values->GetInputValue(pvalue);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(IssmDouble* pvalue){{{*/
+void ControlInput::GetInputValue(IssmDouble* pvalue){
+	values->GetInputValue(pvalue);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(IssmDouble* pvalue){{{*/
+void ControlInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){
+	values->GetInputValue(pvalue,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputValue(IssmDouble* pvalue){{{*/
+void ControlInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){
+	values->GetInputValue(pvalue,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){
+	values->GetInputDerivativeValue(derivativevalues,xyz_list,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void ControlInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){
+	values->GetInputDerivativeValue(derivativevalues,xyz_list,gauss);
+}/*}}}*/
+/*FUNCTION ControlInput::SaveValue{{{*/
+void ControlInput::SaveValue(void){
+	if(!values) _error_("Values of " << EnumToStringx(this->enum_type) << " not found");
+
+	if(savedvalues) delete this->savedvalues;
+	this->savedvalues=(Input*)this->values->copy();
+}/*}}}*/
+/*FUNCTION ControlInput::UpdateValue{{{*/
+void ControlInput::UpdateValue(IssmDouble scalar){
+	if(!gradient)    _error_("Gradient of " << EnumToStringx(this->enum_type) << " not found");
+	if(!savedvalues) _error_("Values of " << EnumToStringx(this->enum_type) << " not found");
+
+	if(values) delete this->values;
+	this->values=(Input*)this->savedvalues->copy();
+	this->values->AXPY(gradient,scalar);
+}/*}}}*/
+/*FUNCTION ControlInput::VerticallyIntegrate{{{*/
+void ControlInput::VerticallyIntegrate(Input* thickness_input){
+	values->VerticallyIntegrate(thickness_input);
+}/*}}}*/
+/*FUNCTION ControlInput::Configure{{{*/
+void ControlInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Inputs/ControlInput.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/ControlInput.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/ControlInput.h	(revision 13395)
@@ -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){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void SetInput(Input* in_input);
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar){_error_("not implemented yet");};
+		void Constrain(void);
+		void Constrain(IssmDouble min,IssmDouble max);
+		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
+		IssmDouble Max(void){_error_("not implemented yet");};
+		IssmDouble MaxAbs(void){_error_("not implemented yet");};
+		IssmDouble Min(void){_error_("not implemented yet");};
+		IssmDouble MinAbs(void){_error_("not implemented yet");};
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data);
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values){_error_("not implemented yet");};
+		ElementResult* SpawnGradient(int step, IssmDouble time);
+		void GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist);
+		void ScaleGradient(IssmDouble scale);
+		void SetGradient(Input* gradient_in);
+		void UpdateValue(IssmDouble scalar);
+		void SaveValue(void);
+		/*}}}*/
+
+};
+#endif  /* _CONTROLINPUT_H */
Index: /issm/trunk/src/c/classes/objects/Inputs/DatasetInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/DatasetInput.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/DatasetInput.cpp	(revision 13395)
@@ -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) _error_("index requested (" << index << ") exceeds dataset size (" << inputs->Size() << ")");
+	Input* input=(Input*)this->inputs->GetObjectByOffset(index);
+	
+	input->GetInputValue(pvalue,gauss);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Inputs/DatasetInput.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/DatasetInput.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/DatasetInput.h	(revision 13395)
@@ -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){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time){_error_("not implemented yet");};
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters){_error_("not implemented yet");};
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar){_error_("not implemented yet");};
+		void Constrain(void){_error_("not implemented yet");};
+		void Constrain(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
+		IssmDouble Max(void){_error_("not implemented yet");};
+		IssmDouble MaxAbs(void){_error_("not implemented yet");};
+		IssmDouble Min(void){_error_("not implemented yet");};
+		IssmDouble MinAbs(void){_error_("not implemented yet");};
+		void Extrude(void){_error_("not implemented yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not implemented yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){_error_("not implemented yet");};
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values){_error_("not implemented yet");};
+		ElementResult* SpawnGradient(int step, IssmDouble time){_error_("not implemented yet");};
+		void GetGradient(Vector<IssmDouble>* gradient_vec,int* doflist){_error_("not implemented yet");};
+		void ScaleGradient(IssmDouble scale){_error_("not implemented yet");};
+		void SetGradient(Input* gradient_in){_error_("not implemented yet");};
+		void UpdateValue(IssmDouble scalar){_error_("not implemented yet");};
+		void SaveValue(void){_error_("not implemented yet");};
+		/*}}}*/
+
+};
+#endif  /* _DATASETINPUT_H */
Index: /issm/trunk/src/c/classes/objects/Inputs/DoubleInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/DoubleInput.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/DoubleInput.cpp	(revision 13395)
@@ -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){
+	_error_("Double input of enum " << EnumToStringx(enum_type) << " cannot return a boolean");
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(int* pvalue){{{*/
+void DoubleInput::GetInputValue(int* pvalue){
+	_error_("Double input of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(IssmDouble* pvalue){{{*/
+void DoubleInput::GetInputValue(IssmDouble* pvalue){
+
+	/*return value*/
+	*pvalue=value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void DoubleInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){*pvalue=this->value;}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
+void DoubleInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){*pvalue=this->value;}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void DoubleInput::GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){
+	/*Epsilon is zero as vx is constant over the element*/
+	for(int i=0;i<3;i++) epsilonvx[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void DoubleInput::GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){
+	/*Epsilon is zero as vy is constant over the element*/
+	for(int i=0;i<3;i++) epsilonvy[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vx is constant over the element*/
+	for(int i=0;i<6;i++) epsilonvx[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vy is constant over the element*/
+	for(int i=0;i<6;i++) epsilonvy[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vz is constant over the element*/
+	for(int i=0;i<6;i++) epsilonvz[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vx is constant over the element*/
+	for(int i=0;i<5;i++) epsilonvx[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){
+	/*Epsilon is zero as vy is constant over the element*/
+	for(int i=0;i<5;i++) epsilonvy[i]=0;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::ChangeEnum{{{*/
+void DoubleInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::SquareMin{{{*/
+void DoubleInput::SquareMin(IssmDouble* psquaremin, 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:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Constrain{{{*/
+void DoubleInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){
+
+	if(!xIsNan<IssmDouble>(cm_min)) if (this->value<cm_min)this->value=cm_min;
+	if(!xIsNan<IssmDouble>(cm_max)) if (this->value>cm_max)this->value=cm_max;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Max{{{*/
+IssmDouble DoubleInput::Max(void){
+	return this->value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::MaxAbs{{{*/
+IssmDouble DoubleInput::MaxAbs(void){
+	return fabs(this->value);
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Min{{{*/
+IssmDouble DoubleInput::Min(void){
+	return this->value;
+}
+/*}}}*/
+/*FUNCTION DoubleInput::MinAbs{{{*/
+IssmDouble DoubleInput::MinAbs(void){
+	return fabs(this->value);
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetVectorFromInputs{{{*/
+void DoubleInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+
+	_error_("not supporte yet!");
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::GetValuesPtr{{{*/
+void DoubleInput::GetValuesPtr(IssmDouble** pvalues,int* pnum_values){
+
+	_error_("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) _error_("Input provided is not a Thickness (enum_type is " << EnumToStringx(thickness_input->InstanceEnum()) << ")");
+
+	/*vertically integrate depending on type:*/
+	switch(thickness_input->ObjectEnum()){
+
+		case PentaP1InputEnum:
+			thickness_input->GetInputAverage(&thickness_value);
+			this->value=this->value*thickness_value;
+			return;
+
+		default:
+			_error_("not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION DoubleInput::PointwiseDivide{{{*/
+Input* DoubleInput::PointwiseDivide(Input* inputB){
+
+	/*Ouput*/
+	DoubleInput* outinput=NULL;
+
+	/*Intermediaries*/
+	IssmDouble       Bvalue;
+
+	/*Check that inputB is of the same type*/
+	inputB->GetInputAverage(&Bvalue);
+
+	/*Create new DoubleInput*/
+	outinput=new DoubleInput(this->enum_type,this->value/Bvalue);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::PointwiseMin{{{*/
+Input* DoubleInput::PointwiseMin(Input* input){
+
+	/*Ouput*/
+	DoubleInput* outinput=NULL;
+
+	/*Intermediaries*/
+	IssmDouble       min;
+
+	/*Check that inputB is of the same type*/
+	if (input->Min() < this->Min()) min=input->Min();
+	else min=this->Min();
+
+	/*Create new DoubleInput*/
+	outinput=new DoubleInput(this->enum_type,min);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::PointwiseMax{{{*/
+Input* DoubleInput::PointwiseMax(Input* input){
+
+	/*Ouput*/
+	DoubleInput* outinput=NULL;
+
+	/*Intermediaries*/
+	IssmDouble       max;
+
+	/*Check that inputB is of the same type*/
+	if (input->Max() > this->Max()) max=input->Max();
+	else max=this->Max();
+
+	/*Create new DoubleInput*/
+	outinput=new DoubleInput(this->enum_type,max);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION DoubleInput::Configure{{{*/
+void DoubleInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Inputs/DoubleInput.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/DoubleInput.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/DoubleInput.h	(revision 13395)
@@ -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){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(IssmDouble* pvalue);
+		void 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){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
+		IssmDouble InfinityNorm(void){_error_("not implemented yet");};
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _DOUBLEINPUT_H */
Index: /issm/trunk/src/c/classes/objects/Inputs/Input.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/Input.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/Input.h	(revision 13395)
@@ -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<IssmDouble>* 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/trunk/src/c/classes/objects/Inputs/IntInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/IntInput.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/IntInput.cpp	(revision 13395)
@@ -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){
+	
+	_error_("not supported yet!");
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION IntInput::GetInputValue(bool* pvalue) {{{*/
+void IntInput::GetInputValue(bool* pvalue){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(int* pvalue){{{*/
+void IntInput::GetInputValue(int* pvalue){
+	*pvalue=value;
+}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue){{{*/
+void IntInput::GetInputValue(IssmDouble* pvalue){
+	_error_("IntInput cannot return a IssmDouble in parallel");
+}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void IntInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
+void IntInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void IntInput::GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not supported yet!");}
+/*}}}*/
+/*FUNCTION IntInput::ChangeEnum{{{*/
+void IntInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION IntInput::SquareMin{{{*/
+void IntInput::SquareMin(IssmDouble* psquaremin, 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:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION IntInput::Constrain{{{*/
+void IntInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){
+
+	if(!xIsNan<IssmDouble>(cm_min)) if (this->value<cm_min)this->value=reCast<int>(cm_min);
+	if(!xIsNan<IssmDouble>(cm_max)) if (this->value>cm_max)this->value=reCast<int>(cm_max);
+
+}
+/*}}}*/
+/*FUNCTION IntInput::GetVectorFromInputs{{{*/
+void IntInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+
+	_error_("not supporte yet!");
+
+}
+/*}}}*/
+/*FUNCTION IntInput::GetValuesPtr{{{*/
+void IntInput::GetValuesPtr(IssmDouble** pvalues,int* pnum_values){
+
+	_error_("not supported yet!");
+
+}
+/*}}}*/
+/*FUNCTION IntInput::Configure{{{*/
+void IntInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Inputs/IntInput.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/IntInput.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/IntInput.h	(revision 13395)
@@ -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){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* inputB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue);
+		void GetInputValue(int* pvalue);
+		void GetInputValue(IssmDouble* pvalue);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Scale(IssmDouble scale_factor);
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
+		IssmDouble InfinityNorm(void){_error_("InfinityNorm not implemented for integers");};
+		IssmDouble Max(void){_error_("Max not implemented for integers");};
+		IssmDouble MaxAbs(void){_error_("Max not implemented for integers");};
+		IssmDouble Min(void){_error_("Min not implemented for integers");};
+		IssmDouble MinAbs(void){_error_("Min not implemented for integers");};
+		void Extrude(void){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _INTINPUT_H */
Index: /issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.cpp	(revision 13395)
@@ -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) _error_("not supported yet");
+			PentaP1Input* cast_input=(PentaP1Input*)cont_input->values;
+			for(i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*(cast_input->values[i]);}
+			return;
+		default:
+			_error_("not implemented yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::Constrain{{{*/
+void PentaP1Input::Constrain(IssmDouble cm_min, IssmDouble cm_max){
+
+	int i;
+	const int numnodes=6;
+		
+	if(!xIsNan<IssmDouble>(cm_min)) for(i=0;i<numnodes;i++)if (this->values[i]<cm_min)this->values[i]=cm_min;
+	if(!xIsNan<IssmDouble>(cm_max)) for(i=0;i<numnodes;i++)if (this->values[i]>cm_max)this->values[i]=cm_max;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::Extrude{{{*/
+void PentaP1Input::Extrude(void){
+
+	int i;
+
+	/*First 3 values copied on 3 last values*/
+	for(i=0;i<3;i++) this->values[3+i]=this->values[i];
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::VerticallyIntegrate{{{*/
+void PentaP1Input::VerticallyIntegrate(Input* thickness_input){
+
+	/*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) _error_("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:
+			_error_("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) _error_("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) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(PentaP1Input*)inputB;
+
+	/*Create point wise min*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] > xinputB->values[i]) minvalues[i]=xinputB->values[i];
+		else minvalues[i]=this->values[i];
+	}
+
+	/*Create new Penta vertex input (copy of current input)*/
+	outinput=new PentaP1Input(this->enum_type,&minvalues[0]);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::PointwiseMax{{{*/
+Input* PentaP1Input::PointwiseMax(Input* inputB){
+
+	/*Ouput*/
+	PentaP1Input* outinput=NULL;
+
+	/*Intermediaries*/
+	int               i;
+	PentaP1Input *xinputB     = NULL;
+	int               B_numvalues;
+	const int         numnodes    = 6;
+	IssmDouble            maxvalues[numnodes];
+
+	/*Check that inputB is of the same type*/
+	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(PentaP1Input*)inputB;
+
+	/*Create point wise max*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] < xinputB->values[i]) maxvalues[i]=xinputB->values[i];
+		else maxvalues[i]=this->values[i];
+	}
+
+	/*Create new Penta vertex input (copy of current input)*/
+	outinput=new PentaP1Input(this->enum_type,&maxvalues[0]);
+
+	/*Return output pointer*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION PentaP1Input::GetVectorFromInputs{{{*/
+void PentaP1Input::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+
+	const int numvertices=6;
+	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
+
+} /*}}}*/
+/*FUNCTION PentaP1Input::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/trunk/src/c/classes/objects/Inputs/PentaP1Input.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.h	(revision 13395)
@@ -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){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss);
+		void ChangeEnum(int newenumtype);
+
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum);
+		void Scale(IssmDouble scale_factor);
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
+		IssmDouble InfinityNorm(void);
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _PENTAP1INPUT_H */
Index: /issm/trunk/src/c/classes/objects/Inputs/TransientInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/TransientInput.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/TransientInput.cpp	(revision 13395)
@@ -0,0 +1,494 @@
+/*!\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(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);
+        xMemCpy(output->timesteps,this->timesteps,this->numtimesteps);
+	output->inputs=(Inputs*)this->inputs->Copy();
+	output->parameters=this->parameters;
+
+	return output;
+
+}
+/*}}}*/
+	
+/*TransientInput management*/
+/*FUNCTION TransientInput::InstanceEnum{{{*/
+int TransientInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::SpawnTriaInput{{{*/
+Input* TransientInput::SpawnTriaInput(int* indices){
+
+	/*output*/
+	TransientInput* outinput=NULL;
+
+	/*Create new Transientinput (copy of current input)*/
+	outinput=new TransientInput();
+	outinput->enum_type=this->enum_type;
+	outinput->numtimesteps=this->numtimesteps;
+	outinput->timesteps=xNew<IssmDouble>(this->numtimesteps);
+	xMemCpy(outinput->timesteps,this->timesteps,this->numtimesteps);
+	outinput->inputs=(Inputs*)this->inputs->SpawnTriaInputs(indices);
+	outinput->parameters=this->parameters;
+
+	/*Assign output*/
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::SpawnResult{{{*/
+ElementResult* TransientInput::SpawnResult(int step, IssmDouble time){
+
+	ElementResult* elementresult=NULL;
+
+	/*Ok, we want to spawn an ElementResult. We have the time, just get 
+	 *the correct values: */
+	Input* input=GetTimeInput(time);
+
+	elementresult=input->SpawnResult(step,time);
+
+   delete input;
+
+	return elementresult;
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION TransientInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){{{*/
+void TransientInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss){
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	this->parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputValue(pvalue,gauss);
+
+	delete input;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
+void TransientInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	this->parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputValue(pvalue,gauss);
+
+	delete input;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){{{*/
+void TransientInput::GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputValue(pvalue,gauss);
+
+	delete input;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){{{*/
+void TransientInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputValue(pvalue,gauss);
+
+	delete input;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussTria* gauss){{{*/
+void TransientInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussTria* gauss){
+
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+		   
+	/*Call input function*/
+	input->GetInputDerivativeValue(p,xyz_list,gauss);
+
+	delete input;
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::ChangeEnum{{{*/
+void TransientInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION TransientInput::GetInputAverage{{{*/
+void TransientInput::GetInputAverage(IssmDouble* pvalue){
+	
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+
+	/*Call input function*/
+	input->GetInputAverage(pvalue);
+			   
+	delete input;
+
+}
+/*}}}*/
+
+/*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);
+		xMemCpy(old_timesteps,this->timesteps,this->numtimesteps);
+		xDelete(this->timesteps);
+	}
+
+	this->numtimesteps=this->numtimesteps+1;
+	this->timesteps=xNew<IssmDouble>(this->numtimesteps);
+
+	if (this->numtimesteps > 1){
+		xMemCpy(this->timesteps,old_timesteps,this->numtimesteps-1);
+		xDelete(old_timesteps);
+	}
+
+	/*go ahead and plug: */
+	this->timesteps[this->numtimesteps-1]=time;
+	inputs->AddObject(input);
+
+}
+/*}}}*/
+/*FUNCTION TransientInput::Extrude{{{*/
+void TransientInput::Extrude(void){
+
+	for(int i=0;i<this->numtimesteps;i++){
+		((Input*)this->inputs->GetObjectByOffset(i))->Extrude();
+	}
+}
+/*}}}*/
+/*FUNCTION TransientInput::SquareMin{{{*/
+void TransientInput::SquareMin(IssmDouble* psquaremin, 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<IssmDouble>* vector,int* doflist){
+
+	IssmDouble time;
+
+	/*First, recover current time from parameters: */
+	parameters->FindParam(&time,TimeEnum);
+
+	/*Retrieve interpolated values for this time step: */
+	Input* input=GetTimeInput(time);
+		   
+	/*Call input function*/
+	input->GetVectorFromInputs(vector,doflist);
+			   
+	delete input;
+
+} /*}}}*/
+/*FUNCTION TransientInput::GetTimeInput{{{*/
+Input* TransientInput::GetTimeInput(IssmDouble intime){
+
+	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)_error_("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/trunk/src/c/classes/objects/Inputs/TransientInput.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/TransientInput.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/TransientInput.h	(revision 13395)
@@ -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){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* forcingB){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* forcingB){_error_("not implemented yet");};
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");};
+		void GetInputValue(int* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+
+		void SquareMin(IssmDouble* psquaremin, bool process_units,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum){_error_("not implemented yet");};
+		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		void AXPY(Input* xforcing,IssmDouble scalar){_error_("not implemented yet");};
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("not implemented yet");};
+		IssmDouble InfinityNorm(void);
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_forcing){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values){_error_("not supported yet");};
+      void GetTimeValues(IssmDouble* values,IssmDouble time){_error_("not implemented yet");};
+		Input* GetTimeInput(IssmDouble time);
+		/*}}}*/
+
+};
+#endif  /* _TRANSIENTINPUT_H */
Index: /issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.cpp	(revision 13395)
@@ -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 :
+			_error_("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<IssmDouble>* 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) _error_("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) _error_("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/trunk/src/c/classes/objects/Inputs/TriaP1Input.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.h	(revision 13395)
@@ -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){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* inputB);
+		Input* PointwiseMax(Input* inputB);
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*}}}*/
+		/*numerics: {{{*/
+		void GetInputValue(bool* pvalue){_error_("not implemented yet");}
+		void GetInputValue(int* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss);
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss);
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void ChangeEnum(int newenumtype);
+
+		void SquareMin(IssmDouble* psquaremin, 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){_error_("not supported yet");};
+		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+		void GetValuesPtr(IssmDouble** pvalues,int* pnum_values);
+		/*}}}*/
+
+};
+#endif  /* _TRIAP1INPUT_H */
Index: /issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.cpp	(revision 13395)
@@ -0,0 +1,724 @@
+/*!\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,**pcom2=NULL;
+
+	buffer=xNew<char>(buflen);
+	buffer[0]='\0';
+
+/*  read kml file character-by-character  */
+
+//  note that fgets includes newline
+//	fgets(buffer,buflen,fid);
+
+	while ((c=getc(fid)) != EOF) {
+		/*  ignore leading blanks  */
+		if (inew && isspace(c))
+			continue;
+
+		/*  distinguish between tag or field  */
+		if (!itag && !ifield) {
+
+			/*  distinguish between tag or comment  */
+			if (c == '<') {
+				ungetc(c,fid);
+				if (!(bufferc=KMLFileTokenComment(fid))) {
+					c=getc(fid);
+					itag=1;
+				}
+				else {
+					if (pncom && ppcom) {
+						(*pncom)++;
+						pcom2=xNew<char*>(*pncom);
+						memcpy(pcom2,*ppcom,(*pncom-1)*sizeof(char*));
+						xDelete<char*>(*ppcom);
+						*ppcom=pcom2;
+						pcom2=NULL;
+//						*ppcom=(char **) xrealloc(*ppcom,*pncom*sizeof(char*));
+						(*ppcom)[*pncom-1]=bufferc;
+					}
+					else
+						xDelete<char>(bufferc);
+					inew=1;
+					continue;
+				}
+			}
+			else
+				ifield=1;
+			inew=0;
+			KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+							   c,
+							   bufblk);
+		}
+
+		/*  accumulate tag, not including newlines  */
+		else if (itag) {
+			if (c != '\n') {
+				inew=0;
+				KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+								   c,
+								   bufblk);
+				if (c == '>')
+					break;
+			}
+			else
+				inew=1;
+		}
+
+		/*  accumulate field, including newlines  */
+		else if (ifield) {
+			/*  distinguish between another tag or comment  */
+			if (c == '<') {
+				ungetc(c,fid);
+				if (!(bufferc=KMLFileTokenComment(fid)))
+					break;
+				else
+					if (pncom && ppcom) {
+						(*pncom)++;
+						pcom2=xNew<char*>(*pncom);
+						memcpy(pcom2,*ppcom,(*pncom-1)*sizeof(char*));
+						xDelete<char*>(*ppcom);
+						*ppcom=pcom2;
+						pcom2=NULL;
+//						*ppcom=(char **) xrealloc(*ppcom,*pncom*sizeof(char*));
+						(*ppcom)[*pncom-1]=bufferc;
+					}
+					else
+						xDelete<char>(bufferc);
+			}
+			else {
+				inew=0;
+				KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+								   c,
+								   bufblk);
+				if (c == '\n')
+					inew=1;
+			}
+		}
+
+	}
+
+/*  remove trailing blanks or newline  */
+
+	while (ibuf > 0)
+		if (isspace(buffer[ibuf-1]))
+			ibuf--;
+		else {
+			buffer[ibuf]='\0';
+			break;
+		}
+
+//	if      (itag)
+//		_pprintLine_("tag buffer (length=" << ibuf << "):");
+//	else if (ifield)
+//		_pprintLine_("field buffer (length=" << ibuf << "):");
+//	_pprintLine_(buffer);
+
+	if (!ibuf)
+		xDelete<char>(buffer);
+
+	return(buffer);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenComment(FILE* fid) {{{*/
+char* KMLFileTokenComment(FILE* fid){
+
+/*  check for comment in the file and read it  */
+
+	bool    inew=1;
+	int     i;
+	int     c;
+	int     ibuf=0,buflen=1024,bufblk=1024;
+	char*   buffer=NULL;
+
+	buffer=xNew<char>(buflen);
+	buffer[0]='\0';
+
+/*  read kml file character-by-character  */
+
+	while ((c=getc(fid)) != EOF) {
+		/*  ignore leading blanks  */
+		if (inew && isspace(c))
+			continue;
+
+		inew=0;
+		KMLFileTokenBuffer(&buffer,&ibuf,&buflen,
+						   c,
+						   bufblk);
+
+		/*  check for comment  */
+		if (ibuf <= 4) {
+			if ((ibuf == 1 && buffer[0] != '<') ||
+				(ibuf == 2 && buffer[1] != '!') ||
+				(ibuf == 3 && buffer[2] != '-') ||
+				(ibuf == 4 && buffer[3] != '-')) {
+				for (i=ibuf-1; i>=0; i--)
+					ungetc(buffer[i],fid);
+				xDelete<char>(buffer);
+				return(buffer);
+			}
+		}
+
+		/*  accumulate comment, including newlines  */
+		else
+			if (buffer[ibuf-3]=='-' && buffer[ibuf-2]=='-' && buffer[ibuf-1]=='>')
+				break;
+	}
+
+/*  remove trailing blanks or newline  */
+
+	while (ibuf > 0)
+		if (isspace(buffer[ibuf-1]))
+			ibuf--;
+		else {
+			buffer[ibuf]='\0';
+			break;
+		}
+
+//	_pprintLine_("comment buffer (length=" << ibuf << "):");
+//	_pprintLine_(buffer);
+
+	if (!ibuf)
+		xDelete<char>(buffer);
+
+	return(buffer);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenBuffer {{{*/
+void KMLFileTokenBuffer(char** pbuffer,int* pibuf,int* pbuflen,
+						int c,
+						int bufblk){
+
+/*  add the specified character to the token buffer  */
+
+	char*   buffer2=NULL;
+
+/*  check buffer length and realloc if necessary  */
+
+	if (*pibuf+2 > *pbuflen) {
+		*pbuflen+=bufblk;
+		buffer2=xNew<char>(*pbuflen);
+		memcpy(buffer2,*pbuffer,(*pbuflen-bufblk)*sizeof(char));
+		xDelete<char>(*pbuffer);
+		*pbuffer=buffer2;
+		buffer2=NULL;
+//		*pbuffer=(char *) xrealloc(*pbuffer,*pbuflen*sizeof(char));
+	}
+
+/*  add character and terminator  */
+
+	(*pbuffer)[(*pibuf)++]=c;
+	(*pbuffer)[ *pibuf   ]='\0';
+
+	return;
+}
+/*}}}*/
+/*FUNCTION  KMLFileTagName {{{*/
+char* KMLFileTagName(char* pname,
+					 char* ktag){
+
+	return(KMLFileTagName(pname,NULL,0,
+						  ktag));
+}
+/*}}}*/
+/*FUNCTION  KMLFileTagName {{{*/
+char* KMLFileTagName(char* pname,int *m,int maxlen,
+					 char* ktag){
+
+/*  for the given tag buffer, read and store the name  */
+
+	char*   ktagi;
+	char*   ktokn;
+
+	if (strncmp(&ktag[0],"<"        ,1) || strncmp(&ktag[strlen(ktag)-1],">",1))
+		_error_("KMLFileTagName -- Missing tag delimiters in " << ktag << ".\n");
+
+/*  strtok modifies ktag, so work on copy  */
+
+	ktagi=xNew<char>(strlen(ktag)+1);
+	memcpy(ktagi,ktag,(strlen(ktag)+1)*sizeof(char));
+
+/*  skip opening delimeter and find subsequent blank or closing delimiter  */
+
+	ktokn=strtok(ktagi,"< >");
+//	_pprintLine_("KMLFileTagName -- initial token=\"" << ktokn << "\".");
+
+	if (!pname) {
+		if (maxlen)
+			pname=xNew<char>(maxlen       +1);
+		else
+			pname=xNew<char>(strlen(ktokn)+1);
+	}
+
+	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));
+
+	xDelete<char>(ktagi);
+
+	if (m)
+		*m=strlen(pname);
+
+	return(pname);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTagAttrib {{{*/
+int KMLFileTagAttrib(KML_Object* kobj,
+					 char* ktag){
+
+/*  for the given tag buffer, read and store the attributes  */
+
+	char*   ktagi;
+	char*   ktokn;
+	char*   ktokv;
+	char    quote[]={'\"','\0'};
+	int     isolo=0;
+
+/*  strtok modifies ktag, so work on copy  */
+
+	ktagi=xNew<char>(strlen(ktag)+1);
+	memcpy(ktagi,ktag,(strlen(ktag)+1)*sizeof(char));
+
+/*  loop through tag to find all attributes  */
+
+	/*  return first non blank and move past subsequent blank  */
+	ktokn=strtok(ktagi," ");
+//	_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);
+	}
+
+	xDelete<char>(ktagi);
+
+/*  check for xml declaration, dtd declaration, or solo tag  */
+
+	if ((!strncmp(&ktag[0],"<?"       ,2) && !strncmp(&ktag[strlen(ktag)-2],"?>",2)) ||
+		(!strncmp(&ktag[0],"<!DOCTYPE",9) && !strncmp(&ktag[strlen(ktag)-1], ">",1)) ||
+		(!strncmp(&ktag[0],"<"        ,1) && !strncmp(&ktag[strlen(ktag)-2],"/>",2)))
+		isolo=1;
+//	_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] == '<'))
+		_error_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");
+
+	sscanf(kstr,"%d",pival);
+	xDelete<char>(kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_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] == '<'))
+	  {_error_("KMLFileTokenParse -- Missing bool field for " << ktag << ".\n");}
+
+	sscanf(kstr,"%d",&ival);
+	*pbval=(bool)ival;
+	xDelete<char>(kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_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] == '<'))
+		_error_("KMLFileTokenParse -- Missing string field for " << ktag << ".\n");
+
+	if (!pstr) {
+		if (maxlen)
+			pstr=xNew<char>(maxlen      +1);
+		else
+			pstr=xNew<char>(strlen(kstr)+1);
+	}
+
+	if (maxlen && (maxlen < strlen(kstr))) {
+		_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));
+
+	xDelete<char>(kstr);
+
+	if (m)
+		*m=strlen(pstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_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] == '<'))
+	  {_error_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");}
+
+	sscanf(kstr,"%g",pfval);
+	xDelete<char>(kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_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] == '<'))
+		_error_("KMLFileTokenParse -- Missing integer field for " << ktag << ".\n");
+
+	sscanf(kstr,"%lg",pdval);
+	xDelete<char>(kstr);
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_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;
+	double* dval2=NULL;
+	char    delim[]={' ',',','\f','\n','\r','\t','\v','\0'};
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing double [m] field for " << ktag << ".\n");
+
+	if (!*pdval)
+		if (maxlen)
+			*pdval=xNew<IssmDouble>(maxlen            );
+		else
+			*pdval=xNew<IssmDouble>((strlen(kstr)+1)/2);
+
+/*  loop through string to get all values  */
+
+	ktok=strtok(kstr,delim);
+	while (ktok) {
+		i++;
+		if (maxlen && (maxlen < i+1))
+			_error_("KMLFileTokenParse -- Double [m] field too short for " << ktag << ".\n");
+		sscanf(ktok,"%lg",&((*pdval)[i]));
+		ktok=strtok(NULL,delim);
+	}
+	xDelete<char>(kstr);
+
+	if (!maxlen)
+		dval2=xNew<double>(i+1);
+		memcpy(dval2,*pdval,(i+1)*sizeof(double));
+		xDelete<double>(*pdval);
+		*pdval=dval2;
+		dval2=NULL;
+//		*pdval=(double *) xrealloc(*pdval,(i+1)*sizeof(double));
+
+	if (m)
+		*m=i+1;
+
+/*  get additional token and compare to closing tag  */
+
+	if (ktag)
+		if (!(kstr=KMLFileToken(fid,
+								NULL,NULL)) ||
+			(kstr[0] != '<') ||
+			(kstr[1] != '/') ||
+			(strncmp(&(kstr[2]),&(ktag[1]),strlen(ktag)-1)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_pprintLine_("KMLFileTokenParse -- " << ktag << "=...");
+//	for (j=0; j<=i; j++)
+//		_pprintLine_("   [" << j << "]: " << (*pdval)[j] << "g");
+
+	return(0);
+}
+/*}}}*/
+/*FUNCTION  KMLFileTokenParse {{{*/
+int KMLFileTokenParse(double **pdval,int* m,int n,int maxlen,
+					  char* ktag,
+					  FILE* fid){
+
+	int     i=-1,j=-1;
+	char*   kstr;
+	char*   ktok;
+	double* dval2=NULL;
+	char    delim[]={' ',',','\f','\n','\r','\t','\v','\0'};
+
+/*  get next token and allocate if necessary  */
+
+	if (!(kstr=KMLFileToken(fid,
+							NULL,NULL)) ||
+		(kstr[0] == '<'))
+		_error_("KMLFileTokenParse -- Missing double [m x n] field for " << ktag << ".\n");
+
+	if (!*pdval)
+		if (maxlen)
+			*pdval=xNew<IssmDouble>(maxlen*n          );
+		else
+			*pdval=xNew<IssmDouble>((strlen(kstr)+1)/2);
+
+/*  loop through string to get all values  */
+
+	ktok=strtok(kstr,delim);
+	while (ktok) {
+		i++;
+		if (maxlen && (maxlen*n < i+1))
+			_error_("KMLFileTokenParse -- Double [m x n] field too short for " << ktag << ".\n");
+		j=(j+1) % n;
+		sscanf(ktok,"%lg",&((*pdval)[i]));
+		ktok=strtok(NULL,delim);
+	}
+	xDelete<char>(kstr);
+
+	if (!maxlen)
+		dval2=xNew<double>((i+1)*n);
+		memcpy(dval2,*pdval,((i+1)*n)*sizeof(double));
+		xDelete<double>(*pdval);
+		*pdval=dval2;
+		dval2=NULL;
+//		*pdval=(double *) xrealloc(*pdval,((i+1)*n)*sizeof(double));
+
+	if (m)
+		*m=((i+1)+(n-1))/n;
+
+	if ((i+1) % n)
+		_pprintLine_("KMLFileTokenParse -- Double [m x n] field for " << ktag << " does not have multiple of n 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)))
+		  {_error_("KMLFileTokenParse -- Missing closing tag for " << ktag << ".\n");}
+		else
+			xDelete<char>(kstr);
+
+//	_pprintLine_("KMLFileTokenParse -- " << ktag << "=...");
+//	for (j=0; j<=i; j++)
+//		_pprintLine_("   [" << j << "]: " << (*pdval)[j] << "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 << ".");
+			xDelete<char>(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] == '/')) {
+			_error_("KMLFileTagSkip -- Unexpected closing tag " << kstr << ".\n");
+		}
+
+		xDelete<char>(kstr);
+	}
+
+	_error_("KMLFileTokenParse -- Corresponding closing tag for " << ktag << " not found.\n");
+
+	return(0);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.h	(revision 13395)
@@ -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 **pdval,int* m,int n,int maxlen,
+					  char* ktag,
+					  FILE* fid);
+int KMLFileTagSkip(char* ktag,
+				   FILE* fid);
+
+#endif  /* _KMLFILEREADUTILS_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Attribute.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Attribute.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Attribute.cpp	(revision 13395)
@@ -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      ) xDelete<char>(name);
+	if (value     ) xDelete<char>(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 =xNew<char>(strlen(namei )+1);
+	memcpy(name,namei,(strlen(namei)+1)*sizeof(char));
+
+	value=xNew<char>(strlen(valuei)+1);
+	memcpy(value,valuei,(strlen(valuei)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::Add {{{*/
+void  KML_Attribute::Add(DataSet* attrib){
+
+	attrib->AddObject((Object*)this);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Attribute::Get {{{*/
+void  KML_Attribute::Get(char** pvalueo,char* deflt){
+
+	if (!value || !strlen(value)) {
+		*pvalueo=xNew<char>(strlen(deflt)+1);
+		memcpy(*pvalueo,deflt,(strlen(deflt)+1)*sizeof(char));
+	}
+	else {
+		*pvalueo=xNew<char>(strlen(value)+1);
+		memcpy(*pvalueo,value,(strlen(value)+1)*sizeof(char));
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Attribute.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Attribute.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Attribute.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+		/*virtual functions: */
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  Alloc(const char* namei,const char* valuei);
+		void  Add(DataSet* attrib);
+		void  Get(char** pvalueo,char* deflt);
+
+};
+#endif  /* _KML_ATTRIBUTE_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_ColorStyle.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_ColorStyle.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_ColorStyle.cpp	(revision 13395)
@@ -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))
+	  {_error_("KML_ColorStyle::Read -- Unexpected closing tag " << kstr);}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_ColorStyle::Read -- Unexpected field \"" << kstr << "\"");}
+
+	else if (!strcmp(kstr,"<color>"))
+		KMLFileTokenParse( color     ,NULL,KML_COLORSTYLE_COLOR_LENGTH, kstr, fid);
+	else if (!strcmp(kstr,"<colorMode>"))
+		KMLFileTokenParse( colormode ,NULL,KML_COLORSTYLE_COLORMODE_LENGTH, kstr, fid);
+
+	else if (!strncmp(kstr,"<",1))
+		KML_SubStyle::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_ColorStyle.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_ColorStyle.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_ColorStyle.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_COLORSTYLE_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Comment.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Comment.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Comment.cpp	(revision 13395)
@@ -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     ) xDelete<char>(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=xNew<char>(strlen(valuei)+1);
+	memcpy(value,valuei,(strlen(valuei)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::Add {{{*/
+void  KML_Comment::Add(DataSet* commnt){
+
+	commnt->AddObject((Object*)this);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Comment::Get {{{*/
+void  KML_Comment::Get(char** pvalueo){
+
+	*pvalueo=xNew<char>(strlen(value)+1);
+	memcpy(*pvalueo,value,(strlen(value)+1)*sizeof(char));
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Comment.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Comment.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Comment.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+		/*virtual functions: */
+		void  Write(FILE* fid,const char* indent);
+		void  Read(FILE* fid,char* kstr);
+		void  Alloc(const char* valuei);
+		void  Add(DataSet* commnt);
+		void  Get(char** pvalueo);
+
+};
+#endif  /* _KML_COMMENT_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Container.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Container.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Container.cpp	(revision 13395)
@@ -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)) {
+		xDelete<char>(kstr);
+		return;
+	}
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_Container::Read -- Unexpected closing tag " << kstr );}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Container::Read -- Unexpected field \"" << kstr << "\"");}
+
+	else if (!strncmp(kstr,"<Placemark",10)) {
+		kobj=(KML_Object*)new KML_Placemark();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Folder", 7)) {
+		kobj=(KML_Object*)new KML_Folder();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Document", 9)) {
+		kobj=(KML_Object*)new KML_Document();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<GroundOverlay",14)) {
+		kobj=(KML_Object*)new KML_GroundOverlay();
+		kobj->Read(fid,kstr);
+		feature   ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Feature::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Container::WriteExp {{{*/
+void  KML_Container::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+
+/*  loop over the features for the container  */
+
+	for (i=0; i<feature->Size(); i++)
+		((KML_Object *)feature->GetObjectByOffset(i))->WriteExp(fid,nstr,sgn,cm,sp);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Container.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Container.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Container.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_CONTAINER_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Document.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Document.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Document.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Document::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Document::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Container::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Document.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Document.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Document.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_DOCUMENT_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Feature.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Feature.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Feature.cpp	(revision 13395)
@@ -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))
+	  {_error_("KML_Feature::Read -- Unexpected closing tag " << kstr);}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Feature::Read -- Unexpected field \"" << kstr << "\"");}
+
+	else if (!strncmp(kstr,"<Style", 6)) {
+		kobj=(KML_Object*)new KML_Style();
+		kobj->Read(fid,kstr);
+		style     ->AddObject((Object*)kobj);
+	}
+
+	else if (!strcmp(kstr,"<name>"))
+		KMLFileTokenParse( name      ,NULL,KML_FEATURE_NAME_LENGTH, kstr, fid);
+	else if (!strcmp(kstr,"<visibility>"))
+		KMLFileTokenParse(&visibility, kstr, fid);
+	else if (!strcmp(kstr,"<open>"))
+		KMLFileTokenParse(&open      , kstr, fid);
+	else if (!strncmp(kstr,"<snippet", 8))
+		KMLFileTokenParse( snippet   ,NULL,KML_FEATURE_SNIPPET_LENGTH, kstr, fid);
+	else if (!strcmp(kstr,"<description>"))
+		KMLFileTokenParse( descript  ,NULL,KML_FEATURE_DESCRIPT_LENGTH, kstr, fid);
+	else if (!strcmp(kstr,"<styleUrl>"))
+		KMLFileTokenParse( styleurl  ,NULL,KML_FEATURE_STYLEURL_LENGTH, kstr, fid);
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Feature.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Feature.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Feature.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FEATURE_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_File.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_File.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_File.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_File::Read -- Unexpected closing tag " << kstri << ".");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_File::Read -- Unexpected field \"" << kstri << "\"");}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_File::WriteExp {{{*/
+void  KML_File::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+
+/*  loop over the kml objects for the file  */
+
+	for (i=0; i<kmlobj->Size(); i++)
+		((KML_Object *)kmlobj->GetObjectByOffset(i))->WriteExp(fid,nstr,sgn,cm,sp);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_File.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_File.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_File.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FILE_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Folder.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Folder.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Folder.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Folder::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Folder::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Container::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Folder.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Folder.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Folder.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_FOLDER_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Geometry.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Geometry.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Geometry.cpp	(revision 13395)
@@ -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))
+	  {_error_("KML_Geometry::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Geometry::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Geometry.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Geometry.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Geometry.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_GEOMETRY_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_GroundOverlay.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_GroundOverlay.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_GroundOverlay.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_GroundOverlay::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_GroundOverlay::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<altitude>"))
+			KMLFileTokenParse(&altitude  ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_GROUNDOVERLAY_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strncmp(kstri,"<LatLonBox",10)) {
+			llbox     =new KML_LatLonBox();
+			llbox     ->Read(fid,kstri);
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Overlay::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_GroundOverlay.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_GroundOverlay.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_GroundOverlay.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_GROUNDOVERLAY_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Icon.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Icon.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Icon.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Icon::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Icon::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<href>"))
+			KMLFileTokenParse( href      ,NULL,KML_ICON_HREF_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<refreshMode>"))
+			KMLFileTokenParse( refmode   ,NULL,KML_ICON_REFMODE_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<refreshInterval>"))
+			KMLFileTokenParse(&refint    , kstri, fid);
+		else if (!strcmp(kstri,"<viewRefreshMode>"))
+			KMLFileTokenParse( vrefmode  ,NULL,KML_ICON_VREFMODE_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<viewRefreshTime>"))
+			KMLFileTokenParse(&vreftime  , kstri, fid);
+		else if (!strcmp(kstri,"<viewBoundScale>"))
+			KMLFileTokenParse(&vboundsc  , kstri, fid);
+		else if (!strcmp(kstri,"<viewFormat>"))
+			KMLFileTokenParse( vformat   ,NULL,KML_ICON_VFORMAT_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<httpQuery>"))
+			KMLFileTokenParse( hquery    ,NULL,KML_ICON_HQUERY_LENGTH, kstri, fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Icon.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Icon.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Icon.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_ICON_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_LatLonBox.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_LatLonBox.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LatLonBox.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_LatLonBox::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_LatLonBox::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<north>"))
+			KMLFileTokenParse(&north     ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<south>"))
+			KMLFileTokenParse(&south     ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<east>"))
+			KMLFileTokenParse(&east      ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<west>"))
+			KMLFileTokenParse(&west      ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<rotation>"))
+			KMLFileTokenParse(&rotation  ,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_LatLonBox.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_LatLonBox.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LatLonBox.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LATLONBOX_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_LineString.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_LineString.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LineString.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_LineString::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_LineString::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<tessellate>"))
+			KMLFileTokenParse(&tessellate,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_LINESTRING_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<coordinates>"))
+			KMLFileTokenParse(&coords    ,&ncoord    ,0,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LineString::WriteExp {{{*/
+void  KML_LineString::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int     i;
+	double  *lat,*lon,*x,*y;
+	char    nstr2[81];
+
+/*  extract latitude and longitude into vectors  */
+
+	lat=xNew<IssmDouble>(ncoord);
+	lon=xNew<IssmDouble>(ncoord);
+	for (i=0; i<ncoord; i++) {
+		lon[i]=coords[3*i+0];
+		lat[i]=coords[3*i+1];
+	}
+
+/*  convert latitude and longitude to x and y  */
+
+	x  =xNew<IssmDouble>(ncoord);
+	y  =xNew<IssmDouble>(ncoord);
+	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");
+
+	xDelete<IssmDouble>(y);
+	xDelete<IssmDouble>(x);
+	xDelete<IssmDouble>(lon);
+	xDelete<IssmDouble>(lat);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_LineString.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_LineString.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LineString.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINESTRING_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_LineStyle.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_LineStyle.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LineStyle.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_LineStyle::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_LineStyle::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<width>"))
+			KMLFileTokenParse(&width     ,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_ColorStyle::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_LineStyle.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_LineStyle.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LineStyle.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINESTYLE_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_LinearRing.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_LinearRing.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LinearRing.cpp	(revision 13395)
@@ -0,0 +1,224 @@
+/*!\file KML_LinearRing.cpp
+ * \brief: implementation of the kml_linearring object
+ */
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <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))
+		  {_error_("KML_LinearRing::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_LinearRing::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude,kstri,fid);
+		else if (!strcmp(kstri,"<tessellate>"))
+			KMLFileTokenParse(&tessellate,kstri,fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse(altmode,NULL,KML_LINEARRING_ALTMODE_LENGTH,kstri,fid);
+		else if (!strcmp(kstri,"<coordinates>"))
+			KMLFileTokenParse(&coords,&ncoord,3,0,kstri,fid);
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for(ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_LinearRing::WriteExp {{{*/
+void  KML_LinearRing::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int     i;
+	double  *lat,*lon,*x,*y;
+	char    nstr2[81];
+
+/*  extract latitude and longitude into vectors  */
+
+	lat=xNew<IssmDouble>(ncoord);
+	lon=xNew<IssmDouble>(ncoord);
+	for (i=0; i<ncoord; i++) {
+		lon[i]=coords[3*i+0];
+		lat[i]=coords[3*i+1];
+	}
+
+/*  convert latitude and longitude to x and y  */
+
+	x  =xNew<IssmDouble>(ncoord);
+	y  =xNew<IssmDouble>(ncoord);
+	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/trunk/src/c/classes/objects/KML/KML_LinearRing.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_LinearRing.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LinearRing.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_LINEARRING_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_MultiGeometry.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_MultiGeometry.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_MultiGeometry.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_MultiGeometry::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_MultiGeometry::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<Point", 6)) {
+			kobj=(KML_Object*)new KML_Point();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LineString",11)) {
+			kobj=(KML_Object*)new KML_LineString();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LinearRing",11)) {
+			kobj=(KML_Object*)new KML_LinearRing();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Polygon", 8)) {
+			kobj=(KML_Object*)new KML_Polygon();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<MultiGeometry",14)) {
+			kobj=(KML_Object*)new KML_MultiGeometry();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_MultiGeometry::WriteExp {{{*/
+void  KML_MultiGeometry::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+
+/*  loop over the geometry elements for the multigeometry  */
+
+	for (i=0; i<geometry->Size(); i++)
+		((KML_Object *)geometry->GetObjectByOffset(i))->WriteExp(fid,nstr,sgn,cm,sp);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_MultiGeometry.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_MultiGeometry.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_MultiGeometry.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_MULTIGEOMETRY_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Object.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Object.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Object.cpp	(revision 13395)
@@ -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))
+	  {_error_("KML_Object::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Object::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<Placemark",10)) {
+		kobj=(KML_Object*)new KML_Placemark();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Folder", 7)) {
+		kobj=(KML_Object*)new KML_Folder();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Document", 9)) {
+		kobj=(KML_Object*)new KML_Document();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<GroundOverlay",14)) {
+		kobj=(KML_Object*)new KML_GroundOverlay();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<LatLonBox",10)) {
+		kobj=(KML_Object*)new KML_LatLonBox();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Icon", 5)) {
+		kobj=(KML_Object*)new KML_Icon();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Point", 6)) {
+		kobj=(KML_Object*)new KML_Point();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<LineString",11)) {
+		kobj=(KML_Object*)new KML_LineString();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<LinearRing",11)) {
+		kobj=(KML_Object*)new KML_LinearRing();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<Polygon", 8)) {
+		kobj=(KML_Object*)new KML_Polygon();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<MultiGeometry",14)) {
+		kobj=(KML_Object*)new KML_MultiGeometry();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+//	else if (!strncmp(kstr,"<IconStyle",10)) {
+//		kobj=(KML_Object*)new KML_IconStyle();
+//		kobj->Read(fid,kstr);
+//		kmlobj    ->AddObject((Object*)kobj);
+//	}
+
+//	else if (!strncmp(kstr,"<LabelStyle",11)) {
+//		kobj=(KML_Object*)new KML_LabelStyle();
+//		kobj->Read(fid,kstr);
+//		kmlobj    ->AddObject((Object*)kobj);
+//	}
+
+	else if (!strncmp(kstr,"<LineStyle",10)) {
+		kobj=(KML_Object*)new KML_LineStyle();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+	else if (!strncmp(kstr,"<PolyStyle",10)) {
+		kobj=(KML_Object*)new KML_PolyStyle();
+		kobj->Read(fid,kstr);
+		kmlobj    ->AddObject((Object*)kobj);
+	}
+
+//	else if (!strncmp(kstr,"<BalloonStyle",13)) {
+//		kobj=(KML_Object*)new KML_BalloonStyle();
+//		kobj->Read(fid,kstr);
+//		kmlobj    ->AddObject((Object*)kobj);
+//	}
+
+//	else if (!strncmp(kstr,"<ListStyle",10)) {
+//		kobj=(KML_Object*)new KML_ListStyle();
+//		kobj->Read(fid,kstr);
+//		kmlobj    ->AddObject((Object*)kobj);
+//	}
+
+	else if (!strncmp(kstr,"<",1)) {
+		_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=xNew<char>(strlen(deflt)+1);
+		memcpy(*pvalue,deflt,(strlen(deflt)+1)*sizeof(char));
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::WriteAttrib {{{*/
+void  KML_Object::WriteAttrib(FILE* filout,const char* indent){
+
+//  attributes always written in keyword line of kml_object
+
+/*  loop over any attributes for the object  */
+
+	if (attrib->Size())
+		for (int i=0; i<attrib->Size(); i++)
+			((KML_Attribute *)attrib->GetObjectByOffset(i))->Write(filout,indent);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::AddCommnt {{{*/
+void  KML_Object::AddCommnt(int ncom,char** pcom){
+
+	int   i;
+	KML_Comment* kcom=NULL;
+
+	for (i=0; i<ncom; i++) {
+		kcom=new KML_Comment();
+		kcom->Alloc(pcom[i]);
+		kcom->Add(commnt);
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::AddCommnt {{{*/
+void  KML_Object::AddCommnt(char* value){
+
+	KML_Comment* kcom=NULL;
+
+	kcom=new KML_Comment();
+	kcom->Alloc(value);
+	kcom->Add(commnt);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::FindCommnt {{{*/
+void  KML_Object::FindCommnt(char** pvalue,int inum){
+
+	KML_Comment* kcom=NULL;
+
+/*  loop over any comments for the object  */
+
+	if (inum <= commnt->Size())
+		kcom=(KML_Comment *)commnt->GetObjectByOffset(inum-1);
+
+/*  if found, get the value; otherwise use the NULL  */
+
+	if (kcom)
+		kcom->Get(pvalue);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Object::WriteCommnt {{{*/
+void  KML_Object::WriteCommnt(FILE* filout,const char* indent){
+
+	int   i;
+
+//  comments always written after keyword line of kml_object
+
+/*  loop over any comments for the object  */
+
+	if (commnt->Size())
+		for (i=0; i<commnt->Size(); i++)
+			((KML_Comment *)commnt->GetObjectByOffset(i))->Write(filout,indent);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Object.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Object.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Object.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+		/*virtual functions: */
+		virtual void  Write(FILE* fid,const char* indent)=0;
+		virtual void  Read(FILE* fid,char* kstr)=0;
+		virtual void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
+		virtual void  AddAttrib(const char* name,const char* value);
+		virtual void  FindAttrib(char** pvalue,char* name,char* deflt);
+		virtual void  WriteAttrib(FILE* fid,const char* indent);
+		virtual void  AddCommnt(int ncom,char** pcom);
+		virtual void  AddCommnt(char* value);
+		virtual void  FindCommnt(char** pvalue,int inum);
+		virtual void  WriteCommnt(FILE* fid,const char* indent);
+
+};
+#endif  /* _KML_OBJECT_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Overlay.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Overlay.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Overlay.cpp	(revision 13395)
@@ -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)) {
+		xDelete<char>(kstr);
+		return;
+	}
+	else if (!strncmp(kstr,"</",2))
+	  {_error_("KML_Overlay::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_Overlay::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strcmp(kstr,"<color>"))
+		KMLFileTokenParse( color     ,NULL,KML_OVERLAY_COLOR_LENGTH,
+						  kstr,
+						  fid);
+	else if (!strcmp(kstr,"<drawOrder>"))
+		KMLFileTokenParse(&draword   ,
+						  kstr,
+						  fid);
+
+	else if (!strncmp(kstr,"<Icon", 5)) {
+		icon      =new KML_Icon();
+		icon      ->Read(fid,kstr);
+	}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Feature::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Overlay.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Overlay.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Overlay.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_OVERLAY_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Placemark.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Placemark.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Placemark.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Placemark::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Placemark::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strncmp(kstri,"<Point", 6)) {
+			kobj=(KML_Object*)new KML_Point();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LineString",11)) {
+			kobj=(KML_Object*)new KML_LineString();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<LinearRing",11)) {
+			kobj=(KML_Object*)new KML_LinearRing();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<Polygon", 8)) {
+			kobj=(KML_Object*)new KML_Polygon();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<MultiGeometry",14)) {
+			kobj=(KML_Object*)new KML_MultiGeometry();
+			kobj->Read(fid,kstri);
+			geometry  ->AddObject((Object*)kobj);
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Feature::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Placemark::WriteExp {{{*/
+void  KML_Placemark::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+	char  nstr2[81];
+
+/*  loop over the geometry elements for the placemark  */
+
+	for (i=0; i<geometry->Size(); i++) {
+		if (strlen(nstr))
+			sprintf(nstr2,"%s %s",nstr,name);
+		else
+			sprintf(nstr2,"%s",name);
+
+		((KML_Object *)geometry->GetObjectByOffset(i))->WriteExp(fid,nstr2,sgn,cm,sp);
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Placemark.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Placemark.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Placemark.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_PLACEMARK_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Point.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Point.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Point.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Point::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Point::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   , kstri, fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_POINT_ALTMODE_LENGTH, kstri, fid);
+		else if (!strcmp(kstri,"<coordinates>"))
+			KMLFileTokenParse(&pcoords   ,NULL,3, kstri, fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Point::WriteExp {{{*/
+void  KML_Point::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int     i;
+	double  lat,lon,x,y;
+	char    nstr2[81];
+
+/*  extract latitude and longitude  */
+
+	lon=coords[0];
+	lat=coords[1];
+
+/*  convert latitude and longitude to x and y  */
+
+	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/trunk/src/c/classes/objects/KML/KML_Point.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Point.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Point.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POINT_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_PolyStyle.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_PolyStyle.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_PolyStyle.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_PolyStyle::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_PolyStyle::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<fill>"))
+			KMLFileTokenParse(&fill      ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<outline>"))
+			KMLFileTokenParse(&outline   ,
+							  kstri,
+							  fid);
+
+		else if (!strncmp(kstri,"<",1))
+			KML_ColorStyle::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_PolyStyle.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_PolyStyle.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_PolyStyle.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POLYSTYLE_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Polygon.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Polygon.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Polygon.cpp	(revision 13395)
@@ -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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Polygon::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Polygon::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+		else if (!strcmp(kstri,"<extrude>"))
+			KMLFileTokenParse(&extrude   ,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<tessellate>"))
+			KMLFileTokenParse(&tessellate,
+							  kstri,
+							  fid);
+		else if (!strcmp(kstri,"<altitudeMode>"))
+			KMLFileTokenParse( altmode   ,NULL,KML_POLYGON_ALTMODE_LENGTH,
+							  kstri,
+							  fid);
+
+		else if (!strcmp(kstri,"<outerBoundaryIs>"))
+
+/*  loop over and process fields within outer boundary  */
+
+			while (kstrj=KMLFileToken(fid,
+									  &ncom,&pcom)) {
+				if      (!strncmp(kstrj,"</outerBoundaryIs",17)) {
+					xDelete<char>(kstrj);
+					break;
+				}
+				else if (!strncmp(kstrj,"</",2))
+				  {_error_("KML_Polygon::Read -- Unexpected closing tag " << kstrj << ".\n");}
+				else if (strncmp(kstrj,"<",1))
+				  {_error_("KML_Polygon::Read -- Unexpected field \"" << kstrj << "\".\n");}
+
+				else if (!strncmp(kstrj,"<LinearRing",11)) {
+					kobj=(KML_Object*)new KML_LinearRing();
+					kobj->Read(fid,kstrj);
+					outer     ->AddObject((Object*)kobj);
+				}
+
+				else if (!strncmp(kstrj,"<",1))
+					KML_Geometry::Read(fid,kstrj);
+
+				xDelete<char>(kstrj);
+			}
+
+		else if (!strcmp(kstri,"<innerBoundaryIs>"))
+
+/*  loop over and process fields within inner boundaries  */
+
+			while (kstrj=KMLFileToken(fid,
+									  &ncom,&pcom)) {
+				if      (!strncmp(kstrj,"</innerBoundaryIs",17)) {
+					xDelete<char>(kstrj);
+					break;
+				}
+				else if (!strncmp(kstrj,"</",2))
+				  {_error_("KML_Polygon::Read -- Unexpected closing tag " << kstrj << ".\n");}
+				else if (strncmp(kstrj,"<",1))
+				  {_error_("KML_Polygon::Read -- Unexpected field \"" << kstrj << "\".\n");}
+
+				else if (!strncmp(kstrj,"<LinearRing",11)) {
+					kobj=(KML_Object*)new KML_LinearRing();
+					kobj->Read(fid,kstrj);
+					inner     ->AddObject((Object*)kobj);
+				}
+
+				else if (!strncmp(kstrj,"<",1))
+					KML_Geometry::Read(fid,kstrj);
+
+				xDelete<char>(kstrj);
+			}
+
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Geometry::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Polygon::WriteExp {{{*/
+void  KML_Polygon::WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp){
+
+	int   i;
+	char  nstr2[81];
+
+/*  check outer boundary for the polygon  */
+
+	if (outer->Size()) {
+		if (strlen(nstr))
+			sprintf(nstr2,"%s (outer)",nstr);
+		else
+			sprintf(nstr2,"(outer)");
+
+		((KML_LinearRing *)outer->GetObjectByOffset(0))->WriteExp(fid,nstr2,sgn,cm,sp);
+	}
+
+/*  loop over any inner boundaries for the polygon  */
+
+	for (i=0; i<inner->Size(); i++) {
+		if (strlen(nstr))
+			sprintf(nstr2,"%s (inner %d of %d)",nstr,i+1,inner->Size());
+		else
+			sprintf(nstr2,"(inner %d of %d)",i+1,inner->Size());
+
+		((KML_LinearRing *)inner->GetObjectByOffset(i))->WriteExp(fid,nstr2,sgn,cm,sp);
+	}
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Polygon.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Polygon.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Polygon.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_POLYGON_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Style.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Style.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Style.cpp	(revision 13395)
@@ -0,0 +1,239 @@
+/*!\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;
+		list      =NULL;
+	}
+	if (balloon) {
+//		delete balloon;
+		balloon   =NULL;
+	}
+	if (poly) {
+		delete poly;
+		poly      =NULL;
+	}
+	if (line) {
+		delete line;
+		line      =NULL;
+	}
+	if (label) {
+//		delete label;
+		label     =NULL;
+	}
+	if (icon) {
+//		delete icon;
+		icon      =NULL;
+	}
+
+}
+/*}}}*/
+
+/*Other*/
+/*FUNCTION KML_Style::Echo {{{*/
+void  KML_Style::Echo(){
+
+	bool  flag=true;
+
+	if(flag) _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)) {
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Style::Read -- Unexpected closing tag " << kstri << ".\n");}
+		else if (strncmp(kstri,"<",1))
+		  {_error_("KML_Style::Read -- Unexpected field \"" << kstri << "\".\n");}
+
+//		else if (!strncmp(kstri,"<IconStyle",10)) {
+//			icon      =new KML_IconStyle();
+//			icon      ->Read(fid,kstri);
+//		}
+
+//		else if (!strncmp(kstri,"<LabelStyle",11)) {
+//			label     =new KML_LabelStyle();
+//			label     ->Read(fid,kstri);
+//		}
+
+		else if (!strncmp(kstri,"<LineStyle",10)) {
+			line      =new KML_LineStyle();
+			line      ->Read(fid,kstri);
+		}
+
+		else if (!strncmp(kstri,"<PolyStyle",10)) {
+			poly      =new KML_PolyStyle();
+			poly      ->Read(fid,kstri);
+		}
+
+//		else if (!strncmp(kstri,"<BalloonStyle",13)) {
+//			balloon   =new KML_BalloonStyle();
+//			balloon   ->Read(fid,kstri);
+//		}
+
+//		else if (!strncmp(kstri,"<ListStyle",10)) {
+//			list      =new KML_ListStyle();
+//			list      ->Read(fid,kstri);
+//		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_StyleSelector::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Style.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Style.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Style.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_STYLE_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_StyleSelector.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_StyleSelector.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_StyleSelector.cpp	(revision 13395)
@@ -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))
+	  {_error_("KML_StyleSelector::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_StyleSelector::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_StyleSelector.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_StyleSelector.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_StyleSelector.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_STYLESELECTOR_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_SubStyle.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_SubStyle.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_SubStyle.cpp	(revision 13395)
@@ -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))
+	  {_error_("KML_SubStyle::Read -- Unexpected closing tag " << kstr << ".\n");}
+	else if (strncmp(kstr,"<",1))
+	  {_error_("KML_SubStyle::Read -- Unexpected field \"" << kstr << "\".\n");}
+
+	else if (!strncmp(kstr,"<",1))
+		KML_Object::Read(fid,kstr);
+
+	return;
+}
+/*}}}*/
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_SubStyle.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_SubStyle.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_SubStyle.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_SUBSTYLE_H */
+
Index: /issm/trunk/src/c/classes/objects/KML/KML_Unknown.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Unknown.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Unknown.cpp	(revision 13395)
@@ -0,0 +1,195 @@
+/*!\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      ) xDelete<char>(name);
+	if (value     ) xDelete<char>(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=xNew<char>(strlen(value)+1);
+		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_("\"");
+
+		xDelete<char>(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=xNew<char>(strlen(value)+1);
+		memcpy(valuei,value,(strlen(value)+1)*sizeof(char)); 
+        
+		vtoken=strtok(valuei,nl);
+		fprintf(filout,"%s  %s\n",indent,vtoken);
+    
+		while (vtoken=strtok(NULL,nl))
+			fprintf(filout,"%s  %s\n",indent,vtoken);
+
+		xDelete<char>(valuei);
+	}
+
+	KML_Object::Write(filout,indent);
+
+	fprintf(filout,"%s</%s>\n",indent,name);
+
+	return;
+}
+/*}}}*/
+/*FUNCTION KML_Unknown::Read {{{*/
+void  KML_Unknown::Read(FILE* fid,char* kstr){
+
+	char*        kstri;
+	char*        value2=NULL;
+	int          ncom=0;
+	char**       pcom=NULL;
+	char         nl[]={'\n','\0'};
+
+/*  get object name  */
+
+	name=KMLFileTagName(NULL,
+						kstr);
+//	_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 << ".");
+			xDelete<char>(kstri);
+			break;
+		}
+		else if (!strncmp(kstri,"</",2))
+		  {_error_("KML_Unknown::Read -- Unexpected closing tag " << kstri << ".\n");}
+
+		else if (strncmp(kstri,"<",1)) {
+			if (value) {
+				value2=xNew<char>(strlen(value)+1+strlen(kstri)+1);
+				memcpy(value2,value,(strlen(value)+1)*sizeof(char));
+				xDelete<char>(value);
+				value=value2;
+				value2=NULL;
+//				value=(char *) xrealloc(value,(strlen(value)+1+strlen(kstri)+1)*sizeof(char));
+				strcat(value,nl);
+				strcat(value,kstri);
+			}
+			else {
+				value=xNew<char>(strlen(kstri)+1);
+				memcpy(value,kstri,(strlen(kstri)+1)*sizeof(char));
+			}
+		}
+
+		else if (!strncmp(kstri,"<",1))
+			KML_Object::Read(fid,kstri);
+
+		xDelete<char>(kstri);
+	}
+
+	this->AddCommnt(ncom,pcom);
+
+	for (ncom; ncom>0; ncom--)
+		xDelete<char>(pcom[ncom-1]);
+	xDelete<char*>(pcom);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/KML/KML_Unknown.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Unknown.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Unknown.h	(revision 13395)
@@ -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(){_error_("Not implemented yet.");};
+		int   MyRank(){_error_("Not implemented yet.");};
+		void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   MarshallSize(){_error_("Not implemented yet.");};
+		void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
+		int   ObjectEnum(){_error_("Not implemented yet.");};
+		Object* copy(){_error_("Not implemented yet.");};
+		/*}}}*/
+
+};
+#endif  /* _KML_UNKNOWN_H */
+
Index: /issm/trunk/src/c/classes/objects/Loads/Friction.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Friction.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Friction.cpp	(revision 13395)
@@ -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 _error_("element_type "<< element_type << " not supported yet");
+
+	/*Checks that s-1>0 if v=0*/
+        if(vmag==0 && (s-1)<0) _error_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
+
+	alpha2=pow(drag_coefficient,2)*pow(Neff,r)*pow(vmag,(s-1));
+	_assert_(!xIsNan<IssmDouble>(alpha2));
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}
+/*}}}*/
+/*FUNCTION Friction::GetAlpha2(IssmDouble* palpha2, GaussPenta* gauss,int vxenum,int vyenum,int vzenum){{{*/
+void Friction::GetAlpha2(IssmDouble* palpha2, GaussPenta* gauss,int vxenum,int vyenum,int vzenum){
+
+	/*This routine calculates the basal friction coefficient 
+	  alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p**/
+
+	/*diverse: */
+	IssmDouble  r,s;
+	IssmDouble  drag_p, drag_q;
+	IssmDouble  gravity,rho_ice,rho_water;
+	IssmDouble  Neff;
+	IssmDouble  thickness,bed;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  drag_coefficient;
+	IssmDouble  alpha2;
+
+	/*Recover parameters: */
+	inputs->GetInputValue(&drag_p,FrictionPEnum);
+	inputs->GetInputValue(&drag_q,FrictionQEnum);
+	this->GetInputValue(&thickness, gauss,ThicknessEnum);
+	this->GetInputValue(&bed, gauss,BedEnum);
+	this->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+
+	/*Get material parameters: */
+	gravity=matpar->GetG();
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From bed and thickness, compute effective pressure when drag is viscous:
+	Neff=gravity*(rho_ice*thickness+rho_water*bed);
+
+	/*If effective pressure becomes negative, sliding becomes unstable (Paterson 4th edition p 148). This is because 
+	  the water pressure is so high, the ice sheet elevates over its ice bumps and slides. But the limit behaviour 
+	  for friction should be an ice shelf sliding (no basal drag). Therefore, for any effective pressure Neff < 0, we should 
+	  replace it by Neff=0 (ie, equival it to an ice shelf)*/
+	if (Neff<0)Neff=0;
+
+	if(strcmp(element_type,"2d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2));
+	}
+	else if (strcmp(element_type,"3d")==0){
+		this->GetInputValue(&vx, gauss,vxenum);
+		this->GetInputValue(&vy, gauss,vyenum);
+		this->GetInputValue(&vz, gauss,vzenum);
+		vmag=sqrt(pow(vx,2)+pow(vy,2)+pow(vz,2));
+	}
+	else _error_("element_type "<< element_type << " not supported yet");
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
+
+	alpha2=pow(drag_coefficient,2)*pow(Neff,r)*pow(vmag,(s-1));
+	_assert_(!xIsNan<IssmDouble>(alpha2));
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}
+/*}}}*/
+/*FUNCTION Friction::GetAlphaComplement(IssmDouble* palpha_complement, GaussTria* gauss,int vxenum,int vyenum,int vzenum) {{{*/
+void Friction::GetAlphaComplement(IssmDouble* palpha_complement, GaussTria* gauss,int vxenum,int vyenum,int vzenum){
+
+	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p. 
+	 * FrictionGetAlphaComplement is used in control methods on drag, and it computes: 
+	 * alpha_complement= Neff ^r * vel ^s*/
+
+	/*diverse: */
+	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 _error_("element_type "<< element_type << " not supported yet");
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
+
+	alpha_complement=pow(Neff,r)*pow(vmag,(s-1));            _assert_(!xIsNan<IssmDouble>(alpha_complement));
+
+	/*Assign output pointers:*/
+	*palpha_complement=alpha_complement;
+}
+/*}}}*/
+/*FUNCTION Friction::GetAlphaComplement(IssmDouble* palpha_complement, GaussPenta* gauss,int vxenum,int vyenum,int vzenum) {{{*/
+void Friction::GetAlphaComplement(IssmDouble* palpha_complement, GaussPenta* gauss,int vxenum,int vyenum,int vzenum){
+
+	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p. 
+	 * FrictionGetAlphaComplement is used in control methods on drag, and it computes: 
+	 * alpha_complement= Neff ^r * vel ^s*/
+
+	/*diverse: */
+	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 _error_("element_type "<< element_type << " not supported yet");
+
+	/*Checks that s-1>0 if v=0*/
+	if(vmag==0 && (s-1)<0) _error_("velocity is 0 and (s-1)=" << (s-1) << "<0, alpha_complement is Inf");
+
+	alpha_complement=pow(Neff,r)*pow(vmag,(s-1));            _assert_(!xIsNan<IssmDouble>(alpha_complement));
+
+	/*Assign output pointers:*/
+	*palpha_complement=alpha_complement;
+}
+/*}}}*/
+/*FUNCTION Friction::GetInputValue{{{*/
+void Friction::GetInputValue(IssmDouble* pvalue,GaussTria* gauss,int enum_type){
+
+	Input* input=inputs->GetInput(enum_type);
+	if(!input) _error_("input " << EnumToStringx(enum_type) << " not found");
+	input->GetInputValue(pvalue,gauss);
+
+}
+/*}}}*/
+/*FUNCTION Friction::GetInputValue{{{*/
+void Friction::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int enum_type){
+
+	Input* input=inputs->GetInput(enum_type);
+	if(!input) _error_("input " << EnumToStringx(enum_type) << " not found");
+	input->GetInputValue(pvalue,gauss);
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Loads/Friction.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Friction.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Friction.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Loads/Icefront.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Icefront.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Icefront.cpp	(revision 13395)
@@ -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 _error_("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<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+
+	/*No stiffness loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Icefront::CreatePVector {{{*/
+void  Icefront::CreatePVector(Vector<IssmDouble>* pf){
+
+	/*Checks in debugging mode*/
+	/*{{{*/
+	_assert_(nodes);
+	_assert_(element);
+	_assert_(matpar);
+	/*}}}*/
+
+	/*Retrieve parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Just branch to the correct element icefront vector generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum:
+			pe=CreatePVectorDiagnosticHoriz();
+			break;
+		#endif
+		#ifdef _HAVE_CONTROL_
+		case AdjointHorizAnalysisEnum:
+			pe=CreatePVectorAdjointHoriz();
+			break;
+		#endif
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+/*FUNCTION Icefront::CreateJacobianMatrix{{{*/
+void  Icefront::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){
+	this->CreateKMatrix(Jff,NULL);
+}
+/*}}}*/
+/*FUNCTION Icefront::PenaltyCreateKMatrix {{{*/
+void  Icefront::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs, IssmDouble kmax){
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Icefront::PenaltyCreatePVector{{{*/
+void  Icefront::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Icefront::PenaltyCreateJacobianMatrix{{{*/
+void  Icefront::PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){
+	this->PenaltyCreateKMatrix(Jff,NULL,kmax);
+}
+/*}}}*/
+/*FUNCTION Icefront::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:
+			_error_("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:
+				_error_("fill type " << EnumToStringx(fill) << " not supported yet");
+		}
+		ice_pressure=1.0/2.0*gravity*rho_ice*pow(thickness,2);
+		air_pressure=0;
+		pressure = ice_pressure + water_pressure + air_pressure;
+
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		tria->GetSegmentNodalFunctions(&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->material;
+	delete tria;
+	delete icefront;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Icefront::CreatePVectorDiagnosticPattyn{{{*/
+ElementVector* Icefront::CreatePVectorDiagnosticPattyn(void){
+
+	/*Constants*/
+	const int numdofs = NUMVERTICESQUA *NDOF2;
+
+	/*Intermediaries*/
+	int         i,j,ig,index1,index2,index3,index4;
+	int         fill;
+	IssmDouble      surface,pressure,ice_pressure,rho_water,rho_ice,gravity;
+	IssmDouble      water_pressure,air_pressure;
+	IssmDouble      Jdet,z_g;
+	IssmDouble      xyz_list[NUMVERTICESQUA][3];
+	IssmDouble      normal[3];
+	IssmDouble      l1l4[4];
+	GaussPenta *gauss = NULL;
+
+	Penta* penta=(Penta*)element;
+
+	/*Initialize Element vector and return if necessary*/
+	if(penta->IsOnWater()) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICESQUA,this->parameters,PattynApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], 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:
+				_error_("fill type " << EnumToStringx(fill) << " not supported yet");
+		}
+		ice_pressure=rho_ice*gravity*(surface-z_g);
+		air_pressure=0;
+		pressure = ice_pressure + water_pressure + air_pressure;
+
+		for(i=0;i<NUMVERTICESQUA;i++) for(j=0;j<NDOF2;j++) pe->values[i*NDOF2+j]+=Jdet*gauss->weight*pressure*l1l4[i]*normal[j];
+	}
+
+	/*Transform load vector*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICESQUA,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Icefront::CreatePVectorDiagnosticStokes{{{*/
+ElementVector* Icefront::CreatePVectorDiagnosticStokes(void){
+
+	/*Constants*/
+	const int numdofs = NUMVERTICESQUA *NDOF4;
+
+	/*Intermediaries*/
+	int         i,j,ig,index1,index2,index3,index4;
+	int         fill;
+	IssmDouble      pressure,rho_water,gravity;
+	IssmDouble      water_pressure,air_pressure;
+	IssmDouble      Jdet,z_g;
+	IssmDouble      xyz_list[NUMVERTICESQUA][3];
+	IssmDouble      normal[3];
+	IssmDouble      l1l4[4];
+	GaussPenta *gauss = NULL;
+
+	Penta* penta=(Penta*)element;
+
+	/*Initialize Element vector and return if necessary*/
+	if(penta->IsOnWater()) return NULL;
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICESQUA,this->parameters,StokesApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0], 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:
+				_error_("fill type " << EnumToStringx(fill) << " not supported yet");
+		}
+		air_pressure=0;
+		pressure = water_pressure + air_pressure; //no ice pressure fore Stokes
+
+		for(i=0;i<NUMVERTICESQUA;i++){
+			for(j=0;j<NDOF4;j++){
+				if(j<3)  pe->values[i*NDOF4+j]+=Jdet*gauss->weight*pressure*l1l4[i]*normal[j];
+				else     pe->values[i*NDOF4+j]+=0; //pressure term
+			}
+		}
+	}
+
+	/*Transform load vector*/
+	TransformLoadVectorCoord(pe,nodes,NUMVERTICESQUA,XYZPEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+#endif
+/*FUNCTION Icefront::GetDofList {{{*/
+void  Icefront::GetDofList(int** pdoflist,int approximation_enum,int setenum){
+
+	int 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/trunk/src/c/classes/objects/Loads/Icefront.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Icefront.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Icefront.h	(revision 13395)
@@ -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){_error_("not implemented yet");};
+		/*}}}*/
+		/*Load virtual functions definitions: {{{*/
+		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void  CreatePVector(Vector<IssmDouble>* pf);
+		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
+		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector<IssmDouble>*  pf, IssmDouble kmax);
+		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* 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/trunk/src/c/classes/objects/Loads/Load.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Load.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Load.h	(revision 13395)
@@ -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;
+template <class doublematrix> class Matrix;
+template <class doubletype> 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<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs)=0;
+		virtual void  CreatePVector(Vector<IssmDouble>* pf)=0;
+		virtual void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff)=0;
+		virtual void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax)=0;
+		virtual void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs, IssmDouble kmax)=0;
+		virtual void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax)=0;
+		virtual bool  InAnalysis(int analysis_type)=0;
+		/*}}}*/
+};
+#endif
Index: /issm/trunk/src/c/classes/objects/Loads/Numericalflux.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Numericalflux.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Numericalflux.cpp	(revision 13395)
@@ -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<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+
+	/*recover some parameters*/
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
+	switch(analysis_type){
+		case PrognosticAnalysisEnum:
+			Ke=CreateKMatrixPrognostic();
+			break;
+		case BalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixBalancethickness();
+			break;
+		case AdjointBalancethicknessAnalysisEnum:
+			Ke=CreateKMatrixAdjointBalancethickness();
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVector {{{*/
+void  Numericalflux::CreatePVector(Vector<IssmDouble>* pf){
+
+	/*recover some parameters*/
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case PrognosticAnalysisEnum:
+			pe=CreatePVectorPrognostic();
+			break;
+		case BalancethicknessAnalysisEnum:
+			pe=CreatePVectorBalancethickness();
+			break;
+		case AdjointBalancethicknessAnalysisEnum:
+			pe=CreatePVectorAdjointBalancethickness();
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::PenaltyCreateKMatrix {{{*/
+void  Numericalflux::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
+
+	/*No stiffness loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::PenaltyCreatePVector{{{*/
+void  Numericalflux::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+
+	/*No penalty loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::InAnalysis{{{*/
+bool Numericalflux::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+
+/*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:
+			_error_("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:
+			_error_("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:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixAdjointBalancethicknessInternal {{{*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessInternal(void){
+
+	ElementMatrix* Ke=CreateKMatrixBalancethicknessInternal();
+	if (Ke) Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreateKMatrixAdjointBalancethicknessBoundary {{{*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessBoundary(void){
+
+	ElementMatrix* Ke=CreateKMatrixBalancethicknessBoundary();
+	if(Ke) Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorPrognostic{{{*/
+ElementVector* Numericalflux::CreatePVectorPrognostic(void){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreatePVectorPrognosticInternal();
+		case BoundaryEnum:
+			return CreatePVectorPrognosticBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorPrognosticInternal{{{*/
+ElementVector* Numericalflux::CreatePVectorPrognosticInternal(void){
+
+	/*Nothing added to PVector*/
+	return NULL;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorPrognosticBoundary{{{*/
+ElementVector* Numericalflux::CreatePVectorPrognosticBoundary(void){
+
+	/* constants*/
+	const int numdof=NDOF1*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)) _error_("Cannot weakly apply constraint because NaN was provided");
+
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL= - gauss->weight*Jdet*dt*UdotN*thickness;
+
+		for(i=0;i<numdof;i++) pe->values[i] += DL*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorBalancethickness{{{*/
+ElementVector* Numericalflux::CreatePVectorBalancethickness(void){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return CreatePVectorBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreatePVectorBalancethicknessBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorBalancethicknessInternal{{{*/
+ElementVector* Numericalflux::CreatePVectorBalancethicknessInternal(void){
+
+	/*Nothing added to PVector*/
+	return NULL;
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::CreatePVectorBalancethicknessBoundary{{{*/
+ElementVector* Numericalflux::CreatePVectorBalancethicknessBoundary(void){
+
+	/* constants*/
+	const int numdof=NDOF1*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/trunk/src/c/classes/objects/Loads/Numericalflux.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Numericalflux.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Numericalflux.h	(revision 13395)
@@ -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){_error_("Not implemented yet!");}
+		void    InputUpdateFromVector(bool* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*Do nothing*/}
+		void    InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*Do nothing*/}
+		void    InputUpdateFromVectorDakota(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(bool* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromConstant(IssmDouble constant, int name){/*Do nothing*/};
+		void    InputUpdateFromConstant(int constant, int name){/*Do nothing*/};
+		void    InputUpdateFromConstant(bool constant, int name){_error_("Not implemented yet!");}
+		void    InputUpdateFromSolution(IssmDouble* solution){_error_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Load virtual functions definitions: {{{*/
+		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void  CreatePVector(Vector<IssmDouble>* pf);
+		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
+		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
+		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		bool  InAnalysis(int analysis_type);
+		/*}}}*/
+		/*Numericalflux management:{{{*/
+		void  GetNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]);
+		ElementMatrix* CreateKMatrixPrognostic(void);
+		ElementMatrix* CreateKMatrixPrognosticInternal(void);
+		ElementMatrix* CreateKMatrixPrognosticBoundary(void);
+		ElementMatrix* CreateKMatrixBalancethickness(void);
+		ElementMatrix* CreateKMatrixBalancethicknessInternal(void);
+		ElementMatrix* CreateKMatrixBalancethicknessBoundary(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethickness(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethicknessInternal(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethicknessBoundary(void);
+		ElementVector* CreatePVectorPrognostic(void);
+		ElementVector* CreatePVectorPrognosticInternal(void);
+		ElementVector* CreatePVectorPrognosticBoundary(void);
+		ElementVector* CreatePVectorBalancethickness(void);
+		ElementVector* CreatePVectorBalancethicknessInternal(void);
+		ElementVector* CreatePVectorBalancethicknessBoundary(void);
+		ElementVector* CreatePVectorAdjointBalancethickness(void);
+		/*}}}*/
+
+};
+
+#endif  /* _NUMERICALFLUX_H_ */
Index: /issm/trunk/src/c/classes/objects/Loads/Pengrid.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Pengrid.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Pengrid.cpp	(revision 13395)
@@ -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<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Pengrid::CreatePVector {{{*/
+void  Pengrid::CreatePVector(Vector<IssmDouble>* pf){
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreateMatrix {{{*/
+void  Pengrid::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
+
+	/*Retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case DiagnosticHorizAnalysisEnum: case AdjointHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDiagnosticStokes(kmax);
+			break;
+		#endif
+		#ifdef _HAVE_THERMAL_
+		case ThermalAnalysisEnum:
+			Ke=PenaltyCreateKMatrixThermal(kmax);
+			break;
+		case MeltingAnalysisEnum:
+			Ke=PenaltyCreateKMatrixMelting(kmax);
+			break;
+		#endif
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global matrix*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreatePVector {{{*/
+void  Pengrid::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+
+	/*Retrieve parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		#ifdef _HAVE_DIAGNOSTIC_
+		case ThermalAnalysisEnum:
+			pe=PenaltyCreatePVectorThermal(kmax);
+			break;
+		#endif
+		#ifdef _HAVE_THERMAL_
+		case MeltingAnalysisEnum:
+			pe=PenaltyCreatePVectorMelting(kmax);
+			break;
+		case DiagnosticHorizAnalysisEnum: case AdjointHorizAnalysisEnum:
+			break;
+		#endif
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+/*FUNCTION Pengrid::InAnalysis{{{*/
+bool Pengrid::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type)return true;
+	else return false;
+}
+/*}}}*/
+
+/*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{
+		_error_("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 (reCast<bool>(dt)) pe->values[0]=melting_offset*pow((IssmDouble)10,penalty_factor)*(temperature-t_pmp)/dt;
+		else    pe->values[0]=melting_offset*pow((IssmDouble)10,penalty_factor)*(temperature-t_pmp);
+	}
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Pengrid::PenaltyCreatePVectorThermal {{{*/
+ElementVector* Pengrid::PenaltyCreatePVectorThermal(IssmDouble kmax){
+
+	const int numdof=NUMVERTICES*NDOF1;
+	IssmDouble pressure;
+	IssmDouble t_pmp;
+	IssmDouble penalty_factor;
+
+	Penta* penta=(Penta*)element;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementVector* pe=new ElementVector(&node,1,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
+
+	pe->values[0]=kmax*pow((IssmDouble)10,penalty_factor)*t_pmp;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+#endif
+/*FUNCTION Pengrid::ResetConstraint {{{*/
+void  Pengrid::ResetConstraint(void){
+	active=0;
+	zigzag_counter=0;
+}
+/*}}}*/
+/*FUNCTION Pengrid::UpdateInputs {{{*/
+void  Pengrid::UpdateInputs(IssmDouble* solution){
+	_error_("not supported yet!");
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Loads/Pengrid.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Pengrid.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Pengrid.h	(revision 13395)
@@ -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){_error_("not implemented yet");};
+		/*}}}*/
+		/*Load virtual functions definitions: {{{*/
+		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void  CreatePVector(Vector<IssmDouble>* pf);
+		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
+		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
+		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		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/trunk/src/c/classes/objects/Loads/Penpair.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Penpair.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Penpair.cpp	(revision 13395)
@@ -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<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+	/*If you code this piece, don't forget that a penalty will be inactive if it is dealing with clone nodes*/
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Penpair::CreatePVector {{{*/
+void  Penpair::CreatePVector(Vector<IssmDouble>* pf){
+
+	/*No loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+/*FUNCTION Penpair::CreateJacobianMatrix{{{*/
+void  Penpair::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){
+	this->CreateKMatrix(Jff,NULL);
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreateKMatrix {{{*/
+void  Penpair::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
+
+	/*Retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case DiagnosticHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDiagnosticHoriz(kmax);
+			break;
+		case PrognosticAnalysisEnum:
+			Ke=PenaltyCreateKMatrixPrognostic(kmax);
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreatePVector {{{*/
+void  Penpair::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+	/*No loads applied, do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreateJacobianMatrix{{{*/
+void  Penpair::PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){
+	this->PenaltyCreateKMatrix(Jff,NULL,kmax);
+}
+/*}}}*/
+/*FUNCTION Penpair::InAnalysis{{{*/
+bool Penpair::InAnalysis(int in_analysis_type){
+	if (in_analysis_type==this->analysis_type)return true;
+	else return false;
+}
+/*}}}*/
+
+/*Update virtual functions definitions:*/
+/*FUNCTION Penpair::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
+void  Penpair::InputUpdateFromConstant(IssmDouble constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromConstant(int constant, int name) {{{*/
+void  Penpair::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromConstant(bool constant, int name) {{{*/
+void  Penpair::InputUpdateFromConstant(bool constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
+void  Penpair::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromVector(int* vector, int name, int type) {{{*/
+void  Penpair::InputUpdateFromVector(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Penpair::InputUpdateFromVector(bool* vector, int name, int type) {{{*/
+void  Penpair::InputUpdateFromVector(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+
+/*Penpair management:*/
+/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticHoriz{{{*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticHoriz(IssmDouble kmax){
+
+	int    approximation0=nodes[0]->GetApproximation();
+	int    approximation1=nodes[1]->GetApproximation();
+
+	switch(approximation0){
+		case MacAyealApproximationEnum:
+			switch(approximation1){
+				case MacAyealApproximationEnum: return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				case PattynApproximationEnum:   return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				default: _error_("not supported yet");
+			}
+		case PattynApproximationEnum:
+			switch(approximation1){
+				case MacAyealApproximationEnum: return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				case PattynApproximationEnum:   return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
+				default: _error_("not supported yet");
+			}
+		case StokesApproximationEnum:
+			switch(approximation1){
+				case StokesApproximationEnum: return PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				case NoneApproximationEnum: return   PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				default: _error_("not supported yet");
+			}
+		case NoneApproximationEnum:
+			switch(approximation1){
+				case StokesApproximationEnum: return PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				case NoneApproximationEnum: return   PenaltyCreateKMatrixDiagnosticStokes(kmax); 
+				default: _error_("not supported yet");
+			}
+		default: _error_("not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticMacAyealPattyn {{{*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticMacAyealPattyn(IssmDouble kmax){
+	
+	const int numdof=NUMVERTICES*NDOF2;
+	IssmDouble penalty_offset;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+
+	//Create elementary matrix: add penalty to 
+	Ke->values[0*numdof+0]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[0*numdof+2]=-kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[2*numdof+0]=-kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[2*numdof+2]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+
+	Ke->values[1*numdof+1]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[1*numdof+3]=-kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[3*numdof+1]=-kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[3*numdof+3]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticStokes {{{*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticStokes(IssmDouble kmax){
+	
+	const int numdof=NUMVERTICES*NDOF4;
+	IssmDouble penalty_offset;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+
+	//Create elementary matrix: add penalty to 
+	Ke->values[0*numdof+0]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[0*numdof+4]=-kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[4*numdof+0]=-kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[4*numdof+4]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+
+	Ke->values[1*numdof+1]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[1*numdof+5]=-kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[5*numdof+1]=-kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[5*numdof+5]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+	
+	Ke->values[2*numdof+2]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[2*numdof+6]=-kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[6*numdof+2]=-kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[6*numdof+6]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+
+	Ke->values[3*numdof+3]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[3*numdof+7]=-kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[7*numdof+3]=-kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[7*numdof+7]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penpair::PenaltyCreateKMatrixPrognostic {{{*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixPrognostic(IssmDouble kmax){
+
+	const int numdof=NUMVERTICES*NDOF1;
+	IssmDouble penalty_factor;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_factor,PrognosticPenaltyFactorEnum);
+
+	//Create elementary matrix: add penalty to 
+	Ke->values[0*numdof+0]=+kmax*pow((IssmDouble)10.0,penalty_factor);
+	Ke->values[0*numdof+1]=-kmax*pow((IssmDouble)10.0,penalty_factor);
+	Ke->values[1*numdof+0]=-kmax*pow((IssmDouble)10.0,penalty_factor);
+	Ke->values[1*numdof+1]=+kmax*pow((IssmDouble)10.0,penalty_factor);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Loads/Penpair.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Penpair.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Penpair.h	(revision 13395)
@@ -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){_error_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromVectorDakota(bool* vector, int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromConstant(IssmDouble constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromSolution(IssmDouble* solution){_error_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+			/*Load virtual functions definitions: {{{*/
+		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void  CreatePVector(Vector<IssmDouble>* pf);
+		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
+		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff,Matrix<IssmDouble>* Kfs,IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* 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/trunk/src/c/classes/objects/Loads/Riftfront.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Riftfront.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Riftfront.cpp	(revision 13395)
@@ -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=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+2));
+	el2=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+3)) ;
+
+	node1=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+0));
+	node2=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+1));
+
+	/*id: */
+	this->id=riftfront_id;
+	this->analysis_type=riftfront_analysis_type;
+
+	/*hooks: */
+	riftfront_node_ids[0]=iomodel->nodecounter+node1;
+	riftfront_node_ids[1]=iomodel->nodecounter+node2;
+	riftfront_elem_ids[0]=el1;
+	riftfront_elem_ids[1]=el2;
+	riftfront_matpar_id=numberofelements+1; //matlab indexing
+
+	/*Hooks: */
+	this->hnodes=new Hook(riftfront_node_ids,2);
+	this->helements=new Hook(riftfront_elem_ids,2);
+	this->hmatpar=new Hook(&riftfront_matpar_id,1);
+
+	/*computational parameters: */
+	this->active=0;
+	this->frozen=0;
+	this->counter=0;
+	this->prestable=0;
+	this->penalty_lock=penalty_lock;
+	this->material_converged=0;
+	this->normal[0]=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+4);
+	this->normal[1]=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+5);
+	this->length=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+6);
+	this->fraction=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+9);
+	this->state=reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+11));
+
+	//intialize inputs, and add as many inputs per element as requested: 
+	this->inputs=new Inputs();
+		
+	riftfront_type=SegmentRiftfrontEnum;
+	riftfront_fill = reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+7));
+	riftfront_friction=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+8);
+	riftfront_fractionincrement=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+10);
+	riftfront_shelf=reCast<bool,IssmDouble>(iomodel->Data(MaskVertexonfloatingiceEnum)[node1-1]);
+
+	this->inputs->AddInput(new IntInput(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*/
+	_error_("not implemented yet");
+	//this->inputs->AddInput(new DoubleInput(name,constant));
+
+}
+/*}}}*/
+
+
+/*Load virtual functions definitions:*/
+/*FUNCTION Riftfront::Configure {{{*/
+void  Riftfront::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	hnodes->configure(nodesin);
+	helements->configure(elementsin);
+	hmatpar->configure(materialsin);
+
+	/*Initialize hooked fields*/
+	this->nodes   =(Node**)hnodes->deliverp();
+	this->elements=(Element**)helements->deliverp();
+	this->matpar  =(Matpar*)hmatpar->delivers();
+
+	/*point parameters to real dataset: */
+	this->parameters=parametersin;
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::SetCurrentConfiguration {{{*/
+void  Riftfront::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*FUNCTION Riftfront::PenaltyCreateKMatrix {{{*/
+void  Riftfront::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
+
+	/*Retrieve parameters: */
+	ElementMatrix* Ke=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case DiagnosticHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDiagnosticHoriz(kmax);
+			break;
+		case AdjointHorizAnalysisEnum:
+			Ke=PenaltyCreateKMatrixDiagnosticHoriz(kmax);
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(Ke){
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Riftfront::PenaltyCreatePVector {{{*/
+void  Riftfront::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
+
+	/*Retrieve parameters: */
+	ElementVector* pe=NULL;
+	int analysis_type;
+	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+
+	switch(analysis_type){
+		case DiagnosticHorizAnalysisEnum:
+			pe=PenaltyCreatePVectorDiagnosticHoriz(kmax);
+			break;
+		case AdjointHorizAnalysisEnum:
+			/*No penalty applied on load vector*/
+			break;
+		default:
+			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
+	}
+
+	/*Add to global Vector*/
+	if(pe){
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+/*FUNCTION Riftfront::CreateKMatrix {{{*/
+void  Riftfront::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Riftfront::CreatePVector {{{*/
+void  Riftfront::CreatePVector(Vector<IssmDouble>* pf){
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+/*FUNCTION Riftfront::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)_error_("only Tria element allowed for Riftfront load!");
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*Initialize Element Matrix*/
+	if(!this->active) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*Get some parameters: */
+	this->parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+	this->inputs->GetInputValue(&friction,FrictionEnum);
+	tria1->GetInputValue(&h[0],nodes[0],ThicknessEnum);
+	tria2->GetInputValue(&h[1],nodes[1],ThicknessEnum);
+	if (h[0]!=h[1])_error_("different thicknesses not supported for rift fronts");
+	thickness=h[0];
+
+	/*There is contact, we need to constrain the normal velocities (zero penetration), and the 
+	 *contact slip friction. */
+
+	/*From Peter Wriggers book (Computational Contact Mechanics, p191): */
+	Ke->values[0*numdof+0]+= +pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[0*numdof+1]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[0*numdof+2]+= -pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[0*numdof+3]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+
+	Ke->values[1*numdof+0]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[1*numdof+1]+= +pow(normal[1],2)*kmax*pow(10,penalty_offset);
+	Ke->values[1*numdof+2]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[1*numdof+3]+= -pow(normal[1],2)*kmax*pow(10,penalty_offset);
+
+	Ke->values[2*numdof+0]+= -pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[2*numdof+1]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[2*numdof+2]+= +pow(normal[0],2)*kmax*pow(10,penalty_offset);
+	Ke->values[2*numdof+3]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+
+	Ke->values[3*numdof+0]+= -normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[3*numdof+1]+= -pow(normal[1],2)*kmax*pow(10,penalty_offset);
+	Ke->values[3*numdof+2]+= +normal[0]*normal[1]*kmax*pow(10,penalty_offset);
+	Ke->values[3*numdof+3]+= +pow(normal[1],2)*kmax*pow(10,penalty_offset);
+
+	/*Now take care of the friction: of type sigma=frictiontangent_velocity2-tangent_velocity1)*/
+
+	Ke->values[0*numdof+0]+= +pow(normal[1],2)*thickness*length*friction;
+	Ke->values[0*numdof+1]+= -normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[0*numdof+2]+= -pow(normal[1],2)*thickness*length*friction;
+	Ke->values[0*numdof+3]+= +normal[0]*normal[1]*thickness*length*friction;
+
+	Ke->values[1*numdof+0]+= -normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[1*numdof+1]+= +pow(normal[0],2)*thickness*length*friction;
+	Ke->values[1*numdof+2]+= +normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[1*numdof+3]+= -pow(normal[0],2)*thickness*length*friction;
+
+	Ke->values[2*numdof+0]+= -pow(normal[1],2)*thickness*length*friction;
+	Ke->values[2*numdof+1]+= +normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[2*numdof+2]+= +pow(normal[1],2)*thickness*length*friction;
+	Ke->values[2*numdof+3]+= -normal[0]*normal[1]*thickness*length*friction;
+
+	Ke->values[3*numdof+0]+= +normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[3*numdof+1]+= -pow(normal[0],2)*thickness*length*friction;
+	Ke->values[3*numdof+2]+= -normal[0]*normal[1]*thickness*length*friction;
+	Ke->values[3*numdof+3]+= +pow(normal[0],2)*thickness*length*friction;
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Riftfront::PenaltyCreatePVectorDiagnosticHoriz {{{*/
+ElementVector* Riftfront::PenaltyCreatePVectorDiagnosticHoriz(IssmDouble kmax){
+
+	const int   numdof = NDOF2*NUMVERTICES;
+	int         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)_error_("only Tria element allowed for Riftfront load!");
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*Initialize Element Matrix*/
+	if(this->active) return NULL; /*The penalty is active. No loads implied here.*/
+	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Get some inputs: */
+	this->inputs->GetInputValue(&fill,FillEnum);
+	this->inputs->GetInputValue(&shelf,SegmentOnIceShelfEnum);
+	rho_ice=matpar->GetRhoIce();
+	rho_water=matpar->GetRhoWater();
+	gravity=matpar->GetG();
+	tria1->GetInputValue(&h[0],nodes[0],ThicknessEnum);
+	tria2->GetInputValue(&h[1],nodes[1],ThicknessEnum);
+	if (h[0]!=h[1])_error_("different thicknesses not supported for rift fronts");
+	thickness=h[0];
+	tria1->GetInputValue(&b[0],nodes[0],BedEnum);
+	tria2->GetInputValue(&b[1],nodes[1],BedEnum);
+	if (b[0]!=b[1])_error_("different beds not supported for rift fronts");
+	bed=b[0];
+
+	/*Ok, this rift is opening. We should put loads on both sides of the rift flanks. Because we are dealing with contact mechanics, 
+	 * and we want to avoid zigzagging of the loads, we want lump the loads onto nodes, not onto surfaces between nodes.:*/
+
+	/*Ok, to compute the pressure, we are going to need material properties, thickness and bed for the two nodes. We assume those properties to 
+	 * be the same across the rift.: */
+
+	/*Ok, now compute the pressure (in norm) that is being applied to the flanks, depending on the type of fill: */
+	if(fill==WaterEnum){
+		if(shelf){
+			/*We are on an ice shelf, hydrostatic equilibrium is used to determine the pressure for water fill: */
+			pressure=rho_ice*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)2  - rho_water*gravity*pow(bed,(IssmDouble)2)/(IssmDouble)2; 
+		}
+		else{
+			//We are on an icesheet, we assume the water column fills the entire front: */
+			pressure=rho_ice*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)2  - rho_water*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)2; 
+		}
+	}
+	else if(fill==AirEnum){
+		pressure=rho_ice*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)2;   //icefront on an ice sheet, pressure imbalance ice vs air.
+	}
+	else if(fill==IceEnum){ //icefront finding itself against another icefront (pressure imbalance is fully compensated, ice vs ice)
+		pressure=0;
+	}
+	else if(fill==MelangeEnum){ //icefront finding itself against another icefront (pressure imbalance is fully compensated, ice vs ice)
+
+		if(!shelf) _error_("fill type " << fill << " not supported on ice sheets yet.");
+
+		pressure_litho=rho_ice*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)2;
+		pressure_air=0;
+		pressure_melange=rho_ice*gravity*pow(fraction*thickness,(IssmDouble)2)/(IssmDouble)2;
+		pressure_water=1.0/2.0*rho_water*gravity*  ( pow(bed,2.0)-pow(rho_ice/rho_water*fraction*thickness,2.0) );
+
+		pressure=pressure_litho-pressure_air-pressure_melange-pressure_water;
+	}
+	else{
+		_error_("fill type " << fill << " not supported yet.");
+	}
+
+	/*Ok, add contribution to first node, along the normal i==0: */
+	for (j=0;j<2;j++){
+		pe->values[j]+=pressure*normal[j]*length;
+	}
+
+	/*Add contribution to second node, along the opposite normal: i==1 */
+	for (j=0;j<2;j++){
+		pe->values[2+j]+= -pressure*normal[j]*length;
+	}	
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Riftfront::Constrain {{{*/
+#define _ZIGZAGCOUNTER_
+
+int Riftfront::Constrain(int* punstable){
+
+	const int   numnodes        = 2;
+	IssmDouble      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)_error_("only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*Is this constraint frozen? In which case we don't touch: */
+	if (this->frozen){
+		*punstable=0;
+		return 1;
+	}
+
+	/*Is this rift segment state specified by user input? :*/
+	if (this->state==OpenEnum || this->state==ClosedEnum){
+
+		if(this->state==OpenEnum)this->active=0;
+		if(this->state==ClosedEnum)this->active=1;
+		
+		/*this segment is like frozen, no instability here: */
+		*punstable=0;
+		return 1;
+	}
+
+
+	/*recover parameters: */
+	this->inputs->GetInputValue(&fractionincrement,FractionIncrementEnum);
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*activation: */
+	if(penetration<0)activate=1;
+	else  activate=0;
+
+	/*Here, we try to avoid zigzaging. When a penalty activates and deactivates for more than penalty_lock times, 
+	 * we increase the fraction of melange:*/
+	if(this->counter>this->penalty_lock){
+		/*reset counter: */
+		this->counter=0;
+		/*increase melange fraction: */
+		this->fraction+=fractionincrement;
+		if (this->fraction>1)this->fraction=(IssmDouble)1.0;
+		//_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(reCast<int,IssmDouble>(converged)){
+		/*ok, material non-linearity has converged. If that was already the case, we keep 
+		 * constraining the rift front. If it was not, and this is the first time the material 
+		 * has converged, we start constraining now!: */
+		this->material_converged=1;
+	}
+
+	return this->material_converged;
+}
+/*}}}*/
+/*FUNCTION Riftfront::MaxPenetration {{{*/
+int   Riftfront::MaxPenetration(IssmDouble* ppenetration){
+
+	const int     numnodes=2;
+	IssmDouble        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)_error_("only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	//initialize: 
+	penetration=-1;
+
+	/*recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node1 faces node2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*Now, we return penetration only if we are active!: */
+	if(this->active==0)penetration=-1;
+
+	/*If we are zigzag locked, same thing: */
+	if(this->counter>this->penalty_lock)penetration=-1;
+	
+	/*assign output pointer: */
+	*ppenetration=penetration;
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Riftfront::Penetration {{{*/
+int   Riftfront::Penetration(IssmDouble* ppenetration){
+
+	IssmDouble    vx1;
+	IssmDouble    vy1;
+	IssmDouble    vx2;
+	IssmDouble    vy2;
+
+	IssmDouble    penetration;
+	int       found;
+
+	/*Objects: */
+	Tria     *tria1       = NULL;
+	Tria     *tria2       = NULL;
+
+	/*enum of element? */
+	if(elements[0]->ObjectEnum()!=TriaEnum)_error_("only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*Now, we return penetration only if we are active!: */
+	if(this->active==0)penetration=0;
+	
+	/*assign output pointer: */
+	*ppenetration=penetration;
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Riftfront::PotentialUnstableConstraint {{{*/
+int   Riftfront::PotentialUnstableConstraint(int* punstable){
+
+
+	const int   numnodes        = 2;
+	IssmDouble      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)_error_("only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*Ok, we are looking for positive penetration in an active constraint: */
+	if(this->active){
+		if (penetration>=0){
+			unstable=1;
+		}
+		else{
+			unstable=0;
+		}
+	}
+	else{
+		unstable=0;
+	}
+
+	/*assign output pointer: */
+	*punstable=unstable;
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Riftfront::PreConstrain {{{*/
+int   Riftfront::PreConstrain(int* punstable){
+
+	const int   numnodes    = 2;
+	IssmDouble      penetration;
+	int         unstable;
+	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)_error_("only Tria element allowed for Riftfront load!");
+
+	/*recover elements on both side of rift: */
+	tria1=(Tria*)elements[0];
+	tria2=(Tria*)elements[1];
+
+	/*First recover velocity: */
+	tria1->GetInputValue(&vx1,nodes[0],VxEnum);
+	tria2->GetInputValue(&vx2,nodes[1],VxEnum);
+	tria1->GetInputValue(&vy1,nodes[0],VyEnum);
+	tria2->GetInputValue(&vy2,nodes[1],VyEnum);
+
+	/*Node 1 faces node 2, compute penetration of 2 into 1 (V2-V1).N (with N normal vector, and V velocity vector: */
+	penetration=(vx2-vx1)*normal[0]+(vy2-vy1)*normal[1];
+
+	/*Ok, we are preconstraining here. Ie, anything that penetrates is constrained until stability of the entire set 
+	 * of constraints is reached.: */
+	if(penetration<0){
+		if (!this->active){
+			/*This is the first time penetration happens: */
+			this->active=1;
+			unstable=1;
+		}
+		else{
+			/*This constraint was already active: */
+			this->active=1;
+			unstable=0;
+		}
+	}
+	else{
+		/*No penetration happening. : */
+		if (!this->active){
+			/*This penalty was not active, and no penetration happening. Do nonthing: */
+			this->active=0;
+			unstable=0; 
+		}
+		else{
+			/*Ok, this penalty wants to get released. But not now, this is preconstraint, not constraint: */
+			this->active=1;
+			unstable=0;
+		}
+	}
+
+	/*assign output pointer: */
+	*punstable=unstable;
+	return 1;
+}
+/*}}}*/
+/*FUNCTION Riftfront::PreStable {{{*/
+bool  Riftfront::PreStable(){
+	return prestable;
+}
+/*}}}*/
+/*FUNCTION Riftfront::SetPreStable {{{*/
+void Riftfront::SetPreStable(){
+	prestable=1;
+}
+/*}}}*/
+/*FUNCTION Riftfront::IsInput{{{*/
+bool Riftfront::IsInput(int name){
+	if (
+				name==ConvergedEnum ||
+				name==ThicknessEnum ||
+				name==SurfaceEnum ||
+				name==BedEnum 
+		){
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Loads/Riftfront.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Riftfront.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Loads/Riftfront.h	(revision 13395)
@@ -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){_error_("Not implemented yet!");}
+		void    InputUpdateFromVector(bool* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows,int ncols, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(int* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVectorDakota(bool* vector, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromConstant(IssmDouble constant, int name);
+		void    InputUpdateFromConstant(int constant, int name){_error_("Not implemented yet!");}
+		void    InputUpdateFromConstant(bool constant, int name);
+		void    InputUpdateFromSolution(IssmDouble* solution){_error_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		/*}}}*/
+		/*Load virtual functions definitions: {{{*/
+		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void  CreatePVector(Vector<IssmDouble>* pf);
+		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
+		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
+		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		bool  InAnalysis(int analysis_type);
+		/*}}}*/
+		/*Riftfront specific routines: {{{*/
+		bool  PreStable();
+		ElementMatrix* PenaltyCreateKMatrixDiagnosticHoriz(IssmDouble kmax);
+		ElementVector* PenaltyCreatePVectorDiagnosticHoriz(IssmDouble kmax);
+		void  SetPreStable();
+		int   PreConstrain(int* punstable);
+		int   Constrain(int* punstable);
+		void  FreezeConstraints(void);
+		bool  IsFrozen(void);
+		int   Penetration(IssmDouble* ppenetration);
+		int   MaxPenetration(IssmDouble* ppenetration);
+		int   PotentialUnstableConstraint(int* punstable);
+		int   IsMaterialStable(void);
+		bool  IsInput(int name);
+		/*}}}*/
+};
+
+#endif  /* _RIFTFRONT_H_ */
Index: /issm/trunk/src/c/classes/objects/Materials/Matdamageice.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Matdamageice.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Materials/Matdamageice.cpp	(revision 13395)
@@ -0,0 +1,896 @@
+/*!\file Matdamageice.c
+ * \brief: implementation of the Matdamageice object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../../classes.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+		
+/*Matdamageice constructors and destructor*/
+/*FUNCTION Matdamageice::Matdamageice(){{{*/
+Matdamageice::Matdamageice(){
+	this->inputs=NULL;
+	this->helement=NULL;
+	return;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::Matdamageice(int id, int index, IoModel* iomodel, int num_vertices){{{*/
+Matdamageice::Matdamageice(int matice_mid,int index, IoModel* iomodel){
+
+	/*Intermediaries:*/
+	int    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 Matdamageice::~Matdamageice(){{{*/
+Matdamageice::~Matdamageice(){
+	delete helement;
+	delete inputs;
+	return;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Matdamageice::Echo {{{*/
+void Matdamageice::Echo(void){
+
+	_printLine_("Matdamageice:");
+	_printLine_("   mid: " << mid);
+	_printLine_("   inputs:");
+	inputs->Echo();
+	_printLine_("   element:");
+	helement->Echo();
+}
+/*}}}*/
+/*FUNCTION Matdamageice::DeepEcho {{{*/
+void Matdamageice::DeepEcho(void){
+
+	_printLine_("Matdamageice:");
+	_printLine_("   mid: " << mid);
+	_printLine_("   inputs:");
+	inputs->DeepEcho();
+	_printLine_("   element:");
+	helement->Echo();
+}		
+/*}}}*/
+/*FUNCTION Matdamageice::Id {{{*/
+int    Matdamageice::Id(void){ return mid; }
+/*}}}*/
+/*FUNCTION Matdamageice::MyRank {{{*/
+int    Matdamageice::MyRank(void){ 
+	extern int my_rank;
+	return my_rank; 
+}
+/*}}}*/
+/*FUNCTION Matdamageice::ObjectEnum{{{*/
+int Matdamageice::ObjectEnum(void){
+
+	return MatdamageiceEnum;
+
+}
+/*}}}*/
+/*FUNCTION Matdamageice::copy {{{*/
+Object* Matdamageice::copy() {
+
+	/*Output*/
+	Matdamageice* matice=NULL;
+
+	/*Initialize output*/
+	matice=new Matdamageice();
+
+	/*copy fields: */
+	matice->mid=this->mid;
+	matice->helement=(Hook*)this->helement->copy();
+	if(this->inputs) matice->inputs=(Inputs*)this->inputs->Copy();
+	else  matice->inputs=new Inputs();
+
+	return matice;
+}
+/*}}}*/
+
+/*Matdamageice management*/
+/*FUNCTION Matdamageice::Configure {{{*/
+void  Matdamageice::Configure(Elements* elementsin){
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and offsets hidden in hooks: */
+	helement->configure(elementsin);
+}
+/*}}}*/
+/*FUNCTION Matdamageice::SetCurrentConfiguration {{{*/
+void  Matdamageice::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
+
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetA {{{*/
+IssmDouble Matdamageice::GetA(){
+	/*
+	 * A = 1/B^n
+	 */
+
+	IssmDouble B,n;
+
+	inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	n=this->GetN();
+
+	return pow(B,-n);
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetB {{{*/
+IssmDouble Matdamageice::GetB(){
+
+	/*Output*/
+	IssmDouble B;
+
+	inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	return B;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetBbar {{{*/
+IssmDouble Matdamageice::GetBbar(){
+
+	/*Output*/
+	IssmDouble Bbar;
+
+	inputs->GetInputAverage(&Bbar,MaterialsRheologyBbarEnum);
+	return Bbar;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetN {{{*/
+IssmDouble Matdamageice::GetN(){
+
+	/*Output*/
+	IssmDouble n;
+
+	inputs->GetInputAverage(&n,MaterialsRheologyNEnum);
+	return n;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetZ {{{*/
+IssmDouble Matdamageice::GetZ(){
+
+	/*Output*/
+	IssmDouble Z;
+
+	inputs->GetInputAverage(&Z,MaterialsRheologyZEnum);
+	return Z;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetZbar {{{*/
+IssmDouble Matdamageice::GetZbar(){
+
+	/*Output*/
+	IssmDouble Zbar;
+
+	inputs->GetInputAverage(&Zbar,MaterialsRheologyZbarEnum);
+	return Zbar;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetVectorFromInputs{{{*/
+void  Matdamageice::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
+
+	/*Intermediaries*/
+	Element *element= NULL;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that input_enum is a material input*/
+	if (!IsInput(input_enum)) return;
+
+	switch(element->ObjectEnum()){
+
+		case TriaEnum:{
+
+			/*Prepare index list*/
+			int 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) _error_("Input " << EnumToStringx(input_enum) << " not found in material");
+
+			/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
+			input->GetVectorFromInputs(vector,&doflist1[0]);}
+			break;
+
+		default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosity2d {{{*/
+void  Matdamageice::GetViscosity2d(IssmDouble* pviscosity, IssmDouble* epsilon){
+	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
+												   Z * B
+	  viscosity= -------------------------------------------------------------------
+						  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+
+	  where viscosity is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	  vector, and n the flow law exponent.
+
+	  If epsilon is NULL, it means this is the first time SystemMatrices is being run, and we 
+	  return 10^14, initial viscosity.
+	  */
+
+	/*output: */
+	IssmDouble viscosity;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary: */
+	IssmDouble A,e;
+	IssmDouble Btmp,B,n,Z;
+
+	/*Get B and n*/
+	Btmp=GetBbar();
+	Z=GetZbar();
+	n=GetN();
+	B=Z*Btmp;
+
+	if (n==1){
+		/*Viscous behaviour! viscosity=B: */
+		viscosity=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
+			viscosity=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		}
+		else{
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			exy=*(epsilon+2);
+
+			/*Build viscosity: viscosity=B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+			if(A==0){
+				/*Maxiviscositym viscosity for 0 shear areas: */
+				viscosity=2.5*pow(10.,17.);
+			}
+			else{
+				e=(n-1)/(2*n);
+				viscosity=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Return: */
+	*pviscosity=viscosity;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosity3d {{{*/
+void  Matdamageice::GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* epsilon){
+
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *                                               B
+	 * viscosity3d= -------------------------------------------------------------------
+	 *                      2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 *     where mu is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	 *     vector, and n the flow law exponent.
+	 *
+	 * If epsilon is NULL, it means this is the first time Emg is being run, and we 
+	 * return g, initial viscosity.
+	 */
+	
+	/*output: */
+	IssmDouble viscosity3d;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,exz,eyz;
+
+	/*Intermediaries: */
+	IssmDouble A,e;
+	IssmDouble B,n,Z;
+
+	/*Get B, Z and n*/
+	n=GetN();
+	Z=GetZ();
+	B=Z*GetB();
+
+	if (n==1){
+		/*Viscous behaviour! viscosity3d=B: */
+		viscosity3d=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0)){
+			viscosity3d=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		}
+		else{
+
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			exy=*(epsilon+2);
+			exz=*(epsilon+3);
+			eyz=*(epsilon+4);
+
+			/*Build viscosity: viscosity3d=2*B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+pow(exz,2)+pow(eyz,2)+exx*eyy;
+			if(A==0){
+				/*Maxiviscosity3dm viscosity for 0 shear areas: */
+				viscosity3d=2.25*pow((IssmDouble)10,(IssmDouble)17);
+			}
+			else{
+				e=(n-1)/2/n;
+			
+				viscosity3d=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity3d<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Assign output pointers:*/
+	*pviscosity3d=viscosity3d;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosity3dStokes {{{*/
+void  Matdamageice::GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon){
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *                                          B
+	 * viscosity3d= -------------------------------------------------------------------
+	 *                   2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 *     where mu is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	 *     vector, and n the flow law exponent.
+	 *
+	 * If epsilon is NULL, it means this is the first time Emg is being run, and we 
+	 * return g, initial viscosity.
+	 */
+	
+	/*output: */
+	IssmDouble viscosity3d;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,exz,eyz,ezz;
+
+	/*Intermediaries: */
+	IssmDouble A,e;
+	IssmDouble B,n,Z;
+	IssmDouble eps0;
+
+	/*Get B and n*/
+	eps0=pow((IssmDouble)10,(IssmDouble)-27);
+	n=GetN();
+	Z=GetZ();
+	B=Z*GetB();
+	
+	if (n==1){
+		/*Viscous behaviour! viscosity3d=B: */
+		viscosity3d=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0) && (epsilon[5]==0)){
+			viscosity3d=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		}
+		else{
+
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			ezz=*(epsilon+2); //not used
+			exy=*(epsilon+3);
+			exz=*(epsilon+4);
+			eyz=*(epsilon+5);
+
+			/*Build viscosity: viscosity3d=B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+pow(exz,2)+pow(eyz,2)+exx*eyy+pow(eps0,2);
+			if(A==0){
+				/*Maxiviscosity3dm viscosity for 0 shear areas: */
+				viscosity3d=2.25*pow((IssmDouble)10,(IssmDouble)17);
+			}
+			else{
+				e=(n-1)/2/n;
+				viscosity3d=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity3d<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Assign output pointers:*/
+	*pviscosity3d=viscosity3d;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosityComplement {{{*/
+void  Matdamageice::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *  										                1
+	 * viscosity= -------------------------------------------------------------------
+	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 * If epsilon is NULL, it means this is the first time Gradjb is being run, and we 
+	 * return mu20, initial viscosity.
+	 */
+	
+	/*output: */
+	IssmDouble viscosity_complement;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary value A and exponent e: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+
+	/*Get B and n*/
+	B=GetBbar();
+	n=GetN();
+
+	if(epsilon){
+		exx=*(epsilon+0);
+		eyy=*(epsilon+1);
+		exy=*(epsilon+2);
+
+		/*Build viscosity: mu2=B/(2*A^e) */
+		A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+		if(A==0){
+			/*Maximum viscosity_complement for 0 shear areas: */
+			viscosity_complement=2.25*pow((IssmDouble)10,(IssmDouble)17);
+		}
+		else{
+			e=(n-1)/(2*n);
+		
+			viscosity_complement=1/(2*pow(A,e));
+		}
+	}
+	else{
+		viscosity_complement=4.5*pow((IssmDouble)10,(IssmDouble)17);
+	}
+
+	/*Checks in debugging mode*/
+	_assert_(B>0);
+	_assert_(n>0);
+	_assert_(viscosity_complement>0);
+		
+	/*Return: */
+	*pviscosity_complement=viscosity_complement;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosityZComplement {{{*/
+void  Matdamageice::GetViscosityZComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
+	/*Return viscosity derivative for control method d(mu)/dZ: 
+	 *
+	 *  										               B 
+	 * dviscosity= -------------------------------------------------------------------
+	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 * If epsilon is NULL, it means this is the first time Gradjb is being run, and we 
+	 * return mu20, initial viscosity.
+	 */
+	
+	/*output: */
+	IssmDouble viscosity_complement;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary value A and exponent e: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+
+	/*Get B and n*/
+	B=GetBbar();
+	n=GetN();
+
+	if(epsilon){
+		exx=*(epsilon+0);
+		eyy=*(epsilon+1);
+		exy=*(epsilon+2);
+
+		/*Build viscosity: mu2=B/(2*A^e) */
+		A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+		if(A==0){
+			/*Maximum viscosity_complement for 0 shear areas: */
+			viscosity_complement=2.25*pow((IssmDouble)10,(IssmDouble)17);
+		}
+		else{
+			e=(n-1)/(2*n);
+		
+			viscosity_complement=B/(2*pow(A,e));
+		}
+	}
+	else{
+		viscosity_complement=4.5*pow((IssmDouble)10,(IssmDouble)17);
+	}
+
+	/*Checks in debugging mode*/
+	_assert_(B>0);
+	_assert_(n>0);
+	_assert_(viscosity_complement>0);
+		
+	/*Return: */
+	*pviscosity_complement=viscosity_complement;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosityDerivativeEpsSquare{{{*/
+void  Matdamageice::GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
+
+	/*output: */
+	IssmDouble mu_prime;
+	IssmDouble mu,n,eff2;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,exz,eyz;
+
+	/*Get visocisty and n*/
+	GetViscosity3d(&mu,epsilon);
+	n=GetN();
+
+	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0)){
+		mu_prime=0.5*pow((IssmDouble)10,(IssmDouble)14);
+	}
+	else{
+		/*Retrive strain rate components: */
+		exx=epsilon[0];
+		eyy=epsilon[1];
+		exy=epsilon[2];
+		exz=epsilon[3];
+		eyz=epsilon[4];
+		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy + exz*exz + eyz*eyz;
+
+		mu_prime=(1-n)/(2*n) * mu/eff2;
+	}
+
+	/*Assign output pointers:*/
+	*pmu_prime=mu_prime;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosity2dDerivativeEpsSquare{{{*/
+void  Matdamageice::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
+
+	/*output: */
+	IssmDouble mu_prime;
+	IssmDouble mu,n,eff2;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,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 Matdamageice::InputDuplicate{{{*/
+void  Matdamageice::InputDuplicate(int original_enum,int new_enum){
+
+	/*Call inputs method*/
+	if (IsInput(original_enum)) inputs->DuplicateInput(original_enum,new_enum);
+
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
+void  Matdamageice::InputUpdateFromVector(IssmDouble* vector, int name, int type){
+
+	/*Intermediaries*/
+	Element *element      = NULL;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			switch(element->ObjectEnum()){
+
+				case TriaEnum: {
+					IssmDouble values[3];
+					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexDof()];
+					this->inputs->AddInput(new TriaP1Input(name,values));
+					return;
+				}
+				default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+			}
+		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromVector(int* vector, int name, int type) {{{*/
+void  Matdamageice::InputUpdateFromVector(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromVector(bool* vector, int name, int type) {{{*/
+void  Matdamageice::InputUpdateFromVector(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type) {{{*/
+void  Matdamageice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
+
+	/*Intermediaries*/
+	Element *element      = NULL;
+	Parameters* parameters= NULL;
+	int         dim;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			switch(element->ObjectEnum()){
+
+				case TriaEnum: {
+					IssmDouble values[3];
+					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->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: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+			}
+		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+
+
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromMatrixDakota(int* vector, int name, int type) {{{*/
+void  Matdamageice::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromVectorDakota(int* vector, int name, int type) {{{*/
+void  Matdamageice::InputUpdateFromVectorDakota(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromVectorDakota(bool* vector, int name, int type) {{{*/
+void  Matdamageice::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
+void  Matdamageice::InputUpdateFromConstant(IssmDouble constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromConstant(int constant, int name) {{{*/
+void  Matdamageice::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromConstant(bool constant, int name) {{{*/
+void  Matdamageice::InputUpdateFromConstant(bool constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromSolution{{{*/
+void  Matdamageice::InputUpdateFromSolution(IssmDouble* solution){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matdamageice::InputUpdateFromIoModel{{{*/
+void Matdamageice::InputUpdateFromIoModel(int index, IoModel* iomodel){
+
+	int i,j;
+
+	int    dim;
+	bool   control_analysis;
+	int    num_control_type;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+
+	/*if 2d*/
+	if(dim==2){
+
+		/*Intermediaries*/
+		const int num_vertices = 3; //Tria has 3 vertices
+		IssmDouble    nodeinputs[num_vertices];
+		IssmDouble    cmmininputs[num_vertices];
+		IssmDouble    cmmaxinputs[num_vertices];
+
+		/*Get B*/
+		if (iomodel->Data(MaterialsRheologyBEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
+			this->inputs->AddInput(new 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));
+		}
+
+		/*Get Z*/
+		if (iomodel->Data(MaterialsRheologyZEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyZEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
+			this->inputs->AddInput(new TriaP1Input(MaterialsRheologyZbarEnum,nodeinputs));
+		}
+
+		/*Control Inputs*/
+		#ifdef _HAVE_CONTROL_
+		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+			for(i=0;i<num_control_type;i++){
+				switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
+					case MaterialsRheologyBbarEnum:
+						if (iomodel->Data(MaterialsRheologyBEnum)){
+							_assert_(iomodel->Data(MaterialsRheologyBEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(MaterialsRheologyBbarEnum,TriaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						}
+						break;
+					case MaterialsRheologyZbarEnum:
+						if (iomodel->Data(MaterialsRheologyZEnum)){
+							_assert_(iomodel->Data(MaterialsRheologyZEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyZEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(MaterialsRheologyZbarEnum,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)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
+			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,nodeinputs));
+		}
+
+		/*Get n*/
+		if (iomodel->Data(MaterialsRheologyNEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
+			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyNEnum,nodeinputs));
+		}
+
+		/*Get Z*/
+		if (iomodel->Data(MaterialsRheologyZEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyZEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
+			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyZEnum,nodeinputs));
+		}
+
+		/*Control Inputs*/
+		#ifdef _HAVE_CONTROL_
+		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+			for(i=0;i<num_control_type;i++){
+				switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
+					case MaterialsRheologyBbarEnum:
+						if (iomodel->Data(MaterialsRheologyBEnum)){
+							_assert_(iomodel->Data(MaterialsRheologyBEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						}
+						break;
+					case MaterialsRheologyZbarEnum:
+						if (iomodel->Data(MaterialsRheologyZEnum)){
+							_assert_(iomodel->Data(MaterialsRheologyZEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyZEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(MaterialsRheologyZEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						}
+						break;
+				}
+			}
+		}
+		#endif
+	}
+	#endif
+	else{
+		_error_("Mesh type not supported yet!");
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::IsInput{{{*/
+bool Matdamageice::IsInput(int name){
+	if (
+				name==MaterialsRheologyBEnum ||
+				name==MaterialsRheologyBbarEnum ||
+				name==MaterialsRheologyNEnum ||
+				name==MaterialsRheologyZEnum ||
+				name==MaterialsRheologyZbarEnum
+		){
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Materials/Matdamageice.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Matdamageice.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Materials/Matdamageice.h	(revision 13395)
@@ -0,0 +1,70 @@
+/*!\file Matdamageice.h
+ * \brief: header file for matice object
+ */
+
+#ifndef MATDAMAGEICE_H_
+#define MATDAMAGEICE_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Material.h"
+class IoModel;
+/*}}}*/
+
+class Matdamageice: public Material{
+
+	private: 
+		int	   mid;
+		Hook* helement;
+
+	public:
+		/*Matdamageice constructors, destructors: {{{*/
+		Matdamageice();
+		Matdamageice(int mid,int i, IoModel* iomodel);
+		~Matdamageice();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   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<IssmDouble>* vector,int input_enum);
+		void   SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin);
+		void   GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon);
+		void   GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon);
+		void   GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon);
+		void   GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
+		void   GetViscosityZComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
+		void   GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		void   GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		IssmDouble GetA();
+		IssmDouble GetB();
+		IssmDouble GetBbar();
+		IssmDouble GetN();
+		IssmDouble GetZ();
+		IssmDouble GetZbar();
+		bool   IsInput(int name);
+		/*}}}*/
+};
+
+#endif  /* _MATICE_H_ */
Index: /issm/trunk/src/c/classes/objects/Materials/Material.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Material.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Materials/Material.h	(revision 13395)
@@ -0,0 +1,42 @@
+/*!\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: 
+		Inputs*  inputs;
+		virtual       ~Material(){};
+		/*WARNING: input should not be public but it is an easy way to update B from T (using UpdateFromSolution) from Pentas*/
+
+		/*Numerics*/
+		virtual void       InputDuplicate(int original_enum,int new_enum)=0;
+		virtual void       Configure(Elements* elements)=0;
+		virtual void       GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum)=0;
+		virtual void       GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon)=0;
+		virtual void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosityZComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
+		virtual IssmDouble GetA()=0;
+		virtual IssmDouble GetB()=0;
+		virtual IssmDouble GetBbar()=0;
+		virtual IssmDouble GetN()=0;
+		virtual IssmDouble GetZ()=0;
+		virtual IssmDouble GetZbar()=0;
+
+};
+#endif
Index: /issm/trunk/src/c/classes/objects/Materials/Matice.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Matice.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Materials/Matice.cpp	(revision 13395)
@@ -0,0 +1,783 @@
+/*!\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::GetA {{{*/
+IssmDouble Matice::GetA(){
+	/*
+	 * A = 1/B^n
+	 */
+
+	IssmDouble B,n;
+
+	inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	n=this->GetN();
+
+	return pow(B,-n);
+}
+/*}}}*/
+/*FUNCTION Matice::GetB {{{*/
+IssmDouble Matice::GetB(){
+
+	/*Output*/
+	IssmDouble B;
+
+	inputs->GetInputAverage(&B,MaterialsRheologyBEnum);
+	return B;
+}
+/*}}}*/
+/*FUNCTION Matice::GetBbar {{{*/
+IssmDouble Matice::GetBbar(){
+
+	/*Output*/
+	IssmDouble Bbar;
+
+	inputs->GetInputAverage(&Bbar,MaterialsRheologyBbarEnum);
+	return Bbar;
+}
+/*}}}*/
+/*FUNCTION Matice::GetN {{{*/
+IssmDouble Matice::GetN(){
+
+	/*Output*/
+	IssmDouble n;
+
+	inputs->GetInputAverage(&n,MaterialsRheologyNEnum);
+	return n;
+}
+/*}}}*/
+/*FUNCTION Matice::GetVectorFromInputs{{{*/
+void  Matice::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
+
+	/*Intermediaries*/
+	Element *element= NULL;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that input_enum is a material input*/
+	if (!IsInput(input_enum)) return;
+
+	switch(element->ObjectEnum()){
+
+		case TriaEnum:{
+
+			/*Prepare index list*/
+			int 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) _error_("Input " << EnumToStringx(input_enum) << " not found in material");
+
+			/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
+			input->GetVectorFromInputs(vector,&doflist1[0]);}
+			break;
+
+		default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosity2d {{{*/
+void  Matice::GetViscosity2d(IssmDouble* pviscosity, IssmDouble* epsilon){
+	/*From a string tensor and a material object, return viscosity, using Glen's flow law.
+												    B
+	  viscosity= -------------------------------------------------------------------
+						  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+
+	  where viscosity is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	  vector, and n the flow law exponent.
+
+	  If epsilon is NULL, it means this is the first time SystemMatrices is being run, and we 
+	  return 10^14, initial viscosity.
+	  */
+
+	/*output: */
+	IssmDouble viscosity;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+
+	/*Get B and n*/
+	B=GetBbar();
+	n=GetN();
+
+	if (n==1){
+		/*Viscous behaviour! viscosity=B: */
+		viscosity=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
+			viscosity=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		}
+		else{
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			exy=*(epsilon+2);
+
+			/*Build viscosity: viscosity=B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+			if(A==0){
+				/*Maxiviscositym viscosity for 0 shear areas: */
+				viscosity=2.5*pow(10.,17.);
+			}
+			else{
+				e=(n-1)/(2*n);
+				viscosity=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Return: */
+	*pviscosity=viscosity;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosity3d {{{*/
+void  Matice::GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* epsilon){
+
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *                                               B
+	 * viscosity3d= -------------------------------------------------------------------
+	 *                      2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 *     where mu is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	 *     vector, and n the flow law exponent.
+	 *
+	 * If epsilon is NULL, it means this is the first time Emg is being run, and we 
+	 * return g, initial viscosity.
+	 */
+	
+	/*output: */
+	IssmDouble viscosity3d;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,exz,eyz;
+
+	/*Intermediaries: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+
+	/*Get B and n*/
+	B=GetB();
+	n=GetN();
+
+	if (n==1){
+		/*Viscous behaviour! viscosity3d=B: */
+		viscosity3d=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0)){
+			viscosity3d=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		}
+		else{
+
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			exy=*(epsilon+2);
+			exz=*(epsilon+3);
+			eyz=*(epsilon+4);
+
+			/*Build viscosity: viscosity3d=2*B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+pow(exz,2)+pow(eyz,2)+exx*eyy;
+			if(A==0){
+				/*Maxiviscosity3dm viscosity for 0 shear areas: */
+				viscosity3d=2.25*pow((IssmDouble)10,(IssmDouble)17);
+			}
+			else{
+				e=(n-1)/2/n;
+			
+				viscosity3d=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity3d<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Assign output pointers:*/
+	*pviscosity3d=viscosity3d;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosity3dStokes {{{*/
+void  Matice::GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon){
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *                                          B
+	 * viscosity3d= -------------------------------------------------------------------
+	 *                   2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 *     where mu is the viscotiy, B the flow law parameter , (u,v) the velocity 
+	 *     vector, and n the flow law exponent.
+	 *
+	 * If epsilon is NULL, it means this is the first time Emg is being run, and we 
+	 * return g, initial viscosity.
+	 */
+	
+	/*output: */
+	IssmDouble viscosity3d;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,exz,eyz,ezz;
+
+	/*Intermediaries: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+	IssmDouble eps0;
+
+	/*Get B and n*/
+	eps0=pow((IssmDouble)10,(IssmDouble)-27);
+	B=GetB();
+	n=GetN();
+	
+	if (n==1){
+		/*Viscous behaviour! viscosity3d=B: */
+		viscosity3d=B/2;
+	}
+	else{
+		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0) && (epsilon[5]==0)){
+			viscosity3d=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		}
+		else{
+
+			/*Retrive strain rate components: */
+			exx=*(epsilon+0);
+			eyy=*(epsilon+1);
+			ezz=*(epsilon+2); //not used
+			exy=*(epsilon+3);
+			exz=*(epsilon+4);
+			eyz=*(epsilon+5);
+
+			/*Build viscosity: viscosity3d=B/(2*A^e) */
+			A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+pow(exz,2)+pow(eyz,2)+exx*eyy+pow(eps0,2);
+			if(A==0){
+				/*Maxiviscosity3dm viscosity for 0 shear areas: */
+				viscosity3d=2.25*pow((IssmDouble)10,(IssmDouble)17);
+			}
+			else{
+				e=(n-1)/2/n;
+				viscosity3d=B/(2*pow(A,e));
+			}
+		}
+	}
+
+	/*Checks in debugging mode*/
+	if(viscosity3d<=0) _error_("Negative viscosity");
+	_assert_(B>0);
+	_assert_(n>0);
+
+	/*Assign output pointers:*/
+	*pviscosity3d=viscosity3d;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosityComplement {{{*/
+void  Matice::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
+	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	 *
+	 *  										                1
+	 * viscosity= -------------------------------------------------------------------
+	 *  				  2[ exx^2+eyy^2+exx*eyy+exy^2+exz^2+eyz^2 ]^[(n-1)/2n]
+	 *
+	 * If epsilon is NULL, it means this is the first time Gradjb is being run, and we 
+	 * return mu20, initial viscosity.
+	 */
+	
+	/*output: */
+	IssmDouble viscosity_complement;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy;
+
+	/*Intermediary value A and exponent e: */
+	IssmDouble A,e;
+	IssmDouble B,n;
+
+	/*Get B and n*/
+	B=GetBbar();
+	n=GetN();
+
+	if(epsilon){
+		exx=*(epsilon+0);
+		eyy=*(epsilon+1);
+		exy=*(epsilon+2);
+
+		/*Build viscosity: mu2=B/(2*A^e) */
+		A=pow(exx,2)+pow(eyy,2)+pow(exy,2)+exx*eyy;
+		if(A==0){
+			/*Maximum viscosity_complement for 0 shear areas: */
+			viscosity_complement=2.25*pow((IssmDouble)10,(IssmDouble)17);
+		}
+		else{
+			e=(n-1)/(2*n);
+		
+			viscosity_complement=1/(2*pow(A,e));
+		}
+	}
+	else{
+		viscosity_complement=4.5*pow((IssmDouble)10,(IssmDouble)17);
+	}
+
+	/*Checks in debugging mode*/
+	_assert_(B>0);
+	_assert_(n>0);
+	_assert_(viscosity_complement>0);
+		
+	/*Return: */
+	*pviscosity_complement=viscosity_complement;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosityDerivativeEpsSquare{{{*/
+void  Matice::GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
+
+	/*output: */
+	IssmDouble mu_prime;
+	IssmDouble mu,n,eff2;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,exz,eyz;
+
+	/*Get visocisty and n*/
+	GetViscosity3d(&mu,epsilon);
+	n=GetN();
+
+	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0)){
+		mu_prime=0.5*pow((IssmDouble)10,(IssmDouble)14);
+	}
+	else{
+		/*Retrive strain rate components: */
+		exx=epsilon[0];
+		eyy=epsilon[1];
+		exy=epsilon[2];
+		exz=epsilon[3];
+		eyz=epsilon[4];
+		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy + exz*exz + eyz*eyz;
+
+		mu_prime=(1-n)/(2*n) * mu/eff2;
+	}
+
+	/*Assign output pointers:*/
+	*pmu_prime=mu_prime;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosity2dDerivativeEpsSquare{{{*/
+void  Matice::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
+
+	/*output: */
+	IssmDouble mu_prime;
+	IssmDouble mu,n,eff2;
+
+	/*input strain rate: */
+	IssmDouble exx,eyy,exy,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: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+			}
+		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVector(int* vector, int name, int type) {{{*/
+void  Matice::InputUpdateFromVector(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVector(bool* vector, int name, int type) {{{*/
+void  Matice::InputUpdateFromVector(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type) {{{*/
+void  Matice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
+
+	/*Intermediaries*/
+	Element *element      = NULL;
+	Parameters* parameters= NULL;
+	int         dim;
+
+	/*Recover element*/
+	element=(Element*)helement->delivers();
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+
+			switch(element->ObjectEnum()){
+
+				case TriaEnum: {
+					IssmDouble values[3];
+					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->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: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
+			}
+		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+
+
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromMatrixDakota(int* vector, int name, int type) {{{*/
+void  Matice::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVectorDakota(int* vector, int name, int type) {{{*/
+void  Matice::InputUpdateFromVectorDakota(int* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromVectorDakota(bool* vector, int name, int type) {{{*/
+void  Matice::InputUpdateFromVectorDakota(bool* vector, int name, int type){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
+void  Matice::InputUpdateFromConstant(IssmDouble constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromConstant(int constant, int name) {{{*/
+void  Matice::InputUpdateFromConstant(int constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromConstant(bool constant, int name) {{{*/
+void  Matice::InputUpdateFromConstant(bool constant, int name){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromSolution{{{*/
+void  Matice::InputUpdateFromSolution(IssmDouble* solution){
+	/*Nothing updated yet*/
+}
+/*}}}*/
+/*FUNCTION Matice::InputUpdateFromIoModel{{{*/
+void Matice::InputUpdateFromIoModel(int index, IoModel* iomodel){
+
+	int i,j;
+
+	int    dim;
+	bool   control_analysis;
+	int    num_control_type;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&dim,MeshDimensionEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
+
+	/*if 2d*/
+	if(dim==2){
+
+		/*Intermediaries*/
+		const int num_vertices = 3; //Tria has 3 vertices
+		IssmDouble    nodeinputs[num_vertices];
+		IssmDouble    cmmininputs[num_vertices];
+		IssmDouble    cmmaxinputs[num_vertices];
+
+		/*Get B*/
+		if (iomodel->Data(MaterialsRheologyBEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
+			this->inputs->AddInput(new 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(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
+					case MaterialsRheologyBbarEnum:
+						if (iomodel->Data(MaterialsRheologyBEnum)){
+							_assert_(iomodel->Data(MaterialsRheologyBEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(MaterialsRheologyBbarEnum,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)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
+			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,nodeinputs));
+		}
+
+		/*Get n*/
+		if (iomodel->Data(MaterialsRheologyNEnum)) {
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
+			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyNEnum,nodeinputs));
+		}
+
+		/*Control Inputs*/
+		#ifdef _HAVE_CONTROL_
+		if (control_analysis && iomodel->Data(InversionControlParametersEnum)){
+			for(i=0;i<num_control_type;i++){
+				switch(reCast<int>(iomodel->Data(InversionControlParametersEnum)[i])){
+					case MaterialsRheologyBbarEnum:
+						if (iomodel->Data(MaterialsRheologyBEnum)){
+							_assert_(iomodel->Data(MaterialsRheologyBEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						}
+						break;
+				}
+			}
+		}
+		#endif
+	}
+	#endif
+	else{
+		_error_("Mesh type not supported yet!");
+	}
+
+	return;
+}
+/*}}}*/
+/*FUNCTION Matice::IsInput{{{*/
+bool Matice::IsInput(int name){
+	if (
+				name==MaterialsRheologyBEnum ||
+				name==MaterialsRheologyBbarEnum ||
+				name==MaterialsRheologyNEnum
+		){
+		return true;
+	}
+	else return false;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Materials/Matice.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Matice.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Materials/Matice.h	(revision 13395)
@@ -0,0 +1,70 @@
+/*!\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: 
+		int	   mid;
+		Hook* helement;
+
+	public:
+		/*Matice constructors, destructors: {{{*/
+		Matice();
+		Matice(int mid,int i, IoModel* iomodel);
+		~Matice();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   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<IssmDouble>* vector,int input_enum);
+		void       SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void       GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon);
+		void       GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon);
+		void       GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon);
+		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
+		void GetViscosityZComplement(IssmDouble*, IssmDouble*){_error_("not supported");};
+		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		IssmDouble GetA();
+		IssmDouble GetB();
+		IssmDouble GetBbar();
+		IssmDouble GetZ(){_error_("not supported");};
+		IssmDouble GetZbar(){_error_("not supported");};
+		IssmDouble GetN();
+		bool       IsInput(int name);
+		/*}}}*/
+};
+
+#endif  /* _MATICE_H_ */
Index: /issm/trunk/src/c/classes/objects/Materials/Matpar.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Matpar.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Materials/Matpar.cpp	(revision 13395)
@@ -0,0 +1,362 @@
+/*!\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);
+	this->inputs=NULL; /*not used here*/
+}
+/*}}}*/
+/*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/trunk/src/c/classes/objects/Materials/Matpar.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Matpar.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Materials/Matpar.h	(revision 13395)
@@ -0,0 +1,112 @@
+/*!\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){_error_("not implemented yet");};
+		/*}}}*/
+		/*Material virtual functions resolution: {{{*/
+		void   InputDuplicate(int original_enum,int new_enum){_error_("not implemented yet");};
+		void   Configure(Elements* elements);
+		void   GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){return;}
+		void       GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon){_error_("not supported");};
+		void       GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon){_error_("not supported");};
+		void       GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon){_error_("not supported");};
+		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon){_error_("not supported");};
+		void       GetViscosityZComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon){_error_("not supported");};
+		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon){_error_("not supported");};
+		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon){_error_("not supported");};
+		IssmDouble GetA(){_error_("not supported");};
+		IssmDouble GetB(){_error_("not supported");};
+		IssmDouble GetBbar(){_error_("not supported");};
+		IssmDouble GetN(){_error_("not supported");};
+		IssmDouble GetZ(){_error_("not supported");};
+		IssmDouble GetZbar(){_error_("not supported");};
+		/*}}}*/
+		/*Numerics: {{{*/
+		IssmDouble GetG();
+		IssmDouble GetRhoIce();
+		IssmDouble GetRhoWater();
+		IssmDouble GetRhoFreshwater();
+		IssmDouble GetMuWater();
+		IssmDouble GetMixedLayerCapacity();
+		IssmDouble GetThermalExchangeVelocity();
+		IssmDouble GetHeatCapacity();
+		IssmDouble GetThermalConductivity();
+		IssmDouble GetLatentHeat();
+		IssmDouble GetBeta();
+		IssmDouble GetMeltingPoint();
+		IssmDouble GetReferenceTemperature();
+		IssmDouble 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/trunk/src/c/classes/objects/Node.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Node.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Node.cpp	(revision 13395)
@@ -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)) _error_("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 && !reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
+				for(k=1;k<=gsize;k++) this->FreezeDof(k);
+			}
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==L1L2ApproximationEnum && !reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
+				for(k=1;k<=gsize;k++) this->FreezeDof(k);
+			}
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealPattynApproximationEnum && reCast<int>(iomodel->Data(FlowequationBordermacayealEnum)[io_index])){
+				if(!reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
+					for(k=1;k<=gsize;k++) this->FreezeDof(k);
+				}
+			}
+			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealStokesApproximationEnum && reCast<int>(iomodel->Data(FlowequationBordermacayealEnum)[io_index])){
+				if(!reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
+					for(k=1;k<=2;k++) this->FreezeDof(k);
+				}
+			}
+		}
+		/*spc all nodes on hutter*/
+		if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==HutterApproximationEnum){
+			for(k=1;k<=gsize;k++){
+				this->FreezeDof(k);
+			}
+		}
+	}
+	#endif
+
+	/*Diagnostic Hutter*/
+	if (analysis_type==DiagnosticHutterAnalysisEnum){
+		_assert_(iomodel->Data(FlowequationVertexEquationEnum));
+		/*Constrain all nodes that are not Hutter*/
+		if (reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[io_index])!=HutterApproximationEnum){
+			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){
+
+	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
+	 * datasets, using internal ids and off_sets hidden in hooks: */
+	hvertex->configure(verticesin);
+
+}/*}}}*/
+/*FUNCTION Node::SetCurrentConfiguration {{{*/
+void  Node::SetCurrentConfiguration(DataSet* nodesin,Vertices* verticesin){
+
+}/*}}}*/
+/*FUNCTION Node::GetDof {{{*/
+int   Node::GetDof(int dofindex,int setenum){
+
+	if(setenum==GsetEnum){
+		_assert_(dofindex>=0 && dofindex<indexing.gsize);
+		return indexing.gdoflist[dofindex];
+	}
+	else if(setenum==FsetEnum){
+		_assert_(dofindex>=0 && dofindex<indexing.fsize);
+		return indexing.fdoflist[dofindex];
+	}
+	else if(setenum==SsetEnum){
+		_assert_(dofindex>=0 && dofindex<indexing.ssize);
+		return indexing.sdoflist[dofindex];
+	}
+	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+
+} /*}}}*/
+/*FUNCTION Node::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 _error_("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 _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+	else{
+
+		if(setenum==GsetEnum){
+			if(indexing.doftype){
+				count=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.doftype[i]==approximation_enum){
+						outdoflist[count]=count;
+						count++;
+					}
+				}
+				_assert_(count);
+			}
+			else for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=i;
+		}
+		else if(setenum==FsetEnum){
+
+			if(indexing.doftype){
+				count=0;
+				count2=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.doftype[i]==approximation_enum){
+						if(indexing.f_set[i]){
+							outdoflist[count]=count2;
+							count++;
+						}
+						count2++;
+					}
+				}
+				_assert_(count2);
+			}
+			else{
+
+				count=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.f_set[i]){
+						outdoflist[count]=i;
+						count++;
+					}
+				}
+			}
+		}
+		else if(setenum==SsetEnum){
+			if(indexing.doftype){
+				count=0;
+				count2=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.doftype[i]==approximation_enum){
+						if(indexing.s_set[i]){
+							outdoflist[count]=count2;
+							count++;
+						}
+						count2++;
+					}
+				}
+				_assert_(count2);
+			}
+			else{
+				count=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(indexing.s_set[i]){
+						outdoflist[count]=i;
+						count++;
+					}
+				}
+			}
+		}
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+}
+/*}}}*/
+/*FUNCTION Node::Sid{{{*/
+int    Node::Sid(void){ return sid; }
+/*}}}*/
+/*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<IssmDouble>* pv_g,Vector<IssmDouble>* pv_f,Vector<IssmDouble>* pv_s){
+
+	IssmDouble gvalue=1.0; //all nodes are in the g set;
+	IssmDouble value;
+
+	int i;
+
+	for(i=0;i<this->indexing.gsize;i++){
+
+		/*g set: */
+		pv_g->SetValue(indexing.gdoflist[i],gvalue,INS_VAL);
+		
+		/*f set: */
+		value=(IssmDouble)this->indexing.f_set[i];
+		pv_f->SetValue(indexing.gdoflist[i],value,INS_VAL);
+
+		/*s set: */
+		value=(IssmDouble)this->indexing.s_set[i];
+		pv_s->SetValue(indexing.gdoflist[i],value,INS_VAL);
+
+	}
+
+
+}
+/*}}}*/
+/*FUNCTION Node::CreateNodalConstraints{{{*/
+void  Node::CreateNodalConstraints(Vector<IssmDouble>* ys){
+
+	int i;
+	IssmDouble* values=NULL;
+	int count;
+
+	/*Recover values for s set and plug them in constraints vector: */
+	if(this->indexing.ssize){
+		values=xNew<IssmDouble>(this->indexing.ssize);
+		count=0;
+		for(i=0;i<this->indexing.gsize;i++){
+			if(this->indexing.s_set[i]){
+				values[count]=this->indexing.svalues[i];
+				_assert_(!xIsNan<IssmDouble>(values[count]));
+				count++;
+			}
+		}
+		
+		/*Add values into constraint vector: */
+		ys->SetValues(this->indexing.ssize,this->indexing.sdoflist,values,INS_VAL);
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+
+
+}
+/*}}}*/
+/*FUNCTION Node::DofInSSet {{{*/
+void  Node::DofInSSet(int dof){
+
+	/*Put dof for this node into the s set (ie, this dof will be constrained 
+	 * to a fixed value during computations. */
+
+	this->indexing.f_set[dof]=0; //n splits into f (for which we solve) and s (single point constraints)
+	this->indexing.s_set[dof]=1;
+}
+/*}}}*/
+/*FUNCTION Node::DofInFSet {{{*/
+void  Node::DofInFSet(int dof){
+
+	/*Put dof for this node into the f set (ie, this dof will NOT be constrained 
+	 * to a fixed value during computations. */
+
+	this->indexing.f_set[dof]=1; 
+	this->indexing.s_set[dof]=0;
+}
+/*}}}*/
+/*FUNCTION Node::FreezeDof{{{*/
+void  Node::FreezeDof(int dof){
+	
+	DofInSSet(dof-1); //with 0 displacement for this dof.
+
+}
+/*}}}*/
+/*FUNCTION Node::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 _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+	else{
+		if(setenum==GsetEnum){
+			if(this->indexing.doftype){
+				numdofs=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if(this->indexing.doftype[i]==approximation_enum) numdofs++;
+				}
+			}
+			else numdofs=this->indexing.gsize;
+		}
+		else if (setenum==FsetEnum){
+			if(this->indexing.doftype){
+				numdofs=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if((this->indexing.doftype[i]==approximation_enum) && (this->indexing.f_set[i])) numdofs++;
+				}
+			}
+			else numdofs=this->indexing.fsize;
+		}
+		else if (setenum==SsetEnum){
+			if(this->indexing.doftype){
+				numdofs=0;
+				for(i=0;i<this->indexing.gsize;i++){
+					if((this->indexing.doftype[i]==approximation_enum) && (this->indexing.s_set[i])) numdofs++;
+				}
+			}
+			else numdofs=this->indexing.ssize;
+		}
+		else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
+	return numdofs;
+}
+/*}}}*/
+/*FUNCTION Node::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<IssmDouble>* ug, IssmDouble* vector_serial,int setenum){
+
+	IssmDouble* values=NULL;
+	int*    indices=NULL;
+	int     count=0;
+	int     i;
+
+	if(setenum==FsetEnum){
+		if(this->indexing.fsize){
+			indices=xNew<int>(this->indexing.fsize);
+ 			values=xNew<IssmDouble>(this->indexing.fsize);
+
+			for(i=0;i<this->indexing.gsize;i++){
+				if(this->indexing.f_set[i]){
+					_assert_(vector_serial);
+					values[count]=vector_serial[this->indexing.fdoflist[count]];
+					indices[count]=this->indexing.gdoflist[i];
+					count++;
+				}
+			}
+
+			/*Add values into ug: */
+			ug->SetValues(this->indexing.fsize,indices,values,INS_VAL);
+		}
+	}
+	else if(setenum==SsetEnum){
+		if(this->indexing.ssize){
+			indices=xNew<int>(this->indexing.ssize);
+			values=xNew<IssmDouble>(this->indexing.ssize);
+
+			for(i=0;i<this->indexing.gsize;i++){
+				if(this->indexing.s_set[i]){
+					_assert_(vector_serial);
+					values[count]=vector_serial[this->indexing.sdoflist[count]];
+					indices[count]=this->indexing.gdoflist[i];
+					count++;
+				}
+			}
+
+			/*Add values into ug: */
+			ug->SetValues(this->indexing.ssize,indices,values,INS_VAL);
+		}
+	}
+	else _error_("VecMerge can only merge from the s or f-set onto the g-set!");
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<int>(indices);
+}
+/*}}}*/
+/*FUNCTION Node::VecReduce {{{*/
+void   Node::VecReduce(Vector<IssmDouble>* vector, IssmDouble* ug_serial,int setenum){
+
+	IssmDouble* values=NULL;
+	int     count=0;
+	int     i;
+
+	if(setenum==FsetEnum){
+		if(this->indexing.fsize){
+ 			values=xNew<IssmDouble>(this->indexing.fsize);
+
+			for(i=0;i<this->indexing.gsize;i++){
+				if(this->indexing.f_set[i]){
+					_assert_(ug_serial);
+					values[count]=ug_serial[this->indexing.gdoflist[i]];
+					count++;
+				}
+			}
+
+			/*Add values into ug: */
+			vector->SetValues(this->indexing.fsize,this->indexing.fdoflist,values,INS_VAL);
+		}
+	}
+	else if(setenum==SsetEnum){
+		if(this->indexing.ssize){
+			values=xNew<IssmDouble>(this->indexing.ssize);
+
+			for(i=0;i<this->indexing.gsize;i++){
+				if(this->indexing.s_set[i]){
+					_assert_(ug_serial);
+					values[count]=ug_serial[this->indexing.gdoflist[i]];
+					count++;
+				}
+			}
+
+			/*Add values into ug: */
+			vector->SetValues(this->indexing.ssize,this->indexing.sdoflist,values,INS_VAL);
+		}
+	}
+	else _error_("VecReduce can only merge from the s or f-set onto the g-set!");
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+}
+/*}}}*/
+
+/* 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 _error_("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 _error_("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 _error_("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 _error_("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/trunk/src/c/classes/objects/Node.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Node.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Node.h	(revision 13395)
@@ -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;
+template <class doubletype> class  Vector;
+template <class doubletype> 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(){_error_("Not implemented yet (similar to Elements)");};
+		/*}}}*/
+		/*Update virtual functions definitions: {{{*/
+		
+		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
+		void  InputUpdateFromVector(int* vector, int name, int type);
+		void  InputUpdateFromVector(bool* vector, int name, int type);
+		void  InputUpdateFromMatrixDakota(IssmDouble* matrix,int nrows, int ncols, int name, int type);
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
+		void  InputUpdateFromConstant(IssmDouble constant, int name);
+		void  InputUpdateFromConstant(int constant, int name);
+		void  InputUpdateFromConstant(bool constant, int name);
+		void  InputUpdateFromSolution(IssmDouble* solution){_error_("Not implemented yet!");}
+		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("Not implemented yet!");}
+		/*}}}*/
+		/*Node numerical routines {{{*/
+		void   Configure(DataSet* nodes,Vertices* vertices);
+		void   CreateNodalConstraints(Vector<IssmDouble>* ys);
+		void   SetCurrentConfiguration(DataSet* nodes,Vertices* vertices);
+		int    Sid(void); 
+		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<IssmDouble>* pv_g,Vector<IssmDouble>* pv_f,Vector<IssmDouble>* pv_s);
+		int    GetConnectivity();
+		void   GetDofList(int* poutdoflist,int approximation_enum,int setenum);
+		void   GetLocalDofList(int* poutdoflist,int approximation_enum,int setenum);
+		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<IssmDouble>* ug, IssmDouble* vector_serial,int setenum);
+		void   VecReduce(Vector<IssmDouble>* 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/trunk/src/c/classes/objects/Object.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Object.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Object.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Options/GenericOption.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Options/GenericOption.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Options/GenericOption.h	(revision 13395)
@@ -0,0 +1,128 @@
+/*! \file GenericOption.h 
+ *  \brief: header file for generic option object
+ */
+
+#ifndef _GENERIC_OPTION_
+#define _GENERIC_OPTION_
+
+/*Headers:{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstring>
+
+#include "../../../include/include.h"
+#include "../../../shared/Exceptions/exceptions.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "./OptionUtilities.h"
+
+#include "../Object.h"
+/*}}}*/
+
+template <class OptionType> 
+class GenericOption: public Option {
+
+	public:
+
+		char* name;
+		OptionType value;
+
+		int   numel; //in case OptionType is an array
+		int   ndims; //in case OptionType is a multi-dimensional array: */
+		int*  size;
+
+		/*GenericOption constructors, destructors*/
+		GenericOption(){ /*{{{*/
+
+			name  =NULL;
+			numel =0;
+			ndims =0;
+			size  =NULL;
+
+
+		} /*}}}*/
+		~GenericOption(){ /*{{{*/
+
+			if(size) xDelete<int>(size);
+			if(name) xDelete<char>(name);
+
+		} /*}}}*/
+
+		/*Object virtual functions definitions:*/
+		void Echo(){ /*{{{*/
+
+			this->DeepEcho();
+
+		} /*}}}*/
+		void DeepEcho(){ /*{{{*/
+
+			char  indent[81]="";
+			this->DeepEcho(indent);
+
+		} /*}}}*/
+		void DeepEcho(char* indent){ /*{{{*/
+
+			char  cstr[81];
+			bool  flag=true;
+
+			if(flag) _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]");
+			_printLine_(indent << "         value: " << value);;
+		} /*}}}*/
+		int   Id(){_error_("Not implemented yet");};
+		int   MyRank(){_error_("Not implemented yet");};
+		int   ObjectEnum(){return GenericOptionEnum;};
+		Object* copy(){_error_("Not implemented yet");};
+		
+		/*GenericOption functions: */
+		char* Name(){return name;};
+		int   NumEl(){return numel;};
+		int   NDims(){return ndims;};
+		int*  Size(){return size;};
+		void  Get(OptionType* pvalue){ *pvalue=value; };
+};
+
+#ifdef _HAVE_ADOLC_ //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization. 
+template <> inline void GenericOption<IssmPDouble*>::Get(IssmPDouble** pvalue){ /*{{{*/
+
+	/*Copy vector*/
+	IssmPDouble* outvalue=xNew<IssmPDouble>(this->NumEl());
+	for(int i=0;i<this->NumEl();i++) outvalue[i]=this->value[i];
+
+	/*Assign output pointer*/
+	*pvalue=outvalue;
+} /*}}}*/
+#endif
+template <> inline void GenericOption<IssmDouble*>::Get(IssmDouble** pvalue){ /*{{{*/
+
+	/*Copy vector*/
+	IssmDouble* outvalue=xNew<IssmDouble>(this->NumEl());
+	for(int i=0;i<this->NumEl();i++) outvalue[i]=this->value[i];
+
+	/*Assign output pointer*/
+	*pvalue=outvalue;
+} /*}}}*/
+template <> inline void GenericOption<char*>::Get(char** pvalue){ /*{{{*/
+
+	char* outstring=NULL;
+	int   stringsize;
+
+	stringsize=strlen(this->value)+1;
+	outstring=xNew<char>(stringsize);
+	xMemCpy<char>(outstring,this->value,stringsize);
+
+	*pvalue=outstring;
+} 
+/*}}}*/
+
+#endif  /* _OPTIONOBJECT_H */
Index: /issm/trunk/src/c/classes/objects/Options/Option.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Options/Option.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Options/Option.h	(revision 13395)
@@ -0,0 +1,43 @@
+/*! \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:
+
+		
+		/*Option constructors, destructors {{{*/
+		Option(){};
+		~Option(){};
+		/*}}}*/
+		/*Object virtual functions definitions:{{{*/
+		virtual void  Echo()= 0;
+		virtual void  DeepEcho()= 0;
+		virtual void  DeepEcho(char  *indent)=0;
+		int           Id(){_error_("Not implemented yet"); };
+		int           MyRank(){_error_("Not implemented yet"); };
+		int           ObjectEnum(){return OptionEnum;              };
+		Object       *copy(){_error_("Not implemented yet"); };
+		/*}}}*/
+
+		/*virtual functions: */
+		virtual char* Name()=0;
+		virtual int   NumEl()=0;
+		virtual int   NDims()=0;
+		virtual int*  Size()=0;
+
+};
+#endif  /* _OPTIONOBJECT_H */
+
Index: /issm/trunk/src/c/classes/objects/Options/OptionUtilities.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Options/OptionUtilities.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Options/OptionUtilities.cpp	(revision 13395)
@@ -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) _error_("Index " << index << " exceeds number of elements " << aprod << ".");
+
+	/*calculate the dimensions (being careful of integer division)  */
+	for (i=ndims-1; i>=0; i--) {
+		aprod=reCast<int>(((IssmPDouble)aprod+0.5)/(IssmPDouble)size[i]);
+		dims[i]=(int)floor(((IssmPDouble)index+0.5)/(IssmPDouble)aprod);
+		index-=dims[i]*aprod;
+	}
+
+	return(0);
+}/*}}}*/
+/*FUNCTION IndexFromColumnWiseDims{{{*/
+int IndexFromColumnWiseDims(int* dims, int* size, int ndims) {
+
+	int   i;
+	int   index=0;
+
+	/*check for any dimension too large  */
+	for (i=0;i<ndims;i++){
+		if (dims[i] >= size[i]) _error_("Dimension " << i << " of " << dims[i] << " exceeds size of " << size[i] << ".");
+	}
+
+	/*calculate the index  */
+	for (i=ndims-1; i>=0; i--){
+		index*=size[i];
+		index+=dims[i];
+	}
+
+	return(index);
+}/*}}}*/
+/*FUNCTION RowWiseDimsFromIndex{{{*/
+int RowWiseDimsFromIndex(int* dims, int index, int* size, int ndims) {
+
+	int   i;
+	int   aprod=1;
+
+	/*check for index too large  */
+	for (i=0; i<ndims; i++) aprod*=size[i];
+	if (index >= aprod) _error_("Index " << index << " exceeds number of elements " << aprod << ".");
+
+	/*calculate the dimensions (being careful of integer division)  */
+	for (i=0; i<ndims; i++) {
+		aprod=(int)(((IssmPDouble)aprod+0.5)/(IssmPDouble)size[i]);
+		dims[i]=(int)floor(((IssmPDouble)index+0.5)/(IssmPDouble)aprod);
+		index-=dims[i]*aprod;
+	}
+
+	return(0);
+}/*}}}*/
+/*FUNCTION IndexFromRowWiseDims{{{*/
+int IndexFromRowWiseDims(int* dims, int* size, int ndims) {
+
+	int   i;
+	int   index=0;
+
+	/*check for any dimension too large  */
+	for (i=0; i<ndims; i++){
+		if (dims[i] >= size[i]) _error_("Dimension " << i << " of " << dims[i] << " exceeds size of " << size[i] << ".");
+	}
+
+	/*calculate the index  */
+	for (i=0; i<ndims; i++) {
+		index*=size[i];
+		index+=dims[i];
+	}
+
+	return(index);
+}/*}}}*/
+/*FUNCTION StringFromDims{{{*/
+int StringFromDims(char* cstr, int* dims, int ndims) {
+
+	sprintf(&cstr[0],"[");
+	for(int i=0; i<ndims-1; i++) sprintf(&cstr[strlen(cstr)],"%d,",dims[i]);
+	sprintf(&cstr[strlen(cstr)],"%d]",dims[ndims-1]);
+
+	return(0);
+}/*}}}*/
+/*FUNCTION StringFromSize{{{*/
+int StringFromSize(char* cstr, int* size, int ndims) {
+
+	sprintf(&cstr[0],"[");
+	for(int i=0; i<ndims-1; i++) sprintf(&cstr[strlen(cstr)],"%dx",size[i]);
+	sprintf(&cstr[strlen(cstr)],"%d]",size[ndims-1]);
+
+	return(0);
+}/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Options/OptionUtilities.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Options/OptionUtilities.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Options/OptionUtilities.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Params/BoolParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/BoolParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/BoolParam.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Params/BoolParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/BoolParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/BoolParam.h	(revision 13395)
@@ -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){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){this->value=boolean;}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an int");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an IssmPDouble");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+		
+		void GetParameterName(char**pname);
+		/*}}}*/
+};
+#endif  /* _BOOLPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.h	(revision 13395)
@@ -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){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << "cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << "cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << "cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims);
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a int mat array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array);
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _DOUBLEMATARRAYPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/DoubleMatParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleMatParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleMatParam.cpp	(revision 13395)
@@ -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){
+	_error_("DoubleMat of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of int");
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::GetParameterName{{{*/
+void DoubleMatParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::SetValue{{{*/
+void  DoubleMatParam::SetValue(IssmDouble* IssmDoublearray,int in_M,int in_N){
+
+	/*avoid leak: */
+	xDelete<IssmDouble>(this->value);
+
+	this->value=xNew<IssmDouble>(in_M*in_N);
+	xMemCpy<IssmDouble>(this->value,IssmDoublearray,in_M*in_N);
+
+	this->M=in_M;
+	this->N=in_N;
+}
+/*}}}*/
+/*FUNCTION DoubleMatParam::UnitConversion{{{*/
+void  DoubleMatParam::UnitConversion(int direction_enum){
+	::UnitConversion(this->value,this->M*this->N,direction_enum,this->enum_type);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Params/DoubleMatParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleMatParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleMatParam.h	(revision 13395)
@@ -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){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N);
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _DOUBLEMATPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/DoubleParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleParam.cpp	(revision 13395)
@@ -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){
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an integer");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(bool* pbool){{{*/
+void DoubleParam::GetParameterValue(bool* pbool){
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an bool");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(int** pintarray,int* pM){{{*/
+void DoubleParam::GetParameterValue(int** pintarray,int* pM){
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of integers");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(int** pintarray,int* pM,int* pN){{{*/
+void DoubleParam::GetParameterValue(int** pintarray,int* pM,int* pN){
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of integers");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){{{*/
+void DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){{{*/
+void DoubleParam::GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){
+	_error_("Double param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of IssmDouble");
+}
+/*}}}*/
+/*FUNCTION DoubleParam::UnitConversion{{{*/
+void  DoubleParam::UnitConversion(int direction_enum){
+	::UnitConversion(&this->value,1,direction_enum,this->enum_type);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Params/DoubleParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleParam.h	(revision 13395)
@@ -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){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM);
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN);
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){this->value=(IssmDouble)boolean;}
+		void  SetValue(int integer){this->value=(IssmDouble)integer;}
+		void  SetValue(IssmDouble scalar){this->value=(IssmDouble)scalar;}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _DOUBLEPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/DoubleTransientMatParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleTransientMatParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleTransientMatParam.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Params/DoubleTransientMatParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleTransientMatParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleTransientMatParam.h	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Params/DoubleVecParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleVecParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleVecParam.cpp	(revision 13395)
@@ -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){
+	_error_("DoubleVec param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return an array of int");
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::GetParameterName{{{*/
+void DoubleVecParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::SetValue{{{*/
+void  DoubleVecParam::SetValue(IssmDouble* IssmDoublearray,int in_M){
+
+	/*avoid leak: */
+	xDelete<IssmDouble>(this->values);
+
+	this->values=xNew<IssmDouble>(in_M);
+	xMemCpy<IssmDouble>(this->values,IssmDoublearray,in_M);
+
+	this->M=in_M;
+}
+/*}}}*/
+/*FUNCTION DoubleVecParam::UnitConversion{{{*/
+void  DoubleVecParam::UnitConversion(int direction_enum){
+	::UnitConversion(this->values,this->M,direction_enum,this->enum_type);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Params/DoubleVecParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleVecParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleVecParam.h	(revision 13395)
@@ -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){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM);
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");};
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM);
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN);
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M);
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+		
+		void GetParameterName(char**pname);
+		/*}}}*/
+};
+#endif  /* _DOUBLEVECPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/FileParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/FileParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/FileParam.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Params/FileParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/FileParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/FileParam.h	(revision 13395)
@@ -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){  _error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){*pfid=value;};
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("File param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/GenericParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/GenericParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/GenericParam.h	(revision 13395)
@@ -0,0 +1,102 @@
+/*
+ * GenericParam.h
+ *
+ *  Created on: Aug 29, 2012
+ *      Author: utke
+ */
+
+#ifndef GENERICPARAM_H_
+#define GENERICPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+        #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+/*}}}*/
+
+/**
+ * here we have a class that holds an instance of P
+ * but because it should live side by side with
+ * the other instances derived from Param it - unfortunately -
+ * inherits all the accessors that are useless in this context
+ */
+template <class P> class GenericParam: public Param{
+
+        private:
+                P myP;
+                int myEnumVal;
+
+        public:
+                /*GenericParam constructors, destructors: {{{*/
+                GenericParam(int enumVal) : myEnumVal(enumVal){};
+                ~GenericParam(){};
+                /*}}}*/
+                /*Object virtual functions definitions:{{{ */
+                // unfortunately,  having to implement such a printer method implies
+                // that any structured P must provide the friend << operator
+                void  DeepEcho() {
+                  _printLine_("GenericParam:");
+                  _printLine_("   enum:  " << myEnumVal << " (" << EnumToStringx(myEnumVal) << ")");
+                  _printLine_("   value: " << myP);;
+                }
+                void  Echo() {DeepEcho();};
+                int   Id(){ return -1; };
+                int   MyRank() { extern int my_rank; return my_rank;} ;
+                int   ObjectEnum() {return AdolcParamEnum;};
+
+                // the "copy"  has to implement the base class abstract function
+                // but I would prefer to drop this not to hide a "new" in here because
+                // it does not clarify  ownership of the newed up instance...
+                // use the default copy constructor instead
+                Object* copy() { return new GenericParam<P>(*this); };
+                /*}}}*/
+                /*Param vritual function definitions: {{{*/
+                int   InstanceEnum(){return myEnumVal;}
+                void GetParameterName(char**pname) {EnumToStringx(pname,this->myEnumVal);}
+
+                P& GetParameterValue() { return myP;}
+                const P& GetParameterValue()const { return myP;};
+
+                // none of these apply ...
+                void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a bool");}
+                void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return an integer");}
+                void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return an array of integers");}
+                void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return an array of integers");}
+                void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a IssmDouble");}
+                void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a IssmDouble for a given time");}
+                void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a string");}
+                void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a string array");}
+                void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a IssmDouble array");}
+                void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a IssmDouble array");}
+                void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a matrix array");}
+                void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a Vec");}
+                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a Mat");}
+                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a FILE");}
+
+                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a bool");}
+                void  SetValue(int integer){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an integer");}
+                void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an int array");}
+                void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an int array");}
+                void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an IssmDouble");}
+                void  SetValue(char* string){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a string");}
+                void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a string array");}
+                void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a IssmDouble array");}
+                void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a IssmDouble array");}
+                void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a Vec");}
+                void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a Mat");}
+                void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a FILE");}
+                void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold an array of matrices");}
+                void  UnitConversion(int direction_enum) {/* nothing useful here either */};
+
+                /*}}}*/
+};
+
+
+#endif /* GENERICPARAM_H_ */
Index: /issm/trunk/src/c/classes/objects/Params/IntMatParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/IntMatParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/IntMatParam.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Params/IntMatParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/IntMatParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/IntMatParam.h	(revision 13395)
@@ -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){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN);
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");};
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");};
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int vec array");};
+		void  SetValue(int* intarray,int M,int N);
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _INTMATPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/IntParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/IntParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/IntParam.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Params/IntParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/IntParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/IntParam.h	(revision 13395)
@@ -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){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){*pinteger=value;}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a bool");}
+		void  SetValue(int integer){this->value=integer;}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an int array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an int array");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an IssmDouble");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/IntVecParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/IntVecParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/IntVecParam.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Params/IntVecParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/IntVecParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/IntVecParam.h	(revision 13395)
@@ -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){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM);
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array (maybe in serial?)");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble mat array");}
+		void  SetValue(int* intarray,int M);
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int mat array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+		
+		void GetParameterName(char**pname);
+		/*}}}*/
+};
+#endif
Index: /issm/trunk/src/c/classes/objects/Params/MatrixParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/MatrixParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/MatrixParam.cpp	(revision 13395)
@@ -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<IssmDouble>* value){{{*/
+MatrixParam::MatrixParam(int in_enum_type,Matrix<IssmDouble>* in_value){
+
+	enum_type=in_enum_type;
+	value=NULL;
+
+	if(in_value){
+		value=in_value->Duplicate();
+	}
+}
+/*}}}*/
+/*FUNCTION MatrixParam::~MatrixParam(){{{*/
+MatrixParam::~MatrixParam(){
+	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<IssmDouble>** poutput){
+	Matrix<IssmDouble>* output=NULL;
+
+	if(value){
+		output=value->Duplicate();
+	}
+	*poutput=output;
+}
+/*}}}*/
+/*FUNCTION MatrixParam::GetParameterName{{{*/
+void MatrixParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION MatrixParam::SetValue{{{*/
+void  MatrixParam::SetValue(Matrix<IssmDouble>* matrix){
+	
+	/*avoid leak: */
+	xdelete(&value);
+	
+	/*copy: */
+	value=matrix->Duplicate();
+}
+/*}}}*/
+/*FUNCTION MatrixParam::UnitConversion{{{*/
+void  MatrixParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Params/MatrixParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/MatrixParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/MatrixParam.h	(revision 13395)
@@ -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<IssmDouble>* value;
+
+	public:
+		/*MatrixParam constructors, destructors: {{{*/
+		MatrixParam();
+		MatrixParam(int enum_type,Matrix<IssmDouble>* value);
+		~MatrixParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** poutput);
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat);
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _MATRIXPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/Param.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/Param.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/Param.h	(revision 13395)
@@ -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<IssmDouble>** pvec)=0;
+		virtual void  GetParameterValue(Matrix<IssmDouble>** 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<IssmDouble>* vec)=0;
+		virtual void  SetValue(Matrix<IssmDouble>* mat)=0;
+		virtual void  SetValue(FILE* fid)=0;
+		virtual void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array)=0;
+		virtual void  UnitConversion(int direction_enum)=0;
+		virtual void  GetParameterName(char**pname)=0;
+};
+#endif
Index: /issm/trunk/src/c/classes/objects/Params/StringArrayParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/StringArrayParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/StringArrayParam.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Params/StringArrayParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/StringArrayParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/StringArrayParam.h	(revision 13395)
@@ -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){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM);
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Vec param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M);
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+		/*}}}*/
+};
+#endif  /* _STRINGARRAYPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/StringParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/StringParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/StringParam.cpp	(revision 13395)
@@ -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/trunk/src/c/classes/objects/Params/StringParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/StringParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/StringParam.h	(revision 13395)
@@ -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){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring);
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string);
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _STRINGPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/TransientParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/TransientParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/TransientParam.cpp	(revision 13395)
@@ -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){
+
+	IssmDouble output;
+	bool   found;
+
+	/*Ok, we have the time, go through the timesteps, and figure out which interval we 
+	 *fall within. Then interpolate the values on this interval: */
+	if(time<this->timesteps[0]){
+		/*get values for the first time: */
+		output=this->values[0];
+		found=true;
+	}
+	else if(time>this->timesteps[this->N-1]){
+		/*get values for the last time: */
+		output=this->values[this->N-1];
+		found=true;
+	}
+	else{
+		/*Find which interval we fall within: */
+		for(int i=0;i<this->N;i++){
+			if(time==this->timesteps[i]){
+				/*We are right on one step time: */
+				output=this->values[i];
+				found=true;
+				break; //we are done with the time interpolation.
+			}
+			else{
+				if(this->timesteps[i]<time && time<this->timesteps[i+1]){
+					/*ok, we have the interval ]i:i+1[. Interpolate linearly for now: */
+					IssmDouble deltat=this->timesteps[i+1]-this->timesteps[i];
+					IssmDouble alpha=(time-this->timesteps[i])/deltat;
+					output=(1.0-alpha)*this->values[i] + alpha*this->values[i+1];
+					found=true;
+					break;
+				}
+				else continue; //keep looking on the next interval
+			}
+		}
+	}
+	if(!found)_error_("did not find time interval on which to interpolate values");
+	*pdouble=output;
+}
+/*}}}*/
+/*FUNCTION TransientParam::GetParameterName{{{*/
+void TransientParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION TransientParam::UnitConversion{{{*/
+void  TransientParam::UnitConversion(int direction_enum){
+	::UnitConversion(this->values,this->N,direction_enum,this->enum_type);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Params/TransientParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/TransientParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/TransientParam.h	(revision 13395)
@@ -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){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time);
+		void  GetParameterValue(char** pstring){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM,int* pN){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(FILE** pfid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble vec array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M,int N){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int vec array");}
+		void  SetValue(int* intarray,int M,int N){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a int mat array");};
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _TRANSIENTPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/VectorParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/VectorParam.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/VectorParam.cpp	(revision 13395)
@@ -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<IssmDouble>* in_value){
+
+	enum_type=in_enum_type;
+
+	value=NULL;
+
+	if(in_value){
+		value=in_value->Duplicate();
+		in_value->Copy(value);
+	}
+}
+/*}}}*/
+/*FUNCTION VectorParam::~VectorParam(){{{*/
+VectorParam::~VectorParam(){
+	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<IssmDouble>** poutput){
+	Vector<IssmDouble>*  output=NULL;
+
+	if(value){
+		output=value->Duplicate();
+		value->Copy(output);
+	}
+	*poutput=output;
+}
+/*}}}*/
+/*FUNCTION VectorParam::GetParameterName{{{*/
+void VectorParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION VectorParam::SetValue{{{*/
+void  VectorParam::SetValue(Vector<IssmDouble>* vector){
+
+	/*avoid leak: */
+	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/trunk/src/c/classes/objects/Params/VectorParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/VectorParam.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Params/VectorParam.h	(revision 13395)
@@ -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<IssmDouble>* value;
+
+	public:
+		/*VectorParam constructors, destructors: {{{*/
+		VectorParam();
+		VectorParam(int enum_type,Vector<IssmDouble>* value);
+		~VectorParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   MyRank();
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an integer");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return an array of integers");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a matrix array");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(Vector<IssmDouble>** poutput);
+		void  GetParameterValue(FILE** pfid){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
+
+		void  SetValue(bool boolean){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a boolean");}
+		void  SetValue(int integer){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an integer");}
+		void  SetValue(IssmDouble scalar){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a scalar");}
+		void  SetValue(char* string){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a string");}
+		void  SetValue(char** stringarray,int M){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec);
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a Mat");}
+		void  SetValue(FILE* fid){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a FILE");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _VECTORPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Segment.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Segment.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Segment.h	(revision 13395)
@@ -0,0 +1,93 @@
+/*!\file Segment.h
+ * \brief: header file for node object
+ */
+
+#ifndef _SEGMENT_H_
+#define _SEGMENT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Object.h"
+/*}}}*/
+
+template <class doubletype> 
+class Segment: public Object{
+
+	public:
+		int eid;
+		doubletype x1;
+		doubletype y1;
+		doubletype x2;
+		doubletype y2;
+
+
+		/*Segment constructors, destructors :*/
+		/*FUNCTION Segment() default constructor {{{*/
+		Segment(){
+			this->eid=UNDEF;
+			this->x1=UNDEF;
+			this->y1=UNDEF;
+			this->x2=UNDEF;
+			this->y2=UNDEF;
+		}
+		/*}}}*/
+		/*FUNCTION Segment(int eid, doubletype x1,doubletype y1,doubletype x2, doubletype y2){{{*/
+		Segment(int segment_eid, doubletype segment_x1,doubletype segment_y1,doubletype segment_x2, doubletype segment_y2){
+
+			this->eid=segment_eid;
+			this->x1=segment_x1;
+			this->y1=segment_y1;
+			this->x2=segment_x2;
+			this->y2=segment_y2;
+
+		}
+		/*}}}*/
+		/*FUNCTION ~Segment(){{{*/
+		~Segment(){
+		}
+		/*}}}*/
+
+		/*Object virtual functions definitions:*/
+		/*FUNCTION Echo{{{*/
+		void Echo(void){
+
+			_printLine_("Segment:");
+			_printLine_("   eid: " << eid);
+			_printLine_("   node 1: " << this->x1 << "|" << this->y1);
+			_printLine_("   node 2: " << this->x2 << "|" << this->y2);
+
+		}
+		/*}}}*/
+		/*FUNCTION DeepEcho{{{*/
+		void DeepEcho(void){
+			this->Echo();
+		}
+		/*}}}*/
+		/*FUNCTION Id{{{*/
+		int    Id(void){ return eid; }
+		/*}}}*/
+		/*FUNCTION MyRank{{{*/
+		int    MyRank(void){ 
+			extern int my_rank;
+
+			return my_rank; 
+		}
+		/*}}}*/
+		/*FUNCTION ObjectEnum{{{*/
+		int ObjectEnum(void){
+
+			return SegmentEnum;
+
+		}
+		/*}}}*/
+		/*FUNCTION copy {{{*/
+		Object* copy() {
+			return new Segment(this->eid,this->x1,this->y1,this->x2,this->y2);
+
+		}
+
+		/*}}}*/
+
+};
+
+#endif  /* _SEGMENT_H_ */
Index: /issm/trunk/src/c/classes/objects/Vertex.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Vertex.cpp	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Vertex.cpp	(revision 13395)
@@ -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<IssmDouble>* vz,Parameters* parameters,IssmDouble* thickness,IssmDouble* bed){
+
+	IssmDouble oldz,newz;
+	IssmDouble dt,velz;
+
+	/*Get time stepping*/
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+
+	/*sigma remains constant. z=bed+sigma*thickness*/
+	oldz = this->z;
+	newz = bed[this->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/trunk/src/c/classes/objects/Vertex.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Vertex.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/Vertex.h	(revision 13395)
@@ -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;
+template <class doubletype> 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<IssmDouble>* vz,Parameters* parameters,IssmDouble* thickness,IssmDouble* bed);
+		/*}}}*/
+};
+#endif  /* _VERTEX_H */
Index: /issm/trunk/src/c/classes/objects/objects.h
===================================================================
--- /issm/trunk/src/c/classes/objects/objects.h	(revision 13395)
+++ /issm/trunk/src/c/classes/objects/objects.h	(revision 13395)
@@ -0,0 +1,122 @@
+/* \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/GenericOption.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/GenericExternalResult.h"
+
+/*Materials: */
+#include "./Materials/Material.h"
+#include "./Materials/Matice.h"
+#include "./Materials/Matdamageice.h"
+#include "./Materials/Matpar.h"
+
+/*Params: */
+#include "./Params/GenericParam.h"
+#include "./Params/BoolParam.h"
+#include "./Params/DoubleMatParam.h"
+#include "./Params/DoubleTransientMatParam.h"
+#include "./Params/DoubleMatArrayParam.h"
+#include "./Params/DoubleParam.h"
+#include "./Params/DoubleVecParam.h"
+#include "./Params/IntParam.h"
+#include "./Params/IntVecParam.h"
+#include "./Params/IntMatParam.h"
+#include "./Params/FileParam.h"
+#include "./Params/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/trunk/src/c/include/macros.h
===================================================================
--- /issm/trunk/src/c/include/macros.h	(revision 13394)
+++ /issm/trunk/src/c/include/macros.h	(revision 13395)
@@ -23,23 +23,13 @@
 #define _printf_(flag,...) do{if(flag) PrintfFunction(__VA_ARGS__);}while(0)
 /*}}}*/
-/* _error_ {{{*/
-/*Error exception macro*/
-#ifdef _INTEL_WIN_
-#define _error_(...)\
-  throw ErrorException(exprintf(__VA_ARGS__))
-#else
-#define _error_(...)\
-  throw ErrorException(__FILE__,__func__,__LINE__,exprintf(__VA_ARGS__))
-#endif
-/*}}}*/
 /* _error2_ {{{*/
 /*new Error exception macro*/
 #ifdef _INTEL_WIN_
-#define _error2_(StreamArgs)\
+#define _error_(StreamArgs)\
    do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
    aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
    throw ErrorException(aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
 #else
-#define _error2_(StreamArgs)\
+#define _error_(StreamArgs)\
 	do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
    aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
@@ -53,10 +43,10 @@
 /*}}}*/
 /* _printString_ {{{*/
-/* macro to print some string, adds std::ends */
+/* macro to print some string */
 #define _printString_(StreamArgs)\
    do{std::cout << StreamArgs;}while(0)
 /*}}}*/
 /* _pprintLine_ {{{*/
-/* macro to print a line, adds std::endl */
+/* macro to print a line, adds std::endl, only on cpu 0 */
 #define _pprintLine_(StreamArgs)\
   do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
@@ -65,5 +55,5 @@
 /*}}}*/
 /* _pprintString_ {{{*/
-/* macro to print some string, adds std::ends */
+/* macro to print some string. Only on cpu0 */
 #define _pprintString_(StreamArgs)\
   do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
@@ -75,5 +65,5 @@
 #ifdef _ISSM_DEBUG_ 
 #define _assert_(statement)\
-  if (!(statement)) _error_("Assertion \"%s\" failed, please report bug to %s",#statement,PACKAGE_BUGREPORT)
+  if (!(statement)) _error_("Assertion \""<<#statement<<"\" failed, please report bug to "<<PACKAGE_BUGREPORT)
 #else
 #define _assert_(ignore)\
Index: /issm/trunk/src/c/io/Disk/diskio.h
===================================================================
--- /issm/trunk/src/c/io/Disk/diskio.h	(revision 13394)
+++ /issm/trunk/src/c/io/Disk/diskio.h	(revision 13395)
@@ -6,7 +6,5 @@
 #define _DISK_IO_H_
 
-#include "../../objects/objects.h"
-#include "../../Container/Container.h"
-#include "../../include/include.h"
+#include <stdio.h>
 
 FILE* pfopen(char* filename,const char* format);
Index: /issm/trunk/src/c/io/Disk/pfclose.cpp
===================================================================
--- /issm/trunk/src/c/io/Disk/pfclose.cpp	(revision 13394)
+++ /issm/trunk/src/c/io/Disk/pfclose.cpp	(revision 13395)
@@ -18,4 +18,4 @@
 	extern int my_rank;
 	_assert_(fid);
-	if(fclose(fid)!=0)_error2_("could not close file " << filename);
+	if(fclose(fid)!=0)_error_("could not close file " << filename);
 }
Index: /issm/trunk/src/c/io/Disk/pfopen.cpp
===================================================================
--- /issm/trunk/src/c/io/Disk/pfopen.cpp	(revision 13394)
+++ /issm/trunk/src/c/io/Disk/pfopen.cpp	(revision 13395)
@@ -20,5 +20,5 @@
 	/*Open handle to data on disk: */
 	fid=fopen(filename,format);
-	if(fid==NULL) _error2_("could not open file " << filename << " for binary reading or writing"); 
+	if(fid==NULL) _error_("could not open file " << filename << " for binary reading or writing"); 
 
 	return fid;
Index: /issm/trunk/src/c/issm.h
===================================================================
--- /issm/trunk/src/c/issm.h	(revision 13394)
+++ /issm/trunk/src/c/issm.h	(revision 13395)
@@ -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"
Index: /issm/trunk/src/c/matlab/include/matlab_macros.h
===================================================================
--- /issm/trunk/src/c/matlab/include/matlab_macros.h	(revision 13394)
+++ /issm/trunk/src/c/matlab/include/matlab_macros.h	(revision 13395)
@@ -19,11 +19,8 @@
 /*The following macros hide the error exception handling in a matlab module. Just put 
  * MODULEBOOT(); and MODULEEND(); at the beginning and end of a module, and c++ exceptions 
- * will be trapped. Really nifty!*/
-//exception.Report(); 
+ * will be trapped*/
+#define MODULEBOOT(); try{ 
 
-#define MODULEBOOT(); ModuleBoot(); \
-	try{
-
-#define MODULEEND(); ModuleEnd(); }\
+#define MODULEEND(); }\
 	catch(ErrorException &exception){\
 		mexErrMsgTxt("ISSM Error"); \
@@ -35,8 +32,7 @@
 		mexErrMsgTxt("An unexpected error occurred");\
 	}
-//}}}
+/*}}}*/
 /* WRAPPER {{{*/
 #define WRAPPER(modulename,...) void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) 
-
 /*}}}*/
 /* CHECKARGUMENTS {{{*/
Index: /issm/trunk/src/c/matlab/io/CheckNumMatlabArguments.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/CheckNumMatlabArguments.cpp	(revision 13394)
+++ /issm/trunk/src/c/matlab/io/CheckNumMatlabArguments.cpp	(revision 13395)
@@ -22,9 +22,9 @@
 		/* special case: */
 		function();
-		_error2_("usage: see above");
+		_error_("usage: see above");
 	}
 	else if (nlhs!=NLHS || nrhs!=NRHS ) {
 		function(); 
-		_error2_("usage error.");
+		_error_("usage error.");
 	}
 	return 1;
Index: /issm/trunk/src/c/matlab/io/FetchMatlabData.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/FetchMatlabData.cpp	(revision 13394)
+++ /issm/trunk/src/c/matlab/io/FetchMatlabData.cpp	(revision 13395)
@@ -48,5 +48,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 			
@@ -61,7 +61,148 @@
 void FetchData(double** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){
 
-	double*  outmatrix=NULL;
+	int     outmatrix_numel,outmatrix_ndims;
+	double *outmatrix       = NULL;
+	int    *outmatrix_size  = NULL;
+
+	if(mxIsEmpty(dataref) ){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		outmatrix_numel = 0;
+		outmatrix_ndims = 0;
+		outmatrix_size  = NULL;
+		outmatrix       = NULL;
+	}
+	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))) && (mxGetNumberOfElements(dataref)==1)){
+			outmatrix_numel = 0;
+			outmatrix_ndims = 0;
+			outmatrix_size  = NULL;
+			outmatrix       = NULL;
+		}
+		else{
+			if(!mxIsClass(dataref,"double") && !mxIsClass(dataref,"single")){
+				_printLine_("Warning: converting matlab data from '" << mxGetClassName(dataref) << "' to 'double'");
+			}
+			/*Convert matlab n-dim array to double* matrix: */
+			MatlabNArrayToNArray(&outmatrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
+		}
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+	}
+			
+	/*Assign output pointers:*/
+	*pmatrix=outmatrix;
+	if (pnumel)*pnumel=outmatrix_numel;
+	if (pndims)*pndims=outmatrix_ndims;
+	if (psize )*psize =outmatrix_size;
+	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){
+
+	int     i,outmatrix_rows,outmatrix_cols;
+	double *doublematrix=NULL;
+	int    *outmatrix=NULL;
+
+	if(mxIsEmpty(dataref) ){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		outmatrix_rows=0;
+		outmatrix_cols=0;
+		outmatrix=NULL;
+	}
+	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) ){
+			outmatrix_rows=0;
+			outmatrix_cols=0;
+			outmatrix=NULL;
+		}
+		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(&doublematrix,&outmatrix_rows,&outmatrix_cols,dataref);
+
+			/*Convert double matrix into integer matrix: */
+			outmatrix=xNew<int>(outmatrix_rows*outmatrix_cols);
+			for(i=0;i<outmatrix_rows*outmatrix_cols;i++)outmatrix[i]=(int)doublematrix[i];
+		}
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+	}
+
+	/*Assign output pointers:*/
+	*pmatrix=outmatrix;
+	if (pM)*pM=outmatrix_rows;
+	if (pN)*pN=outmatrix_cols;
+}
+/*}}}*/
+/*FUNCTION FetchData(bool** pmatrix,int* pM,int *pN,const mxArray* dataref){{{*/
+void FetchData(bool** pmatrix,int* pM,int *pN,const mxArray* dataref){
+
+	int     i,outmatrix_rows,outmatrix_cols;
+	double *doublematrix=NULL;
+	bool   *outmatrix=NULL;
+
+	if(mxIsEmpty(dataref) ){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		outmatrix_rows=0;
+		outmatrix_cols=0;
+		outmatrix=NULL;
+	}
+	else if (mxIsClass(dataref,"double") ){
+
+		/*Check dataref is not pointing to NaN: */
+		if ( mxIsNaN(*(mxGetPr(dataref))) && (mxGetM(dataref)==1) && (mxGetN(dataref)==1) ){
+			outmatrix_rows=0;
+			outmatrix_cols=0;
+			outmatrix=NULL;
+		}
+		else{
+
+			/*Convert matlab matrix to double* matrix: */
+			MatlabMatrixToDoubleMatrix(&doublematrix,&outmatrix_rows,&outmatrix_cols,dataref);
+
+			/*Convert double matrix into integer matrix: */
+			outmatrix=xNew<bool>(outmatrix_rows*outmatrix_cols);
+			for(i=0;i<outmatrix_rows;i++)outmatrix[i]=(bool)doublematrix[i];
+		}
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+	}
+
+	/*Assign output pointers:*/
+	*pmatrix=outmatrix;
+	if (pM)*pM=outmatrix_rows;
+	if (pN)*pN=outmatrix_cols;
+}
+/*}}}*/
+/*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){
+
+	int      i;
 	int      outmatrix_numel,outmatrix_ndims;
 	int*     outmatrix_size=NULL;
+	double*  doublematrix=NULL;
+	bool*    outmatrix=NULL;
 
 	if(mxIsEmpty(dataref) ){
@@ -71,4 +212,19 @@
 		outmatrix_size =NULL;
 		outmatrix=NULL;
+	}
+	else if (mxIsClass(dataref,"logical") ){
+
+		/*Check dataref is not pointing to NaN: */
+		if ( mxIsNaN(*((bool*)mxGetData(dataref))) && (mxGetNumberOfElements(dataref)==1) ){
+			outmatrix_numel=0;
+			outmatrix_ndims=0;
+			outmatrix_size =NULL;
+			outmatrix=NULL;
+		}
+		else{
+
+			/*Convert matlab n-dim array to bool* matrix: */
+			MatlabNArrayToNArray(&outmatrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
+		}
 	}
 	else if (mxIsClass(dataref,"double") ){
@@ -84,10 +240,15 @@
 
 			/*Convert matlab n-dim array to double* matrix: */
-			MatlabNArrayToNArray(&outmatrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
-		}
-	}
-	else{
-		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+			MatlabNArrayToNArray(&doublematrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
+
+			/*Convert double matrix into bool matrix: */
+			outmatrix=xNew<bool>(outmatrix_numel);
+			for(i=0;i<outmatrix_numel;i++)outmatrix[i]=(bool)doublematrix[i];
+			xDelete<double>(doublematrix);
+		}
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 			
@@ -101,153 +262,4 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(int** pmatrix,int* pM,int *pN,const mxArray* dataref){{{*/
-void FetchData(int** pmatrix,int* pM,int *pN,const mxArray* dataref){
-
-	int     i,outmatrix_rows,outmatrix_cols;
-	double *doublematrix=NULL;
-	int    *outmatrix=NULL;
-
-	if(mxIsEmpty(dataref) ){
-		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
-		outmatrix_rows=0;
-		outmatrix_cols=0;
-		outmatrix=NULL;
-	}
-	else if (mxIsClass(dataref,"double") ){
-
-		/*Check dataref is not pointing to NaN: */
-		if ( mxIsNaN(*(mxGetPr(dataref))) && (mxGetM(dataref)==1) && (mxGetN(dataref)==1) ){
-			outmatrix_rows=0;
-			outmatrix_cols=0;
-			outmatrix=NULL;
-		}
-		else{
-
-			/*Convert matlab matrix to double* matrix: */
-			MatlabMatrixToDoubleMatrix(&doublematrix,&outmatrix_rows,&outmatrix_cols,dataref);
-
-			/*Convert double matrix into integer matrix: */
-			outmatrix=xNew<int>(outmatrix_rows*outmatrix_cols);
-			for(i=0;i<outmatrix_rows*outmatrix_cols;i++)outmatrix[i]=(int)doublematrix[i];
-		}
-	}
-	else{
-		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
-	}
-
-	/*Assign output pointers:*/
-	*pmatrix=outmatrix;
-	if (pM)*pM=outmatrix_rows;
-	if (pN)*pN=outmatrix_cols;
-}
-/*}}}*/
-/*FUNCTION FetchData(bool** pmatrix,int* pM,int *pN,const mxArray* dataref){{{*/
-void FetchData(bool** pmatrix,int* pM,int *pN,const mxArray* dataref){
-
-	int     i,outmatrix_rows,outmatrix_cols;
-	double *doublematrix=NULL;
-	bool   *outmatrix=NULL;
-
-	if(mxIsEmpty(dataref) ){
-		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
-		outmatrix_rows=0;
-		outmatrix_cols=0;
-		outmatrix=NULL;
-	}
-	else if (mxIsClass(dataref,"double") ){
-
-		/*Check dataref is not pointing to NaN: */
-		if ( mxIsNaN(*(mxGetPr(dataref))) && (mxGetM(dataref)==1) && (mxGetN(dataref)==1) ){
-			outmatrix_rows=0;
-			outmatrix_cols=0;
-			outmatrix=NULL;
-		}
-		else{
-
-			/*Convert matlab matrix to double* matrix: */
-			MatlabMatrixToDoubleMatrix(&doublematrix,&outmatrix_rows,&outmatrix_cols,dataref);
-
-			/*Convert double matrix into integer matrix: */
-			outmatrix=xNew<bool>(outmatrix_rows*outmatrix_cols);
-			for(i=0;i<outmatrix_rows;i++)outmatrix[i]=(bool)doublematrix[i];
-		}
-	}
-	else{
-		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
-	}
-
-	/*Assign output pointers:*/
-	*pmatrix=outmatrix;
-	if (pM)*pM=outmatrix_rows;
-	if (pN)*pN=outmatrix_cols;
-}
-/*}}}*/
-/*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){
-
-	int      i;
-	int      outmatrix_numel,outmatrix_ndims;
-	int*     outmatrix_size=NULL;
-	double*  doublematrix=NULL;
-	bool*    outmatrix=NULL;
-
-	if(mxIsEmpty(dataref) ){
-		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
-		outmatrix_numel=0;
-		outmatrix_ndims=0;
-		outmatrix_size =NULL;
-		outmatrix=NULL;
-	}
-	else if (mxIsClass(dataref,"logical") ){
-
-		/*Check dataref is not pointing to NaN: */
-		if ( mxIsNaN(*((bool*)mxGetData(dataref))) && (mxGetNumberOfElements(dataref)==1) ){
-			outmatrix_numel=0;
-			outmatrix_ndims=0;
-			outmatrix_size =NULL;
-			outmatrix=NULL;
-		}
-		else{
-
-			/*Convert matlab n-dim array to bool* matrix: */
-			MatlabNArrayToNArray(&outmatrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
-		}
-	}
-	else if (mxIsClass(dataref,"double") ){
-
-		/*Check dataref is not pointing to NaN: */
-		if ( mxIsNaN(*(mxGetPr(dataref))) && (mxGetNumberOfElements(dataref)==1) ){
-			outmatrix_numel=0;
-			outmatrix_ndims=0;
-			outmatrix_size =NULL;
-			outmatrix=NULL;
-		}
-		else{
-
-			/*Convert matlab n-dim array to double* matrix: */
-			MatlabNArrayToNArray(&doublematrix,&outmatrix_numel,&outmatrix_ndims,&outmatrix_size,dataref);
-
-			/*Convert double matrix into bool matrix: */
-			outmatrix=xNew<bool>(outmatrix_numel);
-			for(i=0;i<outmatrix_numel;i++)outmatrix[i]=(bool)doublematrix[i];
-			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");
-	}
-			
-	/*Assign output pointers:*/
-	*pmatrix=outmatrix;
-	if (pnumel)*pnumel=outmatrix_numel;
-	if (pndims)*pndims=outmatrix_ndims;
-	if (psize )*psize =outmatrix_size;
-	else xDelete<int>(outmatrix_size);
-
-}
-/*}}}*/
 /*FUNCTION FetchData(double** pvector,int* pM,const mxArray* dataref){{{*/
 void FetchData(double** pvector,int* pM,const mxArray* dataref){
@@ -269,5 +281,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -301,5 +313,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -333,5 +345,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -365,5 +377,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -381,5 +393,5 @@
 	/*Ok, the string should be coming directly from the matlab workspace: */
 	if (!mxIsClass(dataref,"char")){
-		_error2_("input data_type is not a string!");
+		_error_("input data_type is not a string!");
 	}
 	else{
@@ -416,5 +428,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 			
@@ -434,5 +446,5 @@
 
 	if (!mxIsClass(dataref,"double")){
-		_error2_("input data_type is not a double!");
+		_error_("input data_type is not a double!");
 	}
 	else{
@@ -451,5 +463,5 @@
 
 	if (!mxIsClass(dataref,"double")){
-		_error2_("input data_type is not a scalar!");
+		_error_("input data_type is not a scalar!");
 	}
 	else{
@@ -468,10 +480,10 @@
 
 	if (mxIsClass(dataref,"logical")){
-		if(mxGetM(dataref)!=1) _error2_("input data is not of size 1x1");
-		if(mxGetN(dataref)!=1) _error2_("input data is not of size 1x1");
+		if(mxGetM(dataref)!=1) _error_("input data is not of size 1x1");
+		if(mxGetN(dataref)!=1) _error_("input data is not of size 1x1");
 		mxbool_ptr=mxGetLogicals(dataref);
 	}
 	else{
-		_error2_("input data_type is not a bool!");
+		_error_("input data_type is not a bool!");
 	}
 
@@ -481,8 +493,8 @@
 
 /*ISSM objects*/
-/*FUNCTION FetchData(Matrix** pmatrix,const mxArray* dataref){{{*/
-void FetchData(Matrix** pmatrix,const mxArray* dataref){
-
-	Matrix* outmatrix=NULL;
+/*FUNCTION FetchData(Matrix<double>** pmatrix,const mxArray* dataref){{{*/
+void FetchData(Matrix<double>** pmatrix,const mxArray* dataref){
+
+	Matrix<double>* outmatrix=NULL;
 	int dummy=0;
 
@@ -495,5 +507,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -502,13 +514,13 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(Vector** pvector,const mxArray* dataref){{{*/
-void FetchData(Vector** pvector,const mxArray* dataref){
-
-	Vector* vector=NULL;
+/*FUNCTION FetchData(Vector<double>** pvector,const mxArray* dataref){{{*/
+void FetchData(Vector<double>** pvector,const mxArray* dataref){
+
+	Vector<double>* vector=NULL;
 	int dummy;
 
 	if(mxIsEmpty(dataref)){
 		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
-		vector=new Vector(0);
+		vector=new Vector<double>(0);
 	}
 	else if (mxIsClass(dataref,"double") ){
@@ -519,5 +531,5 @@
 	else{
 		/*This is an error: we don't have the correct input!: */
-		_error2_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
 	}
 
@@ -609,5 +621,5 @@
 }
 /*}}}*/
-/*FUNCTION FetchData(Options** poptions,const mxArray* dataref){{{*/
+/*FUNCTION FetchData(Options** poptions,const mxArray** pdataref){{{*/
 void FetchData(Options** poptions,int istart, int nrhs,const mxArray** pdataref){
 
@@ -620,8 +632,8 @@
 	/*Fetch all options*/
 	for (int i=istart; i<nrhs; i=i+2){
-		if (!mxIsClass(pdataref[i],"char")) _error2_("Argument " << i+1 << " must be name of option");
+		if (!mxIsClass(pdataref[i],"char")) _error_("Argument " << i+1 << " must be name of option");
 
 		FetchData(&name,pdataref[i]);
-		if(i+1 == nrhs) _error2_("Argument " << i+2 << " must exist and be value of option \"" << name << "\".");
+		if(i+1 == nrhs) _error_("Argument " << i+2 << " must exist and be value of option \"" << name << "\".");
 
 		option=(Option*)OptionParse(name,&pdataref[i+1]);
@@ -634,2 +646,49 @@
 }
 /*}}}*/
+/*FUNCTION FetchData(DataSet** pcontours,const mxArray* dataref){{{*/
+void FetchData(DataSet** pcontours,const mxArray* dataref){
+
+	int              numcontours,index,test1,test2;
+	char            *contourname = NULL;
+	DataSet         *contours    = NULL;
+	Contour<double> *contouri    = NULL;
+
+	if (mxIsClass(dataref,"char")){
+		FetchData(&contourname,dataref);
+		contours=DomainOutlineRead<double>(contourname);
+	}
+	else if(mxIsClass(dataref,"struct")){
+
+		contours=new DataSet(0);
+		numcontours=mxGetNumberOfElements(dataref);
+
+		for(int i=0;i<numcontours;i++){
+
+			contouri=xNew<Contour<double> >(1);
+
+			index = mxGetFieldNumber(dataref,"nods");
+			if(index==-1) _error_("input structure does not have a 'nods' field");
+			FetchData(&contouri->nods,mxGetFieldByNumber(dataref,i,index));
+
+			index = mxGetFieldNumber(dataref,"x");
+			if(index==-1) _error_("input structure does not have a 'x' field");
+			FetchData(&contouri->x,&test1,&test2,mxGetFieldByNumber(dataref,i,index));
+			if(test1!=contouri->nods || test2!=1) _error_("field x should be of size ["<<contouri->nods<<" 1]");
+
+			index = mxGetFieldNumber(dataref,"y");
+			if(index==-1) _error_("input structure does not have a 'y' field");
+			FetchData(&contouri->y,&test1,&test2,mxGetFieldByNumber(dataref,i,index));
+			if(test1!=contouri->nods || test2!=1) _error_("field y should be of size ["<<contouri->nods<<" 1]");
+
+			contours->AddObject(contouri);
+		}
+	}
+	else{
+		_error_("Contour is neither a string nor a structure and cannot be loaded ("<<mxGetClassName(dataref)<<" not supported)");
+	}
+
+	/*clean-up and assign output pointer*/
+	xDelete<char>(contourname);
+	*pcontours=contours;
+}
+/*}}}*/
Index: /issm/trunk/src/c/matlab/io/MatlabMatrixToDoubleMatrix.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/MatlabMatrixToDoubleMatrix.cpp	(revision 13394)
+++ /issm/trunk/src/c/matlab/io/MatlabMatrixToDoubleMatrix.cpp	(revision 13395)
@@ -119,5 +119,5 @@
 	}
 	else{
-		_error2_("Matlab matrix type Not implemented yet");
+		_error_("Matlab matrix type Not implemented yet");
 	}
 
Index: /issm/trunk/src/c/matlab/io/MatlabMatrixToMatrix.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/MatlabMatrixToMatrix.cpp	(revision 13394)
+++ /issm/trunk/src/c/matlab/io/MatlabMatrixToMatrix.cpp	(revision 13395)
@@ -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"
@@ -22,16 +22,16 @@
 /*}}}*/
 
-Matrix* MatlabMatrixToMatrix(const mxArray* mxmatrix){
+Matrix<double>* MatlabMatrixToMatrix(const mxArray* mxmatrix){
 
 	int dummy;
-	Matrix* matrix=NULL;
+	Matrix<double>* matrix=NULL;
 
 	/*allocate matrix object: */
-	matrix=new Matrix();
+	matrix=new Matrix<double>();
 
 	#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/trunk/src/c/matlab/io/MatlabMatrixToPetscMat.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/MatlabMatrixToPetscMat.cpp	(revision 13395)
+++ /issm/trunk/src/c/matlab/io/MatlabMatrixToPetscMat.cpp	(revision 13395)
@@ -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/trunk/src/c/matlab/io/MatlabMatrixToPetscMatrix.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/MatlabMatrixToPetscMatrix.cpp	(revision 13394)
+++ 	(revision )
@@ -1,114 +1,0 @@
-/* \file MatlabMatrixToPetscMatrix.cpp
- * \brief: convert a sparse or dense matlab matrix to a serial Petsc matrix:
- */
-
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-#include "../../shared/shared.h"
-
-/*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
-
-/*Matlab includes: */
-#include "mex.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=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: /issm/trunk/src/c/matlab/io/MatlabMatrixToSeqMat.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/MatlabMatrixToSeqMat.cpp	(revision 13394)
+++ /issm/trunk/src/c/matlab/io/MatlabMatrixToSeqMat.cpp	(revision 13395)
@@ -19,9 +19,9 @@
 /*}}}*/
 
-SeqMat* MatlabMatrixToSeqMat(const mxArray* dataref){
+SeqMat<double>* MatlabMatrixToSeqMat(const mxArray* dataref){
 
-	SeqMat* output=NULL;
+	SeqMat<double>* output=NULL;
 
-	output=new SeqMat();
+	output=new SeqMat<double>();
 	MatlabMatrixToDoubleMatrix(&output->matrix,&output->M,&output->N,dataref);
 	return output;
Index: /issm/trunk/src/c/matlab/io/MatlabNArrayToNArray.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/MatlabNArrayToNArray.cpp	(revision 13394)
+++ /issm/trunk/src/c/matlab/io/MatlabNArrayToNArray.cpp	(revision 13395)
@@ -28,10 +28,8 @@
 
 	/*matlab indices: */
-	mwIndex*    ir=NULL;
-	mwIndex*    jc=NULL;
-	double* pr=NULL;
-	int     count;
-	int     nnz;
-	int     nz;
+	mwIndex *ir    = NULL;
+	mwIndex *jc    = NULL;
+	double  *pr    = NULL;
+	int      count;
 
 	/*get Matlab matrix information: */
@@ -46,15 +44,13 @@
 
 		/*Dealing with sparse matrix: recover size first: */
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-		nnz=mxGetNzmax(mxmatrix);
-		nz=(int)((double)nnz/(double)rows);
+		rows = mxGetM(mxmatrix);
+		cols = mxGetN(mxmatrix);
 
 		matrix=xNewZeroInit<double>(rows*cols);
 
 		/*Now, get ir,jc and pr: */
-		ir=mxGetIr(mxmatrix);
-		jc=mxGetJc(mxmatrix);
-		pr=mxGetPr(mxmatrix);
+		ir = mxGetIr(mxmatrix);
+		jc = mxGetJc(mxmatrix);
+		pr = mxGetPr(mxmatrix);
 
 		/*Now, start inserting data into double* matrix: */
@@ -79,16 +75,15 @@
 		for(i=0;i<numel;i++){
 			ColumnWiseDimsFromIndex(dims,i,size,ndims);
-			j=IndexFromRowWiseDims(dims,size,ndims);
-			*(matrix+j)=*(mxmatrix_ptr+i);
+			j = IndexFromRowWiseDims(dims,size,ndims);
+			matrix[j]=(double)mxmatrix_ptr[i];
 		}
 		xDelete<int>(dims);
-		
 	}
 
 	/*Assign output pointer: */
-	*pmatrix=matrix;
-	*pmatrix_numel=numel;
-	*pmatrix_ndims=ndims;
-	*pmatrix_size=size;
+	*pmatrix       = matrix;
+	*pmatrix_numel = numel;
+	*pmatrix_ndims = ndims;
+	*pmatrix_size  = size;
 
 	return 1;
@@ -108,16 +103,14 @@
 
 	/*matlab indices: */
-	mwIndex*    ir=NULL;
-	mwIndex*    jc=NULL;
-	bool*   pm=NULL;
-	int     count;
-	int     nnz;
-	int     nz;
+	mwIndex *ir    = NULL;
+	mwIndex *jc    = NULL;
+	bool    *pm    = NULL;
+	int      count;
 
 	/*get Matlab matrix information: */
-	numel=mxGetNumberOfElements(mxmatrix);
-	ndims=mxGetNumberOfDimensions(mxmatrix);
-	ipt  =mxGetDimensions(mxmatrix);
-	size =xNew<int>(ndims);
+	numel = mxGetNumberOfElements(mxmatrix);
+	ndims = mxGetNumberOfDimensions(mxmatrix);
+	ipt   = mxGetDimensions(mxmatrix);
+	size  = xNew<int>(ndims);
 	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
 
@@ -128,7 +121,4 @@
 		rows=mxGetM(mxmatrix);
 		cols=mxGetN(mxmatrix);
-		nnz=mxGetNzmax(mxmatrix);
-		nz=(int)((double)nnz/(double)rows);
-
 		matrix=xNewZeroInit<bool>(rows*cols);
 
@@ -142,9 +132,8 @@
 		for(i=0;i<cols;i++){
 			for(j=0;j<(jc[i+1]-jc[i]);j++){
-				*(matrix+rows*ir[count]+i)=pm[count];
+				matrix[rows*ir[count]+i]=pm[count];
 				count++;
 			}
 		}
-
 	}
 	else{
@@ -159,5 +148,5 @@
 			ColumnWiseDimsFromIndex(dims,i,size,ndims);
 			j=IndexFromRowWiseDims(dims,size,ndims);
-			*(matrix+j)=(bool)*(mxmatrix_ptr+i);
+			matrix[j]=(bool)mxmatrix_ptr[i];
 		}
 		xDelete<int>(dims);
@@ -165,8 +154,8 @@
 
 	/*Assign output pointer: */
-	*pmatrix=matrix;
-	*pmatrix_numel=numel;
-	*pmatrix_ndims=ndims;
-	*pmatrix_size=size;
+	*pmatrix       = matrix;
+	*pmatrix_numel = numel;
+	*pmatrix_ndims = ndims;
+	*pmatrix_size  = size;
 
 	return 1;
@@ -190,12 +179,10 @@
 	char    *pm    = NULL;
 	int      count;
-	int      nnz;
-	int      nz;
 
 	/*get Matlab matrix information: */
-	numel=mxGetNumberOfElements(mxmatrix);
-	ndims=mxGetNumberOfDimensions(mxmatrix);
-	ipt  =mxGetDimensions(mxmatrix);
-	size =xNew<int>(ndims);
+	numel = mxGetNumberOfElements(mxmatrix);
+	ndims = mxGetNumberOfDimensions(mxmatrix);
+	ipt   = mxGetDimensions(mxmatrix);
+	size  = xNew<int>(ndims);
 	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
 
@@ -204,15 +191,12 @@
 
 		/*Dealing with sparse matrix: recover size first: */
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-		nnz=mxGetNzmax(mxmatrix);
-		nz=(int)((double)nnz/(double)rows);
-
+		rows = mxGetM(mxmatrix);
+		cols = mxGetN(mxmatrix);
 		matrix=xNew<char>(rows*cols);
 
 		/*Now, get ir,jc and pm: */
-		ir=mxGetIr(mxmatrix);
-		jc=mxGetJc(mxmatrix);
-		pm=(char*)mxGetData(mxmatrix);
+		ir = mxGetIr(mxmatrix);
+		jc = mxGetJc(mxmatrix);
+		pm = (char*)mxGetData(mxmatrix);
 
 		/*Now, start inserting data into char* matrix: */
@@ -220,12 +204,10 @@
 		for(i=0;i<cols;i++){
 			for(j=0;j<(jc[i+1]-jc[i]);j++){
-				*(matrix+rows*ir[count]+i)=(char)pm[count];
+				matrix[rows*ir[count]+i]=(char)pm[count];
 				count++;
 			}
 		}
-
 	}
 	else{
-
 		/*Dealing with dense matrix: recover pointer and size: */
 		mxmatrix_ptr=mxGetChars(mxmatrix);
@@ -261,8 +243,8 @@
 
 	/*Assign output pointer: */
-	*pmatrix=matrix;
-	*pmatrix_numel=numel;
-	*pmatrix_ndims=ndims;
-	*pmatrix_size=size;
+	*pmatrix       = matrix;
+	*pmatrix_numel = numel;
+	*pmatrix_ndims = ndims;
+	*pmatrix_size  = size;
 
 	return 1;
Index: /issm/trunk/src/c/matlab/io/MatlabVectorToDoubleVector.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/MatlabVectorToDoubleVector.cpp	(revision 13394)
+++ /issm/trunk/src/c/matlab/io/MatlabVectorToDoubleVector.cpp	(revision 13395)
@@ -46,5 +46,5 @@
 		
 		/*Check that input is actualy a vector*/
-		if (cols!=1) _error2_("input vector of size " << rows << "x" << cols << " should have only one column");
+		if (cols!=1) _error_("input vector of size " << rows << "x" << cols << " should have only one column");
 
 		nz=(int)((double)nnz/(double)rows);
@@ -77,5 +77,5 @@
 
 		/*Check that input is actualy a vector*/
-		if (cols!=1) _error2_("input vector of size " << rows << "x" << cols << " should have only one column");
+		if (cols!=1) _error_("input vector of size " << rows << "x" << cols << " should have only one column");
 
 		/*allocate and memcpy*/
Index: /issm/trunk/src/c/matlab/io/MatlabVectorToPetscVec.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/MatlabVectorToPetscVec.cpp	(revision 13395)
+++ /issm/trunk/src/c/matlab/io/MatlabVectorToPetscVec.cpp	(revision 13395)
@@ -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/trunk/src/c/matlab/io/MatlabVectorToPetscVector.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/MatlabVectorToPetscVector.cpp	(revision 13394)
+++ 	(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=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: /issm/trunk/src/c/matlab/io/MatlabVectorToSeqVec.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/MatlabVectorToSeqVec.cpp	(revision 13394)
+++ /issm/trunk/src/c/matlab/io/MatlabVectorToSeqVec.cpp	(revision 13395)
@@ -19,9 +19,9 @@
 /*}}}*/
 
-SeqVec* MatlabVectorToSeqVec(const mxArray* dataref){
+SeqVec<double>* MatlabVectorToSeqVec(const mxArray* dataref){
 
-	SeqVec* output=NULL;
+	SeqVec<double>* output=NULL;
 
-	output=new SeqVec();
+	output=new SeqVec<double>();
 	MatlabVectorToDoubleVector(&output->vector,&output->M,dataref);
 	return output;
Index: /issm/trunk/src/c/matlab/io/MatlabVectorToVector.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/MatlabVectorToVector.cpp	(revision 13394)
+++ /issm/trunk/src/c/matlab/io/MatlabVectorToVector.cpp	(revision 13395)
@@ -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"
@@ -22,16 +22,16 @@
 /*}}}*/
 
-Vector* MatlabVectorToVector(const mxArray* mxvector){
+Vector<double>* MatlabVectorToVector(const mxArray* mxvector){
 
 	int dummy;
-	Vector* vector=NULL;
+	Vector<double>* vector=NULL;
 
 	/*allocate vector object: */
-	vector=new Vector();
+	vector=new Vector<double>();
 
 	#ifdef _HAVE_PETSC_
-	MatlabVectorToPetscVector(&vector->vector,&dummy,mxvector);
+	vector->pvector=MatlabVectorToPetscVec(mxvector);
 	#else
-	vector->vector=MatlabVectorToSeqVec(mxvector);
+	vector->svector=MatlabVectorToSeqVec(mxvector);
 	#endif
 	
Index: /issm/trunk/src/c/matlab/io/OptionParse.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/OptionParse.cpp	(revision 13394)
+++ /issm/trunk/src/c/matlab/io/OptionParse.cpp	(revision 13395)
@@ -15,29 +15,42 @@
 #include "./matlabio.h"
 
-/*FUNCTION OptionDoubleParse {{{*/
-OptionDouble* OptionDoubleParse( char* name, const mxArray* prhs[]){
-
-	OptionDouble *odouble = NULL;
-
-	/*check and parse the name  */
-	odouble=new OptionDouble;
+GenericOption<double>* OptionDoubleParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<double> *odouble = NULL;
+
+	/*check and parse the name  */
+	odouble=new GenericOption<double>();
 	odouble->name =xNew<char>(strlen(name)+1);
 	memcpy(odouble->name,name,(strlen(name)+1)*sizeof(char));
+	FetchData(&odouble->value,prhs[0]);
+	odouble->numel=1;
+	odouble->ndims=1;
+	odouble->size=NULL;
+
+	return(odouble);
+}/*}}}*/
+GenericOption<double*>* OptionDoubleArrayParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<double*> *odouble = NULL;
+
+	/*check and parse the name  */
+	odouble=new GenericOption<double*>();
+	odouble->name =xNew<char>(strlen(name)+1);
+	memcpy(odouble->name,name,(strlen(name)+1)*sizeof(char));
 
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"double")){
-		_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]);
+		_error_("Value of option \"" << odouble->name  << "\" must be class \"double\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	FetchData(&odouble->value,&odouble->numel,&odouble->ndims,&odouble->size,prhs[0]);
 
 	return(odouble);
 }/*}}}*/
-/*FUNCTION OptionLogicalParse {{{*/
-OptionLogical* OptionLogicalParse( char* name, const mxArray* prhs[]){
-
-	OptionLogical *ological = NULL;
-
-	/*check and parse the name  */
-	ological=new OptionLogical;
+GenericOption<bool*>* OptionLogicalParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<bool*> *ological = NULL;
+
+	/*check and parse the name  */
+	ological=new GenericOption<bool*>();
 	ological->name =xNew<char>(strlen(name)+1);
 	memcpy(ological->name,name,(strlen(name)+1)*sizeof(char));
@@ -45,17 +58,16 @@
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"logical")){
-		_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]);
+		_error_("Value of option \"" << ological->name  << "\" must be class \"logical\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	FetchData(&ological->value,&ological->numel,&ological->ndims,&ological->size,prhs[0]);
 
 	return(ological);
 }/*}}}*/
-/*FUNCTION OptionCharParse {{{*/
-OptionChar* OptionCharParse( char* name, const mxArray* prhs[]){
-
-	OptionChar  *ochar = NULL;
-
-	/*check and parse the name  */
-	ochar=new OptionChar();
+GenericOption<char*>* OptionCharParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<char*>  *ochar = NULL;
+
+	/*check and parse the name  */
+	ochar=new GenericOption<char*>();
 	ochar->name =xNew<char>(strlen(name)+1);
 	memcpy(ochar->name,name,(strlen(name)+1)*sizeof(char));
@@ -63,17 +75,16 @@
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"char")){
-		_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]);
+		_error_("Value of option \"" << ochar->name  << "\" must be class \"char\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	FetchData(&ochar->value,&ochar->numel,&ochar->ndims,&ochar->size,prhs[0]);
 
 	return(ochar);
 }/*}}}*/
-/*FUNCTION OptionStructParse {{{*/
-OptionStruct* OptionStructParse( char* name, const mxArray* prhs[]){
+GenericOption<Options**>* OptionStructParse( char* name, const mxArray* prhs[]){ /*{{{*/
 
 	int            i;
 	char           namei[161];
-	OptionStruct  *ostruct    = NULL;
-	Option        *option     = NULL;
+	Option*                   option      = NULL;
+	GenericOption<Options**>  *ostruct    = NULL;
 	const mwSize  *ipt        = NULL;
 	const mxArray *structi;
@@ -81,5 +92,5 @@
 
 	/*check and parse the name  */
-	ostruct=new OptionStruct;
+	ostruct=new GenericOption<Options**>();
 	ostruct->name =xNew<char>(strlen(name)+1);
 	memcpy(ostruct->name,name,(strlen(name)+1)*sizeof(char));
@@ -87,5 +98,5 @@
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"struct")){
-		_error2_("Value of option \"" << ostruct->name  << "\" must be class \"struct\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+		_error_("Value of option \"" << ostruct->name  << "\" must be class \"struct\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
 	ostruct->numel=mxGetNumberOfElements(prhs[0]);
@@ -94,9 +105,9 @@
 	ostruct->size =xNew<int>(ostruct->ndims);
 	for (i=0; i<ostruct->ndims; i++) ostruct->size[i]=(int)ipt[i];
-	if (ostruct->numel) ostruct->values=xNew<Options*>(ostruct->numel);
+	if (ostruct->numel) ostruct->value=xNew<Options*>(ostruct->numel);
 
 	/*loop through and process each element of the struct array  */
 	for (sindex=0; sindex<ostruct->numel; sindex++) {
-		ostruct->values[sindex]=new Options;
+		ostruct->value[sindex]=new Options;
 
 		/*loop through and process each field for the element  */
@@ -106,5 +117,5 @@
 
 			option=(Option*)OptionParse(namei,&structi);
-			ostruct->values[sindex]->AddObject((Object*)option);
+			ostruct->value[sindex]->AddObject((Object*)option);
 			option=NULL;
 		}
@@ -113,6 +124,5 @@
 	return(ostruct);
 }/*}}}*/
-/*FUNCTION OptionCellParse {{{*/
-OptionCell* OptionCellParse( char* name, const mxArray* prhs[]){
+GenericOption<Options*>* OptionCellParse( char* name, const mxArray* prhs[]){ /*{{{*/
 
 	int            i;
@@ -120,5 +130,5 @@
 	char           namei[161];
 	char           cstr[81];
-	OptionCell    *ocell      = NULL;
+	GenericOption<Options*> *ocell      = NULL;
 	Option        *option     = NULL;
 	const mwSize  *ipt        = NULL;
@@ -127,5 +137,5 @@
 
 	/*check and parse the name  */
-	ocell=new OptionCell;
+	ocell=new GenericOption<Options*>();
 	ocell->name =xNew<char>(strlen(name)+1);
 	memcpy(ocell->name,name,(strlen(name)+1)*sizeof(char));
@@ -133,5 +143,5 @@
 	/*check and parse the value  */
 	if (!mxIsClass(prhs[0],"cell")){
-		_error2_("Value of option \"" << ocell->name  << "\" must be class \"cell\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+		_error_("Value of option \"" << ocell->name  << "\" must be class \"cell\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
 	}
 
@@ -141,5 +151,5 @@
 	ocell->size =xNew<int>(ocell->ndims);
 	for (i=0; i<ocell->ndims; i++) ocell->size[i]=(int)ipt[i];
-	ocell->values=new Options;
+	ocell->value=new Options;
 
 	/*loop through and process each element of the cell array  */
@@ -156,5 +166,5 @@
 
 		option=(Option*)OptionParse(namei,&celli);
-		ocell->values->AddObject((Object*)option);
+		ocell->value->AddObject((Object*)option);
 		option=NULL;
 	}
@@ -163,16 +173,22 @@
 	return(ocell);
 }/*}}}*/
-/*FUNCTION OptionParse{{{*/
-Option* OptionParse(char* name, const mxArray* prhs[]){
-
-	Option *option = NULL;
-	mxArray       *lhs[1];
+Option* OptionParse(char* name, const mxArray* prhs[]){ /*{{{*/
+
+	Option  *option = NULL;
+	mxArray *lhs[1];
 
 	/*parse the value according to the matlab data type  */
-	if     (mxIsClass(prhs[0],"double"))  option=(Option*)OptionDoubleParse(name,prhs);
-	else if(mxIsClass(prhs[0],"logical")) option=(Option*)OptionLogicalParse(name,prhs);
-	else if(mxIsClass(prhs[0],"char"))    option=(Option*)OptionCharParse(name,prhs);
-	else if(mxIsClass(prhs[0],"struct"))  option=(Option*)OptionStructParse(name,prhs);
-	else if(mxIsClass(prhs[0],"cell"))    option=(Option*)OptionCellParse(name,prhs);
+	if     (mxIsClass(prhs[0],"double")  && (mxGetNumberOfElements(prhs[0])==1))
+	 option=(Option*)OptionDoubleParse(name,prhs);
+	else if(mxIsClass(prhs[0],"double")  && (mxGetNumberOfElements(prhs[0])!=1))
+	 option=(Option*)OptionDoubleArrayParse(name,prhs);
+	else if(mxIsClass(prhs[0],"logical"))
+	 option=(Option*)OptionLogicalParse(name,prhs);
+	else if(mxIsClass(prhs[0],"char"))
+	 option=(Option*)OptionCharParse(name,prhs);
+	else if(mxIsClass(prhs[0],"struct"))
+	 option=(Option*)OptionStructParse(name,prhs);
+	else if(mxIsClass(prhs[0],"cell"))
+	 option=(Option*)OptionCellParse(name,prhs);
 	else {
 		_pprintLine_("  Converting value of option \"" << name << "\" from unrecognized class \"" << mxGetClassName(prhs[0]) << "\" to class \"" << "struct" << "\".");
@@ -181,5 +197,5 @@
 			mxDestroyArray(lhs[0]);
 		}
-		else _error2_("Second argument value of option \""<< name <<"\" is of unrecognized class \""<< mxGetClassName(prhs[0]) <<"\".");
+		else _error_("Second argument value of option \""<< name <<"\" is of unrecognized class \""<< mxGetClassName(prhs[0]) <<"\".");
 	}
 
Index: /issm/trunk/src/c/matlab/io/WriteMatlabData.cpp
===================================================================
--- /issm/trunk/src/c/matlab/io/WriteMatlabData.cpp	(revision 13394)
+++ /issm/trunk/src/c/matlab/io/WriteMatlabData.cpp	(revision 13395)
@@ -9,10 +9,8 @@
 #endif
 
+#include <mex.h>
 #include "../../include/include.h"
 #include "../../shared/shared.h"
 #include "./matlabio.h"
-
-#include <mex.h>
-
 
 /*Primitive data types*/
@@ -124,5 +122,5 @@
 	int         i;
 	mxArray    *dataref           = NULL;
-	const int   numfields         = 7;
+	const int   numfields         = 8;
 	const char *fnames[numfields];
 	mwSize      ndim              = 2;
@@ -134,4 +132,5 @@
 	fnames[i++] = "Edges";
 	fnames[i++] = "TangentAtEdges";
+	fnames[i++] = "Corners";
 	fnames[i++] = "RequiredVertices";
 	fnames[i++] = "RequiredEdges";
@@ -148,4 +147,5 @@
 	i++; SetStructureField(dataref,"Edges",           bamggeom->EdgesSize[0],           bamggeom->EdgesSize[1],           bamggeom->Edges);
 	i++; SetStructureField(dataref,"TangentAtEdges",  bamggeom->TangentAtEdgesSize[0],  bamggeom->TangentAtEdgesSize[1],  bamggeom->TangentAtEdges);
+	i++; SetStructureField(dataref,"Corners",         bamggeom->CornersSize[0],         bamggeom->CornersSize[1],         bamggeom->Corners);
 	i++; SetStructureField(dataref,"RequiredVertices",bamggeom->RequiredVerticesSize[0],bamggeom->RequiredVerticesSize[1],bamggeom->RequiredVertices);
 	i++; SetStructureField(dataref,"RequiredEdges",   bamggeom->RequiredEdgesSize[0],   bamggeom->RequiredEdgesSize[1],   bamggeom->RequiredEdges);
@@ -171,10 +171,10 @@
 	/*Initialize field names*/
 	i=0;
-	fnames[i++] = "Triangles";
 	fnames[i++] = "Vertices";
 	fnames[i++] = "Edges";
+	fnames[i++] = "Triangles";
+	fnames[i++] = "Quadrilaterals";
+	fnames[i++] = "IssmEdges";
 	fnames[i++] = "IssmSegments";
-	fnames[i++] = "IssmEdges";
-	fnames[i++] = "Quadrilaterals";
 	fnames[i++] = "VerticesOnGeomVertex";
 	fnames[i++] = "VerticesOnGeomEdge";
@@ -194,10 +194,10 @@
 	/*set each matlab each field*/
 	i=0;
-	i++; SetStructureField(dataref,"Triangles", bamgmesh->TrianglesSize[0],bamgmesh->TrianglesSize[1], bamgmesh->Triangles);
 	i++; SetStructureField(dataref,"Vertices",bamgmesh->VerticesSize[0], bamgmesh->VerticesSize[1],bamgmesh->Vertices);
 	i++; SetStructureField(dataref,"Edges", bamgmesh->EdgesSize[0],bamgmesh->EdgesSize[1], bamgmesh->Edges);
+	i++; SetStructureField(dataref,"Triangles", bamgmesh->TrianglesSize[0],bamgmesh->TrianglesSize[1], bamgmesh->Triangles);
+	i++; SetStructureField(dataref,"Quadrilaterals",bamgmesh->QuadrilateralsSize[0], bamgmesh->QuadrilateralsSize[1],bamgmesh->Quadrilaterals);
+	i++; SetStructureField(dataref,"IssmEdges", bamgmesh->IssmEdgesSize[0],bamgmesh->IssmEdgesSize[1], bamgmesh->IssmEdges);
 	i++; SetStructureField(dataref,"IssmSegments",bamgmesh->IssmSegmentsSize[0], bamgmesh->IssmSegmentsSize[1],bamgmesh->IssmSegments);
-	i++; SetStructureField(dataref,"IssmEdges", bamgmesh->IssmEdgesSize[0],bamgmesh->IssmEdgesSize[1], bamgmesh->IssmEdges);
-	i++; SetStructureField(dataref,"Quadrilaterals",bamgmesh->QuadrilateralsSize[0], bamgmesh->QuadrilateralsSize[1],bamgmesh->Quadrilaterals);
 	i++; SetStructureField(dataref,"VerticesOnGeomVertex",bamgmesh->VerticesOnGeomVertexSize[0],bamgmesh->VerticesOnGeomVertexSize[1], bamgmesh->VerticesOnGeomVertex);
 	i++; SetStructureField(dataref,"VerticesOnGeomEdge",bamgmesh->VerticesOnGeomEdgeSize[0],bamgmesh->VerticesOnGeomEdgeSize[1], bamgmesh->VerticesOnGeomEdge);
@@ -216,6 +216,6 @@
 }
 /*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,Matrix* matrix){{{*/
-void WriteData(mxArray** pdataref,Matrix* matrix){
+/*FUNCTION WriteData(mxArray** pdataref,SeqMat<double>* matrix){{{*/
+void WriteData(mxArray** pdataref,SeqMat<double>* matrix){
 		
 	int      i,j;
@@ -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: */
@@ -250,15 +246,14 @@
 		/*Free ressources:*/
 		xDelete<double>(matrix_ptr);
-
-	}
-	else{
-		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
-	}
-
-	*pdataref=dataref;
-}
-/*}}}*/
-/*FUNCTION WriteData(mxArray** pdataref,Vector* vector){{{*/
-void WriteData(mxArray** pdataref,Vector* vector){
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,SeqVec<double>* vector){{{*/
+void WriteData(mxArray** pdataref,SeqVec<double>* vector){
 	
 	mxArray* dataref=NULL;
@@ -269,10 +264,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 */
Index: /issm/trunk/src/c/matlab/io/matlabio.h
===================================================================
--- /issm/trunk/src/c/matlab/io/matlabio.h	(revision 13394)
+++ /issm/trunk/src/c/matlab/io/matlabio.h	(revision 13395)
@@ -12,14 +12,13 @@
 #endif 
 
-#include "../../objects/objects.h"
+#include <mex.h>
+#include "../../classes/classes.h"
 #include "../../Container/Container.h"
 #include "../../include/include.h"
 
-#include <mex.h>
-
-void WriteData(mxArray** pdataref,Matrix* matrix);
+void WriteData(mxArray** pdataref,SeqMat<double>* matrix);
 void WriteData(mxArray** pdataref,double* matrix, int M,int N);
 void WriteData(mxArray** pdataref,int*    matrix, int M,int N);
-void WriteData(mxArray** pdataref,Vector* vector);
+void WriteData(mxArray** pdataref,SeqVec<double>* vector);
 void WriteData(mxArray** pdataref,double* vector, int M);
 void WriteData(mxArray** pdataref,int integer);
@@ -35,10 +34,10 @@
 void FetchData(bool** pmatrix,int* pM,int *pN,const mxArray* dataref);
 void FetchData(bool** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref);
-void FetchData(Matrix** pmatrix,const mxArray* dataref);
+void FetchData(Matrix<double>** pmatrix,const mxArray* dataref);
 void FetchData(int** pvector,int* pM,const mxArray* dataref);
 void FetchData(float** pvector,int* pM,const mxArray* dataref);
 void FetchData(double** pvector,int* pM,const mxArray* dataref);
 void FetchData(bool** pvector,int* pM,const mxArray* dataref);
-void FetchData(Vector** pvector,const mxArray* dataref);
+void FetchData(Vector<double>** pvector,const mxArray* dataref);
 void FetchData(char** pstring,const mxArray* dataref);
 void FetchData(char** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref);
@@ -50,11 +49,13 @@
 void FetchData(BamgOpts** bamgopts,const mxArray* dataref);
 void FetchData(Options** poptions,int istart, int nrhs,const mxArray** pdataref);
+void FetchData(DataSet** pcontours,const mxArray* dataref);
 
 Option* OptionParse(char* name, const mxArray* prhs[]);
-OptionDouble*   OptionDoubleParse( char* name, const mxArray* prhs[]);
-OptionLogical*  OptionLogicalParse( char* name, const mxArray* prhs[]);
-OptionChar*     OptionCharParse( char* name, const mxArray* prhs[]);
-OptionStruct*   OptionStructParse( char* name, const mxArray* prhs[]);
-OptionCell*     OptionCellParse( char* name, const mxArray* prhs[]);
+GenericOption<double>*    OptionDoubleParse( char* name, const mxArray* prhs[]);
+GenericOption<double*>*   OptionDoubleArrayParse( char* name, const mxArray* prhs[]);
+GenericOption<bool*>*     OptionLogicalParse( char* name, const mxArray* prhs[]);
+GenericOption<char*>*     OptionCharParse( char* name, const mxArray* prhs[]);
+GenericOption<Options**>* OptionStructParse( char* name, const mxArray* prhs[]);
+GenericOption<Options*>*  OptionCellParse( char* name, const mxArray* prhs[]);
 
 mxArray* mxGetAssignedField(const mxArray* pmxa_array,int number, const char* field);
@@ -63,6 +64,6 @@
 
 /*Matlab to Matrix routines: */
-Matrix* MatlabMatrixToMatrix(const mxArray* mxmatrix);
-Vector* MatlabVectorToVector(const mxArray* mxvector);
+Matrix<double>* MatlabMatrixToMatrix(const mxArray* mxmatrix);
+Vector<double>* MatlabVectorToVector(const mxArray* mxvector);
 
 /*Matlab to double* routines: */
@@ -74,13 +75,14 @@
 
 /*Matlab to SeqMat routines: */
-SeqMat* MatlabMatrixToSeqMat(const mxArray* dataref);
-SeqVec* MatlabVectorToSeqVec(const mxArray* dataref);
+SeqMat<double>* MatlabMatrixToSeqMat(const mxArray* dataref);
+SeqVec<double>* MatlabVectorToSeqVec(const mxArray* dataref);
 
 /*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
 
-
 #endif	/* _IO_H_ */
Index: /issm/trunk/src/c/modules/AddExternalResultx/AddExternalResultx.cpp
===================================================================
--- /issm/trunk/src/c/modules/AddExternalResultx/AddExternalResultx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/AddExternalResultx/AddExternalResultx.cpp	(revision 13395)
@@ -7,12 +7,19 @@
 #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){
+void AddExternalResultx( DataSet* results, int enumtype, IssmDouble value){
 	/* Add new result in into results*/
-	results->AddObject(new DoubleExternalResult(results->Size()+1,enumtype,value,1,0));
+	results->AddObject(new GenericExternalResult<double>(results->Size()+1,enumtype,reCast<IssmPDouble>(value),1,0));
 }
-void AddExternalResultx( DataSet* results, int enumtype, double* value, int nraws){
+void AddExternalResultx( DataSet* results, int enumtype, IssmDouble* value, int nrows){
 	/* Add new result in into results*/
-	results->AddObject(new DoubleVecExternalResult(results->Size()+1,enumtype,value,nraws,1,0));
+	#ifdef _HAVE_ADOLC_
+	IssmPDouble* value_passive=xNew<IssmPDouble>(nrows);
+	for(int i=0;i<nrows;i++)value_passive[i]=reCast<IssmPDouble>(value[i]);
+	results->AddObject(new GenericExternalResult<double*>(results->Size()+1,enumtype,value_passive,nrows,1,1,0));
+	xDelete<IssmPDouble>(value_passive);
+	#else
+	results->AddObject(new GenericExternalResult<double*>(results->Size()+1,enumtype,value,nrows,1,1,0));
+	#endif
 }
Index: /issm/trunk/src/c/modules/AddExternalResultx/AddExternalResultx.h
===================================================================
--- /issm/trunk/src/c/modules/AddExternalResultx/AddExternalResultx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/AddExternalResultx/AddExternalResultx.h	(revision 13395)
@@ -9,6 +9,6 @@
 
 /* local prototypes: */
-void AddExternalResultx(DataSet* results, int type, double value);
-void AddExternalResultx(DataSet* results, int type, double* value, int nraws);
+void AddExternalResultx(DataSet* results, int type, IssmDouble value);
+void AddExternalResultx(DataSet* results, int type, IssmDouble* value, int nraws);
 
 #endif  /* _ADDEXTERNALRESULT_H */
Index: /issm/trunk/src/c/modules/AutodiffDriversx/AutodiffDriversx.cpp
===================================================================
--- /issm/trunk/src/c/modules/AutodiffDriversx/AutodiffDriversx.cpp	(revision 13395)
+++ /issm/trunk/src/c/modules/AutodiffDriversx/AutodiffDriversx.cpp	(revision 13395)
@@ -0,0 +1,96 @@
+/*!\file AutodiffDriversx
+ * \brief: compute outputs from the AD mode,  using our dependents and independents, and drivers available in Adolc.
+ */
+
+#include "../../modules/modules.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/Numerics/adolc_edf.h"
+
+
+void AutodiffDriversx(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,Results* results){
+	bool isautodiff       = false;
+	/*AD mode on?: */
+	parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
+	if(isautodiff){
+		#ifdef _HAVE_ADOLC_
+			int  num_dependents;
+			parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
+			int  num_independents;
+			parameters->FindParam(&num_independents,AutodiffNumIndependentsEnum);
+			if(!(num_dependents*num_independents)) return;
+			int  numberofvertices;
+			parameters->FindParam(&numberofvertices,MeshNumberofverticesEnum);
+			/*retrieve state variable: */
+			IssmDouble  *axp  = NULL;
+			parameters->FindParam(&axp,&num_independents,AutodiffXpEnum);
+			/* driver argument */
+			double *xp=xNew<double>(num_independents);
+			for(int i=0;i<num_independents;i++){
+				xp[i]=reCast<double,IssmDouble>(axp[i]);
+			}
+			/* get the dimension for the solverx arguments*/
+			int configuration_type;
+			parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+			int solveSize=nodes->NumberOfDofs(configuration_type,FsetEnum);
+			int edf_n=solveSize*(solveSize+1), edf_m=solveSize;
+
+			/*get the EDF pointer:*/
+			ext_diff_fct *anEDF_for_solverx_p=dynamic_cast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p;
+
+			/*set the forward method function pointers: */
+			anEDF_for_solverx_p->zos_forward=EDF_for_solverx;
+			anEDF_for_solverx_p->fos_forward=EDF_fos_forward_for_solverx;
+			anEDF_for_solverx_p->fov_forward=EDF_fov_forward_for_solverx;
+			anEDF_for_solverx_p->fos_reverse=EDF_fos_reverse_for_solverx;
+			// anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
+			/*allocate the space for the parameters to invoke the forward methods:*/
+			anEDF_for_solverx_p->dp_x=xNew<double>(edf_n);
+			anEDF_for_solverx_p->dp_X=xNew<double>(edf_n);
+			anEDF_for_solverx_p->dpp_X=xNew<double>(edf_n, num_independents);
+			anEDF_for_solverx_p->dp_y=xNew<double>(edf_m);
+			anEDF_for_solverx_p->dp_Y=xNew<double>(edf_m);
+			anEDF_for_solverx_p->dpp_Y=xNew<double>(edf_m, num_independents);
+			anEDF_for_solverx_p->dp_U=xNew<double>(edf_m);
+			anEDF_for_solverx_p->dpp_U=xNew<double>(num_dependents,edf_m);
+			anEDF_for_solverx_p->dp_Z=xNew<double>(edf_n);
+			anEDF_for_solverx_p->dpp_Z=xNew<double>(num_dependents,edf_n);
+			/* Call AD driver:*/
+			// single direction:
+			double *tangentDir=xNewZeroInit<double>(num_independents);
+			unsigned int anIndepNum=55; // <---------- make this selectable via config
+			tangentDir[anIndepNum]=1.0;
+			double *theJacVecProduct=xNew<double>(num_dependents);
+			double *theOutput=xNew<double>(num_dependents);
+			if (fos_forward(1,num_dependents,num_independents, 0, xp, tangentDir, theOutput, theJacVecProduct ))
+				_error_("fos_forward returned non-zero error code");
+			results->AddObject(new GenericExternalResult<IssmPDouble*>(results->Size()+1,AutodiffJacobianEnum,theJacVecProduct,num_dependents,1,1,0.0));
+
+#if 0
+			double **J=xNew<double>(num_dependents,num_independents);
+			jacobian(1,num_dependents,num_independents,xp,J);
+			results->AddObject(new GenericExternalResult<IssmPDouble*>(results->Size()+1,AutodiffJacobianEnum,*J,num_independents,num_dependents,1,1,0.0));
+			xDelete(J);
+#endif
+
+			/* delete the allocated space for the parameters:*/
+			xDelete(anEDF_for_solverx_p->dp_x);
+			xDelete(anEDF_for_solverx_p->dp_X);
+			xDelete(anEDF_for_solverx_p->dpp_X);
+			xDelete(anEDF_for_solverx_p->dp_y);
+			xDelete(anEDF_for_solverx_p->dp_Y);
+			xDelete(anEDF_for_solverx_p->dpp_Y);
+			xDelete(anEDF_for_solverx_p->dp_U);
+			xDelete(anEDF_for_solverx_p->dpp_U);
+			xDelete(anEDF_for_solverx_p->dp_Z);
+			xDelete(anEDF_for_solverx_p->dpp_Z);
+			/*Free ressources: */
+			xDelete(xp);
+			xDelete(axp); // did we allocate this?
+		#else
+			_error_("Should not be requesting AD drivers when an AD library is not available!");
+		#endif
+	}
+}
Index: /issm/trunk/src/c/modules/AutodiffDriversx/AutodiffDriversx.h
===================================================================
--- /issm/trunk/src/c/modules/AutodiffDriversx/AutodiffDriversx.h	(revision 13395)
+++ /issm/trunk/src/c/modules/AutodiffDriversx/AutodiffDriversx.h	(revision 13395)
@@ -0,0 +1,13 @@
+/*!\file:  AutodiffDriversx.h
+ * \brief header file for  requesting AD results (gradient, jacobian, etc ...)
+ */ 
+
+#ifndef _AUTODIFF_DRIVERSX_H_
+#define _AUTODIFF_DRIVERSX_H_
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void AutodiffDriversx(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,Results* results);
+
+#endif  /* _AUTODIFF_DRIVERSX_H_*/
Index: /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 13395)
@@ -29,7 +29,7 @@
 
 	/*output: */
-	Vector* partition_contributions=NULL;
-	Vector* partition_areas=NULL;
-	Vector* vec_average=NULL;
+	Vector<IssmDouble>* partition_contributions=NULL;
+	Vector<IssmDouble>* partition_areas=NULL;
+	Vector<IssmDouble>* vec_average=NULL;
 	double* average=NULL;
 
@@ -44,7 +44,7 @@
 
 	/*allocate: */
-	partition_contributions=new Vector(npart);
-	partition_areas=new Vector(npart);
-	vec_average=new Vector(npart);
+	partition_contributions=new Vector<IssmDouble>(npart);
+	partition_areas=new Vector<IssmDouble>(npart);
+	vec_average=new Vector<IssmDouble>(npart);
 
 	/*loop on each element, and add contribution of the element to the partition (surface weighted average): */
Index: /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h
===================================================================
--- /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _AVERAGEONTOPARTITIONXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp	(revision 13395)
@@ -7,5 +7,5 @@
 #include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../objects/objects.h"
+#include "../../classes/bamg/bamgobjects.h"
 
 using namespace bamg;
Index: /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h
===================================================================
--- /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _BAMGCONVERTMESHX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.h
===================================================================
--- /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.h	(revision 13394)
+++ /issm/trunk/src/c/modules/BamgTriangulatex/BamgTriangulatex.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _BAMGTRIANGULATEX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Bamgx/Bamgx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Bamgx/Bamgx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Bamgx/Bamgx.cpp	(revision 13395)
@@ -3,5 +3,5 @@
  */
 #include "./Bamgx.h"
-#include "../../objects/objects.h"
+#include "../../classes/bamg/bamgobjects.h"
 #include "../../shared/shared.h"
 #include "../../include/include.h"
@@ -119,5 +119,5 @@
 			if (verbosity>1) _printLine_("   Merging Metric with hVertices...");
 			for (i=0;i<BTh.nbv;i++){
-				if (!xIsNan<IssmDouble>(bamgopts->hVertices[i])){
+				if (!xIsNan<IssmPDouble>(bamgopts->hVertices[i])){
 					BTh[i].m=Metric((float)bamgopts->hVertices[i]);
 				}
@@ -129,5 +129,5 @@
 			if (verbosity>1) _printLine_("   Merging Metric with hminVertices...");
 			for (i=0;i<BTh.nbv;i++){
-				if (!xIsNan<IssmDouble>(bamgopts->hminVertices[i])){
+				if (!xIsNan<IssmPDouble>(bamgopts->hminVertices[i])){
 					Metric M=BTh.vertices[i].m;
 					EigenMetric Vp(M/coef);
@@ -142,5 +142,5 @@
 			if (verbosity>1) _printLine_("   Merging Metric with hmaxVertices...");
 			for (i=0;i<BTh.nbv;i++){
-				if (!xIsNan<IssmDouble>(bamgopts->hmaxVertices[i])){
+				if (!xIsNan<IssmPDouble>(bamgopts->hmaxVertices[i])){
 					Metric M=BTh.vertices[i].m;
 					EigenMetric Vp(M/coef);
Index: /issm/trunk/src/c/modules/Bamgx/Bamgx.h
===================================================================
--- /issm/trunk/src/c/modules/Bamgx/Bamgx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Bamgx/Bamgx.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _BAMGX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/bamg/bamgobjects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Chacox/Chacox.h
===================================================================
--- /issm/trunk/src/c/modules/Chacox/Chacox.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Chacox/Chacox.h	(revision 13395)
@@ -33,5 +33,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void	ComputeBasalStressx( Vector** psigma,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,Parameters* parameters){
+void	ComputeBasalStressx( Vector<IssmDouble>** psigma,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
@@ -19,5 +19,5 @@
 
 	/*output: */
-	Vector* sigma=NULL;
+	Vector<IssmDouble>* sigma=NULL;
 
 	/*Recover numberofelements: */
@@ -25,5 +25,5 @@
 
 	/*Allocate sigma on numberofelements: */
-	sigma=new Vector(reCast<int>(numberofelements));
+	sigma=new Vector<IssmDouble>(reCast<int>(numberofelements));
 
 	/*Compute basal stress for each element: */
Index: /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h
===================================================================
--- /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h	(revision 13395)
@@ -6,9 +6,9 @@
 #define _COMPUTEBASALSTRESSX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 /* local prototypes: */
-void	ComputeBasalStressx( Vector** pp_g,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
+void	ComputeBasalStressx( Vector<IssmDouble>** pp_g,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
 
 #endif  /* _COMPUTEBASALSTRESSX_H */
Index: /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void	ComputeStrainRatex( Vector** peps,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,Parameters* parameters){
+void	ComputeStrainRatex( Vector<IssmDouble>** peps,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
@@ -19,5 +19,5 @@
 
 	/*output: */
-	Vector* eps=NULL;
+	Vector<IssmDouble>* eps=NULL;
 
 	/*Recover numberofelements: */
@@ -25,5 +25,5 @@
 
 	/*Allocate eps on numberofelements (only 1 dof): */
-	eps=new Vector(numberofelements);
+	eps=new Vector<IssmDouble>(numberofelements);
 
 	/*Compute basal stress for each element: */
Index: /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h
===================================================================
--- /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h	(revision 13395)
@@ -6,9 +6,9 @@
 #define _COMPUTESTRAINRATEX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 /* local prototypes: */
-void	ComputeStrainRatex(Vector** eps_g,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
+void	ComputeStrainRatex(Vector<IssmDouble>** eps_g,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
 
 #endif  /* _COMPUTESTRAINRATEX_H */
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 13395)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /*melting: */
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 13395)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 13395)
@@ -11,5 +11,5 @@
 #include "./ContourToMeshx.h"
 
-int ContourToMeshx( Vector** pin_nod,Vector** pin_elem, double* index, double* x, double* y,DataSet* contours,char* interptype,int nel,int nods, int edgevalue) {
+int ContourToMeshx(SeqVec<double>** pin_nod,SeqVec<double>** pin_elem, double* index, double* x, double* y,DataSet* contours,char* interptype,int nel,int nods, int edgevalue) {
 
 	int noerr=1;
@@ -30,9 +30,8 @@
 
 	/*output: */
-	Vector* in_nod=NULL;
-	Vector* in_elem=NULL;
-
-	in_nod=new Vector(nods);
-	in_elem=new Vector(nel);
+	SeqVec<double>* in_nod=NULL;
+	SeqVec<double>* in_elem=NULL;
+	in_nod  = new SeqVec<double>(nods);
+	in_elem = new SeqVec<double>(nel);
 
 	/*initialize thread parameters: */
Index: /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.h
===================================================================
--- /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.h	(revision 13395)
@@ -8,15 +8,15 @@
 
 #include "../../shared/shared.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /*threading: */
 typedef struct{
 
-	DataSet* contours;
-	int nods;
-	int edgevalue;
-	Vector* in_nod;
-	double* x;
-	double* y;
+	DataSet *contours;
+	int    nods;
+	int    edgevalue;
+	SeqVec<double> *in_nod;
+	double *x;
+	double *y;
 
 } ContourToMeshxThreadStruct;
@@ -24,9 +24,7 @@
 
 /* local prototypes: */
-int ContourToMeshx( Vector** pin_nods,Vector** pin_elem, double* index, double* x, double* y,DataSet* contours,char* interptype,int nel,int nods, int edgevalue);
+int ContourToMeshx(SeqVec<double>** pin_nods,SeqVec<double>** pin_elem, double* index, double* x, double* y,DataSet* contours,char* interptype,int nel,int nods, int edgevalue);
 
 void* ContourToMeshxt(void* vContourToMeshxThreadStruct);
 
-
 #endif /* _CONTOURTOMESHX_H */
-
Index: /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp	(revision 13395)
@@ -33,6 +33,5 @@
 	double* x=NULL;
 	double* y=NULL;
-	Vector* in_nod=NULL;
-
+	SeqVec<double>* in_nod=NULL;
 
 	/*recover handle and gate: */
@@ -55,9 +54,8 @@
 	/*Loop through all contours: */
 	for (i=0;i<contours->Size();i++){
-		Contour* contour=(Contour*)contours->GetObjectByOffset(i);
+		Contour<double>* contour=(Contour<double>*)contours->GetObjectByOffset(i);
 		IsInPoly(in_nod,contour->x,contour->y,contour->nods,x,y,i0,i1,edgevalue);
 	}
 
 	return NULL;
-
 }
Index: /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp	(revision 13395)
@@ -4,5 +4,5 @@
 #include "./ContourToNodesx.h"
 
-int ContourToNodesx( Vector** pflags,double* x, double* y, int nods, Contour** contours,int numcontours,int edgevalue){
+int ContourToNodesx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, Contour<IssmPDouble>** contours,int numcontours,int edgevalue){
 
 	int i;
@@ -10,5 +10,5 @@
 
 	/*Contour:*/
-	Contour* contouri=NULL;
+	Contour<IssmPDouble>* contouri=NULL;
 	int      numnodes;
 	double*  xc=NULL;
@@ -17,7 +17,6 @@
 
 	/*output: */
-	Vector* flags=NULL;
-
-	flags=new Vector(nods);
+	SeqVec<IssmPDouble>* flags=NULL;
+	flags=new SeqVec<IssmPDouble>(nods);
 
 	/*Loop through all contours: */
@@ -39,5 +38,5 @@
 }
 
-int ContourToNodesx( Vector** pflags,double* x, double* y, int nods, DataSet* contours, int edgevalue){
+int ContourToNodesx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, DataSet* contours, int edgevalue){
 
 	int i;
@@ -45,5 +44,5 @@
 
 	/*Contour:*/
-	Contour* contouri=NULL;
+	Contour<IssmPDouble>* contouri=NULL;
 	int      numnodes;
 	double*  xc=NULL;
@@ -52,12 +51,11 @@
 
 	/*output: */
-	Vector* flags=NULL;
-
-	flags=new Vector(nods);
+	SeqVec<IssmPDouble>* flags=NULL;
+	flags=new SeqVec<IssmPDouble>(nods);
 
 	/*Loop through all contours: */
 	if(contours){
 		for (i=0;i<contours->Size();i++){
-			Contour* contour=(Contour*)contours->GetObjectByOffset(i);
+			Contour<IssmPDouble>* contour=(Contour<IssmPDouble>*)contours->GetObjectByOffset(i);
 			IsInPoly(flags,contour->x,contour->y,contour->nods,x,y,0,nods,edgevalue);
 		}
@@ -69,5 +67,4 @@
 	/*Assign output pointers: */
 	*pflags=flags;
-	
 	return 1;
 }
Index: /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.h
===================================================================
--- /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.h	(revision 13395)
@@ -2,5 +2,4 @@
 	ContourToNodesx.h
 */
-
 
 #ifndef _CONTOURTONODESX_H
@@ -8,10 +7,9 @@
 
 #include "../../shared/shared.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-int ContourToNodesx( Vector** pflags,double* x, double* y, int nods, Contour** contours,int numcontours,int edgevalue);
-int ContourToNodesx( Vector** pflags,double* x, double* y, int nods, DataSet* contours, int edgevalue);
+int ContourToNodesx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, Contour<IssmPDouble>** contours,int numcontours,int edgevalue);
+int ContourToNodesx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, DataSet* contours, int edgevalue);
 
 #endif /* _CONTOURTONODESX_H */
-
Index: /issm/trunk/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp	(revision 13395)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ControlInputGetGradientx( Vector** pgradient, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
+void ControlInputGetGradientx( Vector<IssmDouble>** pgradient, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
 
 	/*Intermediaries*/
 	int  num_controls;
 	int *control_type = NULL;
-	Vector*  gradient=NULL;
+	Vector<IssmDouble>*  gradient=NULL;
 
 	/*Retrieve some parameters*/
@@ -21,5 +21,5 @@
 
 	/*Allocate and populate gradient*/
-	gradient=new Vector(num_controls*vertices->NumberOfVertices());
+	gradient=new Vector<IssmDouble>(num_controls*vertices->NumberOfVertices());
 
 	for(int i=0;i<num_controls;i++){
Index: /issm/trunk/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ControlInputGetGradientx/ControlInputGetGradientx.h	(revision 13395)
@@ -5,8 +5,8 @@
 #define _CONTROLINPUTGETGRADIENTX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
-void	ControlInputGetGradientx( Vector** pgradient, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
+void	ControlInputGetGradientx( Vector<IssmDouble>** pgradient, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
 
 #endif
Index: /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp	(revision 13395)
@@ -9,11 +9,11 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* norm_list,int step){
+void ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* norm_list,int step){
 
 	/*Intermediaries*/
 	int     i,j,num_controls;
 	int    *control_type = NULL;
-	double *scalar_list = NULL;
-	double  scalar;
+	IssmDouble *scalar_list = NULL;
+	IssmDouble  scalar;
 
 
@@ -38,4 +38,4 @@
 	/*Clean up and return*/
 	xDelete<int>(control_type);
-	xDelete<double>(scalar_list);
+	xDelete<IssmDouble>(scalar_list);
 }
Index: /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.h	(revision 13395)
@@ -5,8 +5,8 @@
 #define _CONTROLINPUTSSCALEGRADIENTX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
-void	ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,double* norm_list,int step);
+void	ControlInputScaleGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,IssmDouble* norm_list,int step);
 
 #endif
Index: /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* gradient){
+void ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* gradient){
 
 	/*Intermediaries*/
@@ -30,8 +30,8 @@
 
 }
-void ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector* gradient){
+void ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* gradient){
 
 	/*Serialize gradient*/
-	double* serial_gradient=NULL;
+	IssmDouble* serial_gradient=NULL;
 	serial_gradient=gradient->ToMPISerial();
 
@@ -39,4 +39,4 @@
 
 	/*Clean up and return*/
-	xDelete<double>(serial_gradient);
+	xDelete<IssmDouble>(serial_gradient);
 }
Index: /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ControlInputSetGradientx/ControlInputSetGradientx.h	(revision 13395)
@@ -5,9 +5,9 @@
 #define _CONTROLINPUTSSETGRADIENTX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 void	ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,double* gradient);
-void	ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector* gradient);
+void	ControlInputSetGradientx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector<IssmDouble>* gradient);
 
 #endif
Index: /issm/trunk/src/c/modules/CostFunctionx/CostFunctionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/CostFunctionx/CostFunctionx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/CostFunctionx/CostFunctionx.cpp	(revision 13395)
@@ -11,15 +11,14 @@
 #include "../Responsex/Responsex.h"
 
-void CostFunctionx(double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+void CostFunctionx(IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
 
 	/*Intermediary*/
 	int      i;
 	int      num_responses;
-	double   S;
 	Element *element       = NULL;
 	int     *responses     = NULL;
 
 	/*output: */
-	double J,Jplus;
+	IssmDouble J,Jplus;
 	
 	/*Recover parameters*/
Index: /issm/trunk/src/c/modules/CostFunctionx/CostFunctionx.h
===================================================================
--- /issm/trunk/src/c/modules/CostFunctionx/CostFunctionx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/CostFunctionx/CostFunctionx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void CostFunctionx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+void CostFunctionx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
 
 #endif
Index: /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp
===================================================================
--- /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void CreateJacobianMatrixx(Matrix** pJff,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,IssmDouble kmax){
+void CreateJacobianMatrixx(Matrix<IssmDouble>** pJff,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,IssmDouble kmax){
 	
 	int      i,connectivity;
@@ -17,5 +17,5 @@
 	Element *element = NULL;
 	Load    *load    = NULL;
-	Matrix*  Jff     = NULL;
+	Matrix<IssmDouble>*  Jff     = NULL;
 
 	/*Checks*/
@@ -29,5 +29,5 @@
 
 	/*Initialize Jacobian Matrix*/
-	Jff=new Matrix(fsize,fsize,connectivity,numberofdofspernode);
+	Jff=new Matrix<IssmDouble>(fsize,fsize,connectivity,numberofdofspernode);
 	
 	/*Create and assemble matrix*/
Index: /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h
===================================================================
--- /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h	(revision 13395)
@@ -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,IssmDouble kmax);
+void CreateJacobianMatrixx(Matrix<IssmDouble>** pJff,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,IssmDouble kmax);
 
 #endif  /* _CREATEJACOBIANMATRIXX_H */
Index: /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void CreateNodalConstraintsx( Vector** pys, Nodes* nodes,int configuration_type){
+void CreateNodalConstraintsx( Vector<IssmDouble>** pys, Nodes* nodes,int configuration_type){
 
 	int i;
@@ -18,5 +18,5 @@
 
 	/*output: */
-	Vector* ys=NULL;
+	Vector<IssmDouble>* ys=NULL;
 
 	/*figure out how many dofs we have: */
@@ -24,5 +24,5 @@
 
 	/*allocate:*/
-	ys=new Vector(numberofdofs);
+	ys=new Vector<IssmDouble>(numberofdofs);
 
 	/*go through all nodes, and for the ones corresponding to this configuration_type, fill the 
Index: /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h	(revision 13395)
@@ -6,8 +6,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void CreateNodalConstraintsx( Vector** pys, Nodes* nodes,int configuration_type);
+void CreateNodalConstraintsx( Vector<IssmDouble>** pys, Nodes* nodes,int configuration_type);
 
 #endif  /* _CREATENODALCONSTRAINTSX_H */
Index: /issm/trunk/src/c/modules/DakotaResponsesx/DakotaResponsesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/DakotaResponsesx/DakotaResponsesx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/DakotaResponsesx/DakotaResponsesx.cpp	(revision 13395)
@@ -86,5 +86,5 @@
 		}
 		else if (flag==NodalEnum){
-			_error2_("nodal response functions not supported yet!");
+			_error_("nodal response functions not supported yet!");
 
 			/*increment response_pointer :*/
@@ -104,5 +104,5 @@
 			}
 		}
-		else _error2_("flag type " << flag << " not supported yet for response analysis");
+		else _error_("flag type " << flag << " not supported yet for response analysis");
 	}
 
Index: /issm/trunk/src/c/modules/DakotaResponsesx/DakotaResponsesx.h
===================================================================
--- /issm/trunk/src/c/modules/DakotaResponsesx/DakotaResponsesx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/DakotaResponsesx/DakotaResponsesx.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _DAKOTARESPONSESXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/trunk/src/c/modules/Dakotax/Dakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/Dakotax/Dakotax.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Dakotax/Dakotax.cpp	(revision 13395)
@@ -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.
Index: /issm/trunk/src/c/modules/Dakotax/Dakotax.h
===================================================================
--- /issm/trunk/src/c/modules/Dakotax/Dakotax.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Dakotax/Dakotax.h	(revision 13395)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/classes.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Dakotax/DescriptorIndex.cpp
===================================================================
--- /issm/trunk/src/c/modules/Dakotax/DescriptorIndex.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Dakotax/DescriptorIndex.cpp	(revision 13395)
@@ -23,10 +23,10 @@
 	/*retrieve first token, separated by underscore: */
 	pch = strtok (descriptor,"_");
-	if(!pch)_error2_("descriptor " << descriptor << " is not correctly formatted!");
+	if(!pch)_error_("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)_error2_("scaled descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("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)_error2_("indexed descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("indexed descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 		/*now recover  the index: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("indexed descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("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)_error2_("nodal descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("nodal descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 		/*now recover  the index: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("nodal descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("nodal descriptor " << descriptor << " is not correctly formatted!");
 		sscanf(pch,"%i",pindex);
 		return NodalEnum;
Index: /issm/trunk/src/c/modules/Dakotax/SpawnCore.cpp
===================================================================
--- /issm/trunk/src/c/modules/Dakotax/SpawnCore.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Dakotax/SpawnCore.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../io/io.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
Index: /issm/trunk/src/c/modules/Dakotax/SpawnCoreParallel.cpp
===================================================================
--- /issm/trunk/src/c/modules/Dakotax/SpawnCoreParallel.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Dakotax/SpawnCoreParallel.cpp	(revision 13395)
@@ -26,5 +26,5 @@
 
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../io/io.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
@@ -72,5 +72,5 @@
 	if(control_analysis)solutioncore=&control_core;
 	#else
-	_error2_("ISSM was not compiled with control capabilities, exiting!");
+	_error_("ISSM was not compiled with control capabilities, exiting!");
 	#endif
 
Index: /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp	(revision 13395)
+++ /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.h
===================================================================
--- /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.h	(revision 13395)
+++ /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.h	(revision 13395)
@@ -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/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void DragCoefficientAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void DragCoefficientAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void DragCoefficientAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/ElementResponsex/ElementResponsex.cpp
===================================================================
--- /issm/trunk/src/c/modules/ElementResponsex/ElementResponsex.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ElementResponsex/ElementResponsex.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ElementResponsex( double* presponse, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int response_enum,bool process_units){
+void ElementResponsex( IssmDouble* presponse, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int response_enum,bool process_units){
 	
 
@@ -20,5 +20,5 @@
 	int cpu_found=-1;
 	int index;
-	double response;
+	IssmDouble response;
 	Element* element=NULL;
 
@@ -39,5 +39,5 @@
 	#ifdef _HAVE_MPI_
 	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
-	if(!sumfound)_error2_("could not find material with id" << index << " to compute ElementResponse");
+	if(!sumfound)_error_("could not find material with id" << index << " to compute ElementResponse");
 	#endif
 
Index: /issm/trunk/src/c/modules/ElementResponsex/ElementResponsex.h
===================================================================
--- /issm/trunk/src/c/modules/ElementResponsex/ElementResponsex.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ElementResponsex/ElementResponsex.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void ElementResponsex( double* presponse, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int response_enum,bool process_units);
+void ElementResponsex( IssmDouble* presponse, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int response_enum,bool process_units);
 
 #endif  /* _ELEMENTRESPONSEX_H */
Index: /issm/trunk/src/c/modules/EnumToStringx/EnumToStringx.cpp
===================================================================
--- /issm/trunk/src/c/modules/EnumToStringx/EnumToStringx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/EnumToStringx/EnumToStringx.cpp	(revision 13395)
@@ -17,7 +17,12 @@
 	switch(en){
 
-		case AutodiffForwardEnum : return "AutodiffForward";
 		case AutodiffIsautodiffEnum : return "AutodiffIsautodiff";
-		case AutodiffReverseEnum : return "AutodiffReverse";
+		case AutodiffDependentsEnum : return "AutodiffDependents";
+		case AutodiffNumDependentsEnum : return "AutodiffNumDependents";
+		case AutodiffIndependentsEnum : return "AutodiffIndependents";
+		case AutodiffNumIndependentsEnum : return "AutodiffNumIndependents";
+		case AutodiffJacobianEnum : return "AutodiffJacobian";
+		case AutodiffXpEnum : return "AutodiffXp";
+		case AutodiffFosForwardOutputEnum : return "AutodiffFosForwardOutput";
 		case BalancethicknessSpcthicknessEnum : return "BalancethicknessSpcthickness";
 		case BalancethicknessStabilizationEnum : return "BalancethicknessStabilization";
@@ -55,4 +60,5 @@
 		case FlowequationElementEquationEnum : return "FlowequationElementEquation";
 		case FlowequationIshutterEnum : return "FlowequationIshutter";
+		case FlowequationIsl1l2Enum : return "FlowequationIsl1l2";
 		case FlowequationIsmacayealpattynEnum : return "FlowequationIsmacayealpattyn";
 		case FlowequationIsstokesEnum : return "FlowequationIsstokes";
@@ -106,4 +112,6 @@
 		case MaterialsRheologyLawEnum : return "MaterialsRheologyLaw";
 		case MaterialsRheologyNEnum : return "MaterialsRheologyN";
+		case MaterialsRheologyZEnum : return "MaterialsRheologyZ";
+		case MaterialsRheologyZbarEnum : return "MaterialsRheologyZbar";
 		case MaterialsRhoIceEnum : return "MaterialsRhoIce";
 		case MaterialsRhoWaterEnum : return "MaterialsRhoWater";
@@ -154,4 +162,10 @@
 		case SettingsResultsAsPatchesEnum : return "SettingsResultsAsPatches";
 		case SettingsWaitonlockEnum : return "SettingsWaitonlock";
+		case SurfaceforcingsDelta18oEnum : return "SurfaceforcingsDelta18o";
+		case SurfaceforcingsDelta18oSurfaceEnum : return "SurfaceforcingsDelta18oSurface";
+		case SurfaceforcingsIsdelta18oEnum : return "SurfaceforcingsIsdelta18o";
+		case SurfaceforcingsPrecipitationsPresentdayEnum : return "SurfaceforcingsPrecipitationsPresentday";
+		case SurfaceforcingsTemperaturesPresentdayEnum : return "SurfaceforcingsTemperaturesPresentday";
+		case SurfaceforcingsTemperaturesLgmEnum : return "SurfaceforcingsTemperaturesLgm";
 		case DebugProfilingEnum : return "DebugProfiling";
 		case ProfilingCurrentMemEnum : return "ProfilingCurrentMem";
@@ -231,9 +245,10 @@
 		case TransientSolutionEnum : return "TransientSolution";
 		case ApproximationEnum : return "Approximation";
+		case NoneApproximationEnum : return "NoneApproximation";
 		case HutterApproximationEnum : return "HutterApproximation";
 		case MacAyealApproximationEnum : return "MacAyealApproximation";
 		case MacAyealPattynApproximationEnum : return "MacAyealPattynApproximation";
 		case MacAyealStokesApproximationEnum : return "MacAyealStokesApproximation";
-		case NoneApproximationEnum : return "NoneApproximation";
+		case L1L2ApproximationEnum : return "L1L2Approximation";
 		case PattynApproximationEnum : return "PattynApproximation";
 		case PattynStokesApproximationEnum : return "PattynStokesApproximation";
@@ -246,4 +261,6 @@
 		case VerticesEnum : return "Vertices";
 		case ResultsEnum : return "Results";
+		case GenericParamEnum : return "GenericParam";
+		case AdolcParamEnum : return "AdolcParam";
 		case BoolInputEnum : return "BoolInput";
 		case BoolParamEnum : return "BoolParam";
@@ -267,11 +284,14 @@
 		case IntParamEnum : return "IntParam";
 		case IntVecParamEnum : return "IntVecParam";
+		case TransientParamEnum : return "TransientParam";
 		case MacAyeal2dIceFrontEnum : return "MacAyeal2dIceFront";
 		case MacAyeal3dIceFrontEnum : return "MacAyeal3dIceFront";
 		case MaticeEnum : return "Matice";
+		case MatdamageiceEnum : return "Matdamageice";
 		case MatparEnum : return "Matpar";
 		case NodeEnum : return "Node";
 		case NumericalfluxEnum : return "Numericalflux";
 		case ParamEnum : return "Param";
+		case L1L2IceFrontEnum : return "L1L2IceFront";
 		case PattynIceFrontEnum : return "PattynIceFront";
 		case PengridEnum : return "Pengrid";
@@ -344,4 +364,6 @@
 		case TemperatureOldEnum : return "TemperatureOld";
 		case TemperaturePicardEnum : return "TemperaturePicard";
+		case TemperatureSurfaceEnum : return "TemperatureSurface";
+		case TemperatureBasalEnum : return "TemperatureBasal";
 		case ThicknessAbsMisfitEnum : return "ThicknessAbsMisfit";
 		case TypeEnum : return "Type";
@@ -365,4 +387,6 @@
 		case EnthalpyPicardEnum : return "EnthalpyPicard";
 		case ThicknessAbsGradientEnum : return "ThicknessAbsGradient";
+		case ThicknessAlongGradientEnum : return "ThicknessAlongGradient";
+		case ThicknessAcrossGradientEnum : return "ThicknessAcrossGradient";
 		case StepResponsesEnum : return "StepResponses";
 		case IntMatParamEnum : return "IntMatParam";
@@ -385,5 +409,4 @@
 		case StressTensoryzEnum : return "StressTensoryz";
 		case StressTensorzzEnum : return "StressTensorzz";
-		case IceVolumeEnum : return "IceVolume";
 		case P0Enum : return "P0";
 		case P1Enum : return "P1";
@@ -419,4 +442,6 @@
 		case MaxVzEnum : return "MaxVz";
 		case MaxAbsVzEnum : return "MaxAbsVz";
+		case IceVolumeEnum : return "IceVolume";
+		case TotalSmbEnum : return "TotalSmb";
 		case RelativeEnum : return "Relative";
 		case AbsoluteEnum : return "Absolute";
@@ -458,4 +483,5 @@
 		case XYZPEnum : return "XYZP";
 		case OptionEnum : return "Option";
+		case GenericOptionEnum : return "GenericOption";
 		case OptionCellEnum : return "OptionCell";
 		case OptionCharEnum : return "OptionChar";
Index: /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 13395)
@@ -55,5 +55,5 @@
 
 	if (!DomainOutlineRead(&nprof,&pnvert,&pprofx,&pprofy,&closed,filexp))
-		_error2_("Error reading exp file.");
+		_error_("Error reading exp file.");
 	_pprintLine_("Exp2Kmlx -- Reading " << nprof << " exp profiles from file \"" << filexp << "\".");
 //	for (i=0; i<nprof; i++)
Index: /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.h
===================================================================
--- /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.h	(revision 13395)
@@ -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/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void	GetSolutionFromInputsx( Vector** psolution, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters){
+void	GetSolutionFromInputsx( Vector<IssmDouble>** psolution, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters){
 
 	/*intermediary: */
@@ -19,5 +19,5 @@
 
 	/*output: */
-	Vector* solution=NULL;
+	Vector<IssmDouble>* solution=NULL;
 
 	/*retrive parameters: */
@@ -26,8 +26,8 @@
 	/*Get size of vector: */
 	gsize=nodes->NumberOfDofs(configuration_type,GsetEnum);
-	if (gsize==0) _error2_("Allocating a Vec of size 0 as gsize=0 for configuration: " << EnumToStringx(configuration_type));
+	if (gsize==0) _error_("Allocating a Vec of size 0 as gsize=0 for configuration: " << EnumToStringx(configuration_type));
 	
 	/*Initialize solution: */
-	solution=new Vector(gsize);
+	solution=new Vector<IssmDouble>(gsize);
 	
 	/*Go through elements and plug solution: */
Index: /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 13395)
@@ -6,9 +6,9 @@
 #define _GETSOLUTIONFROMINPUTSXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 /* local prototypes: */
-void GetSolutionFromInputsx( Vector** psolution, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
+void GetSolutionFromInputsx( Vector<IssmDouble>** psolution, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
 
 #endif  /* _GETSOLUTIONFROMINPUTSXX_H */
Index: /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 13395)
@@ -9,9 +9,9 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void GetVectorFromControlInputsx(Vector** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,const char* data){
+void GetVectorFromControlInputsx(Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,const char* data){
 
 	int  num_controls;
 	int *control_type = NULL;
-	Vector*  vector=NULL;
+	Vector<IssmDouble>*  vector=NULL;
 
 	/*Retrieve some parameters*/
@@ -20,5 +20,5 @@
 
 	/*Allocate and populate gradient*/
-	vector=new Vector(num_controls*vertices->NumberOfVertices());
+	vector=new Vector<IssmDouble>(num_controls*vertices->NumberOfVertices());
 
 	for(int i=0;i<num_controls;i++){
@@ -36,11 +36,11 @@
 }
 
-void GetVectorFromControlInputsx( double** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){
+void GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){
 	
 	/*output: */
-	double* vector=NULL;
+	IssmDouble* vector=NULL;
 	
 	/*intermediary: */
-	Vector* vec_vector=NULL;
+	Vector<IssmDouble>* vec_vector=NULL;
 
 	GetVectorFromControlInputsx( &vec_vector, elements,nodes, vertices, loads, materials, parameters,data);
Index: /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 13395)
@@ -5,10 +5,10 @@
 #define _GETVECTORFROMCONTROLINPUTSXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 /* local prototypes: */
-void	GetVectorFromControlInputsx( Vector** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
-void	GetVectorFromControlInputsx( double** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
+void	GetVectorFromControlInputsx( Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
+void	GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
 
 #endif  /* _GETVECTORFROMCONTROLINPUTSXX_H */
Index: /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 13395)
@@ -9,13 +9,13 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void GetVectorFromInputsx( Vector** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name, int type){
+void GetVectorFromInputsx( Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name, int type){
 
 	int i;
-	Vector* vector=NULL;
+	Vector<IssmDouble>* vector=NULL;
 
 	if(type==VertexEnum){
 
 		/*Allocate vector*/
-		vector=new Vector(vertices->NumberOfVertices());
+		vector=new Vector<IssmDouble>(vertices->NumberOfVertices());
 
 		/*Look up in elements*/
@@ -32,5 +32,5 @@
 	}
 	else{
-		_error2_("vector type: " << EnumToStringx(type) << " not supported yet!");
+		_error_("vector type: " << EnumToStringx(type) << " not supported yet!");
 	}
 
@@ -47,5 +47,5 @@
 	
 	/*intermediary: */
-	Vector* vec_vector=NULL;
+	Vector<IssmDouble>* vec_vector=NULL;
 
 	GetVectorFromInputsx( &vec_vector, elements,nodes, vertices, loads, materials, parameters, name, type);
Index: /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 13395)
@@ -5,9 +5,9 @@
 #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( Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name,int type);
 void	GetVectorFromInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name,int type);
 
Index: /issm/trunk/src/c/modules/Gradjx/Gradjx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Gradjx/Gradjx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Gradjx/Gradjx.cpp	(revision 13395)
@@ -10,13 +10,13 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void Gradjx(Vector** pgradient,double** pnorm_list, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
+void Gradjx(Vector<IssmDouble>** pgradient,IssmDouble** pnorm_list, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters){
 
 	int     i,j,numberofvertices;
 	int     num_controls;
-	double   norm_inf;
-	double  *norm_list     = NULL;
+	IssmDouble   norm_inf;
+	IssmDouble  *norm_list     = NULL;
 	int     *control_type  = NULL;
-	Vector  *gradient      = NULL;
-	Vector **gradient_list = NULL;
+	Vector<IssmDouble>  *gradient      = NULL;
+	Vector<IssmDouble> **gradient_list = NULL;
 	
 	/*retrieve some parameters: */
@@ -26,10 +26,10 @@
 
 	/*Allocate gradient_list */
-	gradient_list = xNew<Vector*>(num_controls);
-	norm_list = xNew<double>(num_controls);
+	gradient_list = xNew<Vector<IssmDouble>*>(num_controls);
+	norm_list = xNew<IssmDouble>(num_controls);
 	for(i=0;i<num_controls;i++){
-		gradient_list[i]=new Vector(num_controls*numberofvertices);
+		gradient_list[i]=new Vector<IssmDouble>(num_controls*numberofvertices);
 	}
-	gradient=new Vector(num_controls*numberofvertices);
+	gradient=new Vector<IssmDouble>(num_controls*numberofvertices);
 
 	/*Compute all gradient_list*/
@@ -54,6 +54,6 @@
 	/*Check that gradient is clean*/
 	norm_inf=gradient->Norm(NORM_INF);
-	if(norm_inf<=0)    _error2_("||∂J/∂α||∞ = 0    gradient norm is zero");
-	if(xIsNan<IssmDouble>(norm_inf))_error2_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
+	if(norm_inf<=0)    _error_("||∂J/∂α||∞ = 0    gradient norm is zero");
+	if(xIsNan<IssmDouble>(norm_inf))_error_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
 
 	/*Clean-up and assign output pointer*/
@@ -62,8 +62,8 @@
 	}
 	else{
-		xDelete<double>(norm_list);
+		xDelete<IssmDouble>(norm_list);
 	}
 	if(pgradient)  *pgradient=gradient;
-	xDelete<Vector*>(gradient_list);
+	xDelete<Vector<IssmDouble>*>(gradient_list);
 	xDelete<int>(control_type);
 }
Index: /issm/trunk/src/c/modules/Gradjx/Gradjx.h
===================================================================
--- /issm/trunk/src/c/modules/Gradjx/Gradjx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Gradjx/Gradjx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void Gradjx(Vector** pgrad_g,double** pgrad_norm,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters);
+void Gradjx(Vector<IssmDouble>** pgrad_g,IssmDouble** pgrad_norm,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters);
 
 #endif  /* _GRADJX_H */
Index: /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 13395)
@@ -14,8 +14,8 @@
 
 	int      i, migration_style,analysis_type;
-	double*  vertices_potentially_ungrounding = NULL;
-	double*  vertices_ungrounding             = NULL;
-	double*  old_floatingice                  = NULL;
-	Vector*      vec_old_floatingice              = NULL;
+	IssmDouble*  vertices_potentially_ungrounding = NULL;
+	IssmDouble*  vertices_ungrounding             = NULL;
+	IssmDouble*  old_floatingice                  = NULL;
+	Vector<IssmDouble>*      vec_old_floatingice              = NULL;
 	Element* element                          = NULL;
 	
@@ -27,5 +27,5 @@
 
 	if(migration_style==NoneEnum) return;
-	if(migration_style!=AgressiveMigrationEnum && migration_style!=SoftMigrationEnum) _error2_(EnumToStringx(migration_style) << " not supported yet!");
+	if(migration_style!=AgressiveMigrationEnum && migration_style!=SoftMigrationEnum) _error_(EnumToStringx(migration_style) << " not supported yet!");
 
 	if(migration_style==SoftMigrationEnum){
@@ -49,19 +49,19 @@
 	/*free ressouces: */
 	xdelete(&vec_old_floatingice);
-	xDelete<double>(vertices_potentially_ungrounding);
-	xDelete<double>(vertices_ungrounding);
-	xDelete<double>(old_floatingice);
+	xDelete<IssmDouble>(vertices_potentially_ungrounding);
+	xDelete<IssmDouble>(vertices_ungrounding);
+	xDelete<IssmDouble>(old_floatingice);
 }
 
 /*FUNCTION CreateNodesOnFloatingIce {{{*/
-Vector* CreateNodesOnFloatingIce(Nodes* nodes,int configuration_type){ 
+Vector<IssmDouble>* CreateNodesOnFloatingIce(Nodes* nodes,int configuration_type){ 
 
 	int     i,numnods;
-	Vector*   vec_nodes_on_floatingice = NULL;
+	Vector<IssmDouble>*   vec_nodes_on_floatingice = NULL;
 	Node *node                     = NULL;
 
 	/*First, initialize nodes_on_floatingice, which will track which nodes have changed status: */
 	numnods=nodes->NumberOfNodes(configuration_type);
-	vec_nodes_on_floatingice=new Vector(numnods);
+	vec_nodes_on_floatingice=new Vector<IssmDouble>(numnods);
 
 	/*Loop through nodes, and fill vec_nodes_on_floatingice: */
@@ -82,14 +82,14 @@
 /*%}}}*/
 /*FUNCTION PotentialSheetUngrounding {{{*/
-double*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters){ 
+IssmDouble*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters){ 
 
 	int      i,numberofvertices;
-	double*  vertices_potentially_ungrounding      = NULL;
-	Vector*      vec_vertices_potentially_ungrounding  = NULL;
+	IssmDouble*  vertices_potentially_ungrounding      = NULL;
+	Vector<IssmDouble>*      vec_vertices_potentially_ungrounding  = NULL;
 	Element* element                               = NULL;
 
 	/*Initialize vector with number of vertices*/
 	numberofvertices=vertices->NumberOfVertices();
-	vec_vertices_potentially_ungrounding=new Vector(numberofvertices); //grounded vertex that could start floating
+	vec_vertices_potentially_ungrounding=new Vector<IssmDouble>(numberofvertices); //grounded vertex that could start floating
 
 	/*Fill vector vertices_potentially_floating: */
@@ -109,13 +109,13 @@
 /*}}}*/
 /*FUNCTION PropagateFloatingiceToGroundedNeighbors {{{*/
-double*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,double* vertices_potentially_ungrounding){ 
+IssmDouble*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,IssmDouble* vertices_potentially_ungrounding){ 
 
 	int      i,analysis_type;
 	int      numberofvertices;
 	int      nflipped,local_nflipped;
-	double*  nodes_on_floatingice                  = NULL;
-	double*  elements_neighboring_floatingce      = NULL;
-	Vector*      vec_elements_neighboring_floatingice = NULL;
-	Vector*      vec_nodes_on_floatingice              = NULL;
+	IssmDouble*  nodes_on_floatingice                  = NULL;
+	IssmDouble*  elements_neighboring_floatingce      = NULL;
+	Vector<IssmDouble>*      vec_elements_neighboring_floatingice = NULL;
+	Vector<IssmDouble>*      vec_nodes_on_floatingice              = NULL;
 	Node*    node                                  = NULL;
 	Element* element                               = NULL;
@@ -134,5 +134,5 @@
 		
 		/*Vector of size number of elements*/
-		vec_elements_neighboring_floatingice=new Vector(elements->NumberOfElements(),true);
+		vec_elements_neighboring_floatingice=new Vector<IssmDouble>(elements->NumberOfElements(),true);
 
 		/*Figure out if any of the nodes of the element will be floating -> elements neighbouting the floating ice*/
@@ -150,5 +150,5 @@
 		for(i=0;i<elements->Size();i++){
 			element=(Element*)elements->GetObjectByOffset(i);
-			if(elements_neighboring_floatingce[element->Sid()]){
+			if(reCast<int,IssmDouble>(elements_neighboring_floatingce[element->Sid()])){
 				local_nflipped+=element->UpdatePotentialSheetUngrounding(vertices_potentially_ungrounding,vec_nodes_on_floatingice,nodes_on_floatingice);
 			}
@@ -164,6 +164,6 @@
 
 		/*Avoid leaks: */
-		xDelete<double>(elements_neighboring_floatingce);
-		xDelete<double>(nodes_on_floatingice);
+		xDelete<IssmDouble>(elements_neighboring_floatingce);
+		xDelete<IssmDouble>(nodes_on_floatingice);
 
 		/*Assemble and serialize:*/
@@ -174,5 +174,5 @@
 	/*Free ressources:*/
 	xdelete(&vec_nodes_on_floatingice);
-	xDelete<double>(elements_neighboring_floatingce);
+	xDelete<IssmDouble>(elements_neighboring_floatingce);
 
 	return nodes_on_floatingice;
Index: /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h
===================================================================
--- /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h	(revision 13395)
@@ -14,6 +14,6 @@
 void       GroundinglineMigrationx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters);
 
-Vector*        CreateNodesOnFloatingIce(Nodes* nodes,int configuration_type);
-double*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters);
-double*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,double* vertices_potentially_ungrounding);
+Vector<IssmDouble>*        CreateNodesOnFloatingIce(Nodes* nodes,int configuration_type);
+IssmDouble*    PotentialSheetUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters);
+IssmDouble*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,IssmDouble* vertices_potentially_ungrounding);
 #endif  /* _GROUNDINGLINEMIGRATIONX_H */
Index: /issm/trunk/src/c/modules/IceVolumex/IceVolumex.cpp
===================================================================
--- /issm/trunk/src/c/modules/IceVolumex/IceVolumex.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/IceVolumex/IceVolumex.cpp	(revision 13395)
@@ -10,8 +10,8 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void IceVolumex(double* pV, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void IceVolumex(IssmDouble* pV, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 
-	double local_ice_volume = 0;
-	double total_ice_volume;
+	IssmDouble local_ice_volume = 0;
+	IssmDouble total_ice_volume;
 
 	for(int i=0;i<elements->Size();i++){
Index: /issm/trunk/src/c/modules/IceVolumex/IceVolumex.h
===================================================================
--- /issm/trunk/src/c/modules/IceVolumex/IceVolumex.h	(revision 13394)
+++ /issm/trunk/src/c/modules/IceVolumex/IceVolumex.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void IceVolumex(double* pV, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void IceVolumex(IssmDouble* pV, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif
Index: /issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.h
===================================================================
--- /issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.h	(revision 13394)
+++ /issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _INPUTARTIFICIALNOISEX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,double scalar,bool save_parameter){
+void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,IssmDouble scalar,bool save_parameter){
 
 	/*Go through elemnets, and ask to carry out the operation on inputs: */
Index: /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.h
===================================================================
--- /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.h	(revision 13394)
+++ /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.h	(revision 13395)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters, double scalar,bool save_parameter);
+void InputControlUpdatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters, IssmDouble scalar,bool save_parameter);
 
 #endif 
Index: /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _UPDATEINPUTSFROMCONSTANTXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 13395)
@@ -95,8 +95,8 @@
 		}
 		else if (strncmp(descriptor,"indexed_",8)==0){
-			_error2_("indexed variables not supported yet!");
+			_error_("indexed variables not supported yet!");
 		}
 		else if (strncmp(descriptor,"nodal_",8)==0){
-			_error2_("nodal variables not supported yet!");
+			_error_("nodal variables not supported yet!");
 		}
 		else{
Index: /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 13394)
+++ /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _INPUTUPDATEFROMDAKOTAXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 13394)
+++ /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _UPDATEINPUTSFROMMATRIXDAKOTAXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-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,Vector<IssmDouble>* solution){
 
 	IssmDouble* serial_solution=NULL;
Index: /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 13395)
@@ -6,13 +6,13 @@
 #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,Vector<IssmDouble>* solution);
 void        InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* solution);
 
 //with timestep
-void		InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector* solution,int timestep);
+void		InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector<IssmDouble>* solution,int timestep);
 void        InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* solution, int timestep);
 
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector* vector, int name, int type){
+void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* vector, int name, int type){
 
 	double* serial_vector=NULL;
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 13394)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 13395)
@@ -6,9 +6,9 @@
 #define _UPDATEINPUTSFROMVECTORDAKOTAXX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 /* local prototypes: */
-void	InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector* vector, int name,int type);
+void	InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector<IssmDouble>* vector, int name,int type);
 void	InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,double* vector, int name,int type);
 void	InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int* vector, int name,int type);
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-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,Vector<IssmDouble>* vector, int name, int type){
 
 	IssmDouble* serial_vector=NULL;
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 13395)
@@ -6,9 +6,9 @@
 #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,Vector<IssmDouble>* vector, int name,int type);
 void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,IssmDouble* vector, int name,int type);
 void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int* vector, int name,int type);
Index: /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 13395)
@@ -17,8 +17,8 @@
 
 /*InterpFromGridToMeshx{{{*/
-int InterpFromGridToMeshx( Vector** pdata_mesh,double* x_in, int x_rows, double* y_in, int y_rows, double* data, int M, int N, double* x_mesh, double* y_mesh, int nods,double default_value, int interpenum){
+int InterpFromGridToMeshx(SeqVec<IssmPDouble>** pdata_mesh,double* x_in, int x_rows, double* y_in, int y_rows, double* data, int M, int N, double* x_mesh, double* y_mesh, int nods,double default_value, int interpenum){
 
 	/*output: */
-	Vector* data_mesh=NULL;
+	SeqVec<IssmPDouble>* data_mesh=NULL;
 	
 	/*Intermediary*/
@@ -37,15 +37,15 @@
 	/*Some checks on arguments: */
 	if ((M<2) || (N<2) || (nods<=0)){
-		_error2_("nothing to be done according to the dimensions of input matrices and vectors.");
+		_error_("nothing to be done according to the dimensions of input matrices and vectors.");
 	}
 	if (x_in[1]-x_in[0]<0){
-		_error2_("x coordinate vector should be increasing.\n   use Matlab's command x=flipud(x), also flip the data matrix data=fliplr(data)");
+		_error_("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){
-		_error2_("y coordinate vector should be increasing.\n   use Matlab's command y=flipud(y), also flip the data matrix data=flipud(data)");
+		_error_("y coordinate vector should be increasing.\n   use Matlab's command y=flipud(y), also flip the data matrix data=flipud(data)");
 	}
 
 	/*Allocate output vector: */
-	data_mesh=new Vector(nods);
+	data_mesh=new SeqVec<IssmPDouble>(nods);
 
 	/*Find out what kind of coordinates (x_in,y_in) have been given is input*/
@@ -69,5 +69,5 @@
 	}
 	else{
-		_error2_("x and y vectors length should be 1 or 0 more than data number of rows.");
+		_error_("x and y vectors length should be 1 or 0 more than data number of rows.");
 	}
 
@@ -120,17 +120,17 @@
 
 	/*recover parameters :*/
-	double *x_mesh        = gate->x_mesh;
-	double *y_mesh        = gate->y_mesh;
-	int     x_rows        = gate->x_rows;
-	int     y_rows        = gate->y_rows;
-	double *x             = gate->x;
-	double *y             = gate->y;
-	int     nods          = gate->nods;
-	Vector *data_mesh     = gate->data_mesh;
-	double *data          = gate->data;
-	double  default_value = gate->default_value;
-	int     interpenum    = gate->interp;
-	int     M             = gate->M;
-	int     N             = gate->N;
+	double *x_mesh                = gate->x_mesh;
+	double *y_mesh                = gate->y_mesh;
+	int     x_rows                = gate->x_rows;
+	int     y_rows                = gate->y_rows;
+	double *x                     = gate->x;
+	double *y                     = gate->y;
+	int     nods                  = gate->nods;
+	SeqVec<IssmPDouble>*data_mesh = gate->data_mesh;
+	double *data                  = gate->data;
+	double  default_value         = gate->default_value;
+	int     interpenum            = gate->interp;
+	int     M                     = gate->M;
+	int     N                     = gate->N;
 
 	bool debug = M*N>1? true:false;
@@ -181,5 +181,5 @@
 					return NULL; /*WARNING: no error because it would blow up the multithreading!*/
 			}
-			if(xIsNan<IssmDouble>(data_value)) data_value=default_value;
+			if(xIsNan<IssmPDouble>(data_value)) data_value=default_value;
 		}
 		else{
Index: /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h
===================================================================
--- /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _INTERPFROMGRIDTOMESHX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../toolkits/toolkits.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
@@ -12,20 +12,20 @@
 /*threading: */
 typedef struct{
-	double* x;
-	int     x_rows;
-	double* y;
-	int     y_rows;
-	double* data;
-	double  default_value;
-	int     interp;
-	int     M;
-	int     N;
-	int     nods;
-	double* x_mesh;
-	double* y_mesh;
-	Vector*     data_mesh;
+	double*             x;
+	int                 x_rows;
+	double*             y;
+	int                 y_rows;
+	double*             data;
+	double              default_value;
+	int                 interp;
+	int                 M;
+	int                 N;
+	int                 nods;
+	double*             x_mesh;
+	double*             y_mesh;
+	SeqVec<IssmPDouble>* data_mesh;
 } InterpFromGridToMeshxThreadStruct;
 
-int    InterpFromGridToMeshx( Vector** pdata_mesh,double* x, int x_rows, double* y, int y_rows, double* data, int M, int N, double* x_mesh, double* y_mesh, int nods, double default_value, int interpenum=BilinearInterpEnum);
+int    InterpFromGridToMeshx(SeqVec<IssmPDouble>** pdata_mesh,double* x, int x_rows, double* y, int y_rows, double* data, int M, int N, double* x_mesh, double* y_mesh, int nods, double default_value, int interpenum=BilinearInterpEnum);
 void*  InterpFromGridToMeshxt(void* vInterpFromGridToMeshxThreadStruct);
 bool   findindices(int* pn,int* pm,double* x,int x_rows, double* y,int y_rows, double xgrid,double ygrid);
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 13395)
@@ -7,18 +7,19 @@
 #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){
-
+int InterpFromMesh2dx(SeqVec<IssmPDouble>** pdata_prime,
+			double* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length,
+			double* x_prime, double* y_prime, int nods_prime,
+			double* default_values,int num_default_values,Contour<IssmPDouble>** contours,int numcontours){
 	
 	/*Output*/
-	Vector* data_prime=NULL;
+	SeqVec<IssmPDouble>* data_prime=NULL;
 
 	/*Intermediary*/
-	int i,j;
-	int interpolation_type;
-	bool debug;
+	int    i,j;
+	int    interpolation_type;
+	bool   debug;
 	double area;
 	double area_1,area_2,area_3;
@@ -28,6 +29,6 @@
 
 	/*contours: */
-	Vector*    vec_incontour=NULL;
-	double*    incontour=NULL;
+	SeqVec<IssmPDouble> *vec_incontour = NULL;
+	double              *incontour     = NULL;
 
 	/*threading: */
@@ -41,5 +42,5 @@
 	/*some checks*/
 	if (nels_data<1 || nods_data<3 || nods_prime==0){
-		_error2_("nothing to be done according to the mesh given in input");
+		_error_("nothing to be done according to the mesh given in input");
 	}
 
@@ -55,9 +56,9 @@
 	}
 	else{
-		_error2_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
+		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
 	}
 
 	if((numcontours) && (interpolation_type==2)){
-		_error2_("element interpolation_type with contours not supported yet!");
+		_error_("element interpolation_type with contours not supported yet!");
 	}
 
@@ -72,5 +73,5 @@
 
 	/*Initialize output*/
-	data_prime=new Vector(nods_prime);
+	data_prime=new SeqVec<IssmPDouble>(nods_prime);
 	if(num_default_values){
 		if(num_default_values==1)for (i=0;i<nods_prime;i++) data_prime->SetValue(i,default_values[0],INS_VAL);
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 13395)
@@ -6,36 +6,34 @@
 #define _INTERPFROMMESH2DX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../toolkits/toolkits.h"
-
 
 /*threading: */
 typedef struct{
 
-	int interpolation_type;
-	bool debug;
-	int  nels_data;
-	double* index_data;
-	double* x_data;
-	double* y_data;
-	double* data;
-	double xmin,xmax;
-	double ymin,ymax;
-	int    nods_prime;
-	Vector*    data_prime;
-	double* x_prime;
-	double* y_prime;
-	double* default_values;
-	int     num_default_values;
-	double*    incontour;
+	int                 interpolation_type;
+	bool                debug;
+	int                 nels_data;
+	double              *index_data;
+	double              *x_data;
+	double              *y_data;
+	double              *data;
+	double              xmin,xmax;
+	double              ymin,ymax;
+	int                 nods_prime;
+	SeqVec<IssmPDouble> *data_prime;
+	double              *x_prime;
+	double              *y_prime;
+	double              *default_values;
+	int                 num_default_values;
+	double              *incontour;
 
 
 } InterpFromMesh2dxThreadStruct;
 
-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);
+int InterpFromMesh2dx(SeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, int nods_prime,
+		double* default_values,int num_default_values,Contour<IssmPDouble>** contours,int numcontours);
 
 void* InterpFromMesh2dxt(void* vInterpFromMesh2dxThreadStruct);
 
 #endif /* _INTERPFROMMESH2DX_H */
-
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 13395)
@@ -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;
+	SeqVec<IssmPDouble>* 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,5 +43,5 @@
 
 	/*Loop over the elements*/
-	for (i=i0;i<i1;i++){
+	for(i=i0;i<i1;i++){
 
 		/*display current iteration*/
@@ -113,5 +87,5 @@
 						data_value=data[i];
 					}
-					if (xIsNan<IssmDouble>(data_value)){
+					if (xIsNan<IssmPDouble>(data_value)){
 						if(num_default_values==1) data_value=default_values[0];
 						else data_value=default_values[j];
Index: /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 13395)
@@ -30,5 +30,5 @@
 	/*some checks*/
 	if (nels<1 || nods<3 || nlines<1 || ncols<1 || xposting==0 || yposting==0){
-		_error2_("nothing to be done according to the mesh given in input");
+		_error_("nothing to be done according to the mesh given in input");
 	}
 
@@ -41,5 +41,5 @@
 	}
 	else{
-		_error2_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
+		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
 	}
 
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 13395)
@@ -7,5 +7,5 @@
 #include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../modules.h"
 
@@ -20,4 +20,5 @@
 
 	/*Intermediary*/
+	double xmin,xmax,ymin,ymax;
 	bool   isdefault;
 	double defaultvalue;
@@ -34,5 +35,5 @@
 	/*Checks*/
 	if (M_data!=nods_data && M_data!=nels_data){
-		_error2_("data provided should have either " << nods_data << " or " << nels_data << " lines (not " << M_data << ")");
+		_error_("data provided should have either " << nods_data << " or " << nels_data << " lines (not " << M_data << ")");
 	}
 
@@ -57,6 +58,24 @@
 	Th.CreateSingleVertexToTriangleConnectivity();
 
+	/*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];
+	}
+
 	/*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;
+			}
+		}
 
 		/*Get current point coordinates*/
@@ -119,5 +138,5 @@
 			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");
+					_error_("Triangle number " << it << " not in [0 " << nels_data << "], report bug to developers");
 				}
 				data_interp[i*N_data+j]=data[N_data*it+j];
@@ -125,4 +144,5 @@
 		}
 	}
+	//if(N_interp>=100) _printLine_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
 
 	/*clean-up and return*/
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _INTERPFROMMESHTOMESH2DX_H
 
-class Options;
+#include "../../classes/classes.h"
 
 int InterpFromMeshToMesh2dx(double** pdata_interp,int* index_data,double* x_data,double* y_data,int nods_data,int nels_data,
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 13395)
@@ -7,8 +7,8 @@
 #include "../../include/include.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) {
+int InterpFromMeshToMesh3dx( SeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, double* z_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, double* z_prime, int nods_prime,double default_value) {
 
 	/*Output*/
-	Vector* data_prime=NULL;
+	SeqVec<IssmPDouble>* data_prime=NULL;
 
 	/*Intermediary*/
@@ -27,5 +27,5 @@
 	/*some checks*/
 	if (nels_data<1 || nods_data<6 || nods_prime==0){
-		_error2_("nothing to be done according to the mesh given in input");
+		_error_("nothing to be done according to the mesh given in input");
 	}
 
@@ -41,5 +41,5 @@
 	}
 	else{
-		_error2_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
+		_error_("length of vector data not supported yet. It should be of length (number of nodes) or (number of elements)!");
 	}
 
@@ -54,5 +54,5 @@
 
 	/*Initialize output*/
-	data_prime=new Vector(nods_prime);
+	data_prime=new SeqVec<IssmPDouble>(nods_prime);
 	for (i=0;i<nods_prime;i++) data_prime->SetValue(i,default_value,INS_VAL);
 
@@ -124,5 +124,5 @@
 						data_value=data[i];
 					}
-					if (xIsNan<IssmDouble>(data_value)) data_value=default_value;
+					if (xIsNan<IssmPDouble>(data_value)) data_value=default_value;
 
 					/*insert value and go to the next point*/
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h	(revision 13395)
@@ -7,8 +7,7 @@
 
 #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);
+int InterpFromMeshToMesh3dx(SeqVec<IssmPDouble>** pdata_prime,double* index_data, double* x_data, double* y_data, double* z_data, int nods_data,int nels_data, double* data, int data_length, double* x_prime, double* y_prime, double* z_prime, int nods_prime,double default_value);
 
 #endif /* _INTERPFROMMESHTOMESH3DX_H */
-
Index: /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 13395)
@@ -38,6 +38,6 @@
 	fid=iomodel->SetFilePointerToData(&code, &vector_layout,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));
+	if(code!=7)_error_("expecting a IssmDouble vector for constraints with enum " << EnumToStringx(vector_enum));
+	if(vector_layout!=1)_error_("expecting a nodal vector for constraints with enum " << EnumToStringx(vector_enum));
 
 	/*Fetch vector:*/
@@ -99,5 +99,5 @@
 	}
 	else{
-		_error2_("Size of field " << EnumToStringx(vector_enum) << " not supported");
+		_error_("Size of field " << EnumToStringx(vector_enum) << " not supported");
 	}
 
Index: /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h	(revision 13395)
@@ -6,5 +6,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.h
===================================================================
--- /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.h	(revision 13395)
@@ -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/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp
===================================================================
--- /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp	(revision 13395)
@@ -133,5 +133,5 @@
 					}
 					else
-						_error2_("Nodal connectivity table needs more than specified " << mxepg << " columns.\n");
+						_error_("Nodal connectivity table needs more than specified " << mxepg << " columns.\n");
 				}
 				jpt++;
@@ -173,5 +173,5 @@
 
 		else
-			_error2_("Data matrix has incorrect number of " << mdata << " rows.\n");
+			_error_("Data matrix has incorrect number of " << mdata << " rows.\n");
 	}
 
Index: /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.h
===================================================================
--- /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.h	(revision 13394)
+++ /issm/trunk/src/c/modules/KMLMeshWritex/KMLMeshWritex.h	(revision 13395)
@@ -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/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.h
===================================================================
--- /issm/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.h	(revision 13395)
@@ -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/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 13395)
@@ -44,5 +44,5 @@
 	fidi=fopen(filkml,"r");
 	if (!(kobj=KMLFileReadx(fidi)))
-		_error2_("Error reading kml file.");
+		_error_("Error reading kml file.");
 	fclose(fidi);
 
Index: /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.h
===================================================================
--- /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.h	(revision 13395)
@@ -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/trunk/src/c/modules/Krigingx/Krigingx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp	(revision 13395)
@@ -7,5 +7,5 @@
 #include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Observations.h"
 #include "../modules.h"
@@ -48,5 +48,5 @@
 
 	/*Get output*/
-	options->Get(&output,"output","prediction");
+	options->Get(&output,"output",(char*)"prediction");
 
 	if(strcmp(output,"quadtree")==0){
@@ -96,4 +96,6 @@
 	}
 	else if(strcmp(output,"idw")==0){ //Inverse distance weighting
+		double power;
+		options->Get(&power,"power",2.);
 		/*initialize thread parameters: */
 		gate.n_interp     = n_interp;
@@ -108,4 +110,5 @@
 		gate.error        = error;
 		gate.percent      = xNewZeroInit<double>(num);
+		gate.power        = power;
 
 		/*launch the thread manager with Krigingxt as a core: */
@@ -135,5 +138,5 @@
 	}
 	else{
-		_error2_("output '" << output << "' not supported yet");
+		_error_("output '" << output << "' not supported yet");
 	}
 
@@ -270,8 +273,8 @@
 	double       *error        = gate->error;
 	double       *percent      = gate->percent;
+	double        power        = gate->power;
 
 	/*Intermediaries*/
 	double localpercent;
-	double  power = 2.;
 
 	/*partition loop across threads: */
@@ -302,5 +305,5 @@
 		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 _error_("variogram " << model << " not supported yet (list of supported variogram: gaussian, exponential, spherical and power)");
 	}
 	else variogram = new GaussianVariogram(options);
Index: /issm/trunk/src/c/modules/Krigingx/Krigingx.h
===================================================================
--- /issm/trunk/src/c/modules/Krigingx/Krigingx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Krigingx/Krigingx.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _KRIGINGX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../toolkits/toolkits.h"
 
@@ -29,4 +29,5 @@
 	double       *error;
 	double       *percent;
+	double        power;//for idw
 }KrigingxThreadStruct;
 
Index: /issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp	(revision 13395)
@@ -7,5 +7,5 @@
 #include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 #include "../../io/io.h"
@@ -41,5 +41,5 @@
 
 	/*Get output*/
-	options->Get(&output,"output","prediction");
+	options->Get(&output,"output",(char*)"prediction");
 
 	if(strcmp(output,"quadtree")==0){
@@ -56,8 +56,8 @@
 		/*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<<"%");
+			_pprintLine_("      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.<<"%");
+		_pprintLine_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
 
 #ifdef _HAVE_MPI_
@@ -74,8 +74,8 @@
 		/*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<<"%");
+			_pprintLine_("      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.<<"%");
+		_pprintLine_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
 
 #ifdef _HAVE_MPI_
@@ -91,8 +91,8 @@
 		/*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<<"%");
+			_pprintLine_("      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.<<"%");
+		_pprintLine_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%");
 
 #ifdef _HAVE_MPI_
@@ -103,5 +103,5 @@
 	}
 	else{
-		_error2_("output '" << output << "' not supported yet");
+		_error_("output '" << output << "' not supported yet");
 	}
 
@@ -126,5 +126,5 @@
 		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 _error_("variogram " << model << " not supported yet (list of supported variogram: gaussian, exponential, spherical and power)");
 	}
 	else variogram = new GaussianVariogram(options);
Index: /issm/trunk/src/c/modules/Ll2xyx/Ll2xyx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Ll2xyx/Ll2xyx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Ll2xyx/Ll2xyx.cpp	(revision 13395)
@@ -52,5 +52,5 @@
 	double  T,rho,sl,tc,mc;
 
-	if((sgn!=1) && (sgn!=-1)) _error2_("Sign should be either +1 or -1.\n");
+	if((sgn!=1) && (sgn!=-1)) _error_("Sign should be either +1 or -1.\n");
 
 	delta = central_meridian;
@@ -123,5 +123,5 @@
 		if(flag) _pprintLine_("Info: creating coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).");
 	}
-	else _error2_("Sign should be either +1 or -1.\n");
+	else _error_("Sign should be either +1 or -1.\n");
 
 	return;
Index: /issm/trunk/src/c/modules/MassFluxx/MassFluxx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MassFluxx/MassFluxx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MassFluxx/MassFluxx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MassFluxx(double* pmass_flux, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool process_units){
+void MassFluxx(IssmDouble* pmass_flux, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool process_units){
 
 	int i,j;
@@ -20,11 +20,11 @@
 	
 	/*output: */
-	double mass_flux=0;
-	double all_mass_flux=0;
+	IssmDouble mass_flux=0;
+	IssmDouble all_mass_flux=0;
 
 	int  counter;
 
 	/*all segments: */
-	double** array=NULL;
+	IssmDouble** array=NULL;
 	int      M;
 	int*     mdims_array=NULL;
@@ -32,5 +32,5 @@
 
 	/*our segments of interest: */
-	double*  segments=NULL;
+	IssmDouble*  segments=NULL;
 	int      num_segments;
 
@@ -48,5 +48,5 @@
 	 * When we find one, use the element to compute the mass flux on the segment: */
 	for(i=0;i<num_segments;i++){
-		element_id=(int)*(segments+5*i+4);
+		element_id=reCast<int,IssmDouble>(*(segments+5*i+4));
 		for(j=0;j<elements->Size();j++){
 			element=(Element*)elements->GetObjectByOffset(j);
@@ -66,10 +66,10 @@
 	/*Free ressources:*/
 	for(j=0;j<M;j++){
-		double* matrix=array[j];
-		xDelete<double>(matrix);
+		IssmDouble* matrix=array[j];
+		xDelete<IssmDouble>(matrix);
 	}
 	xDelete<int>(mdims_array);
 	xDelete<int>(ndims_array);
-	xDelete<double*>(array);
+	xDelete<IssmDouble*>(array);
 	
 	/*Assign output pointers: */
Index: /issm/trunk/src/c/modules/MassFluxx/MassFluxx.h
===================================================================
--- /issm/trunk/src/c/modules/MassFluxx/MassFluxx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MassFluxx/MassFluxx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MassFluxx(double* pmass_flux, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool process_units);
+void MassFluxx(IssmDouble* pmass_flux, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,bool process_units);
 
 
Index: /issm/trunk/src/c/modules/MaxAbsVxx/MaxAbsVxx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MaxAbsVxx/MaxAbsVxx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxAbsVxx/MaxAbsVxx.cpp	(revision 13395)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxAbsVxx( double* pmaxabsvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxAbsVxx( IssmDouble* pmaxabsvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double maxabsvx;
-	double node_maxabsvx;
-	double element_maxabsvx;
+	IssmDouble maxabsvx;
+	IssmDouble node_maxabsvx;
+	IssmDouble element_maxabsvx;
 
 	/*Go through elements, and request velocity: */
Index: /issm/trunk/src/c/modules/MaxAbsVxx/MaxAbsVxx.h
===================================================================
--- /issm/trunk/src/c/modules/MaxAbsVxx/MaxAbsVxx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxAbsVxx/MaxAbsVxx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MaxAbsVxx( double* pmaxabsvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxAbsVxx( IssmDouble* pmaxabsvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXABSVXX_H */
Index: /issm/trunk/src/c/modules/MaxAbsVyx/MaxAbsVyx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MaxAbsVyx/MaxAbsVyx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxAbsVyx/MaxAbsVyx.cpp	(revision 13395)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxAbsVyx( double* pmaxabsvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxAbsVyx( IssmDouble* pmaxabsvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double maxabsvy;
-	double node_maxabsvy;
-	double element_maxabsvy;
+	IssmDouble maxabsvy;
+	IssmDouble node_maxabsvy;
+	IssmDouble element_maxabsvy;
 
 
Index: /issm/trunk/src/c/modules/MaxAbsVyx/MaxAbsVyx.h
===================================================================
--- /issm/trunk/src/c/modules/MaxAbsVyx/MaxAbsVyx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxAbsVyx/MaxAbsVyx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MaxAbsVyx( double* pmaxabsvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxAbsVyx( IssmDouble* pmaxabsvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXABSVYX_H */
Index: /issm/trunk/src/c/modules/MaxAbsVzx/MaxAbsVzx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MaxAbsVzx/MaxAbsVzx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxAbsVzx/MaxAbsVzx.cpp	(revision 13395)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxAbsVzx( double* pmaxabsvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxAbsVzx( IssmDouble* pmaxabsvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double maxabsvz;
-	double node_maxabsvz;
-	double element_maxabsvz;
+	IssmDouble maxabsvz;
+	IssmDouble node_maxabsvz;
+	IssmDouble element_maxabsvz;
 
 	/*Go through elements, and request velocity: */
Index: /issm/trunk/src/c/modules/MaxAbsVzx/MaxAbsVzx.h
===================================================================
--- /issm/trunk/src/c/modules/MaxAbsVzx/MaxAbsVzx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxAbsVzx/MaxAbsVzx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MaxAbsVzx( double* pmaxabsvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxAbsVzx( IssmDouble* pmaxabsvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXABSVZX_H */
Index: /issm/trunk/src/c/modules/MaxVelx/MaxVelx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MaxVelx/MaxVelx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxVelx/MaxVelx.cpp	(revision 13395)
@@ -10,10 +10,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxVelx( double* pmaxvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxVelx( IssmDouble* pmaxvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double maxvel;
-	double node_maxvel;
-	double element_maxvel;
+	IssmDouble maxvel;
+	IssmDouble node_maxvel;
+	IssmDouble element_maxvel;
 
 	/*Go through elements, and request velocity: */
Index: /issm/trunk/src/c/modules/MaxVelx/MaxVelx.h
===================================================================
--- /issm/trunk/src/c/modules/MaxVelx/MaxVelx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxVelx/MaxVelx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MaxVelx( double* pmaxvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxVelx( IssmDouble* pmaxvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXVELX_H */
Index: /issm/trunk/src/c/modules/MaxVxx/MaxVxx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MaxVxx/MaxVxx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxVxx/MaxVxx.cpp	(revision 13395)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxVxx( double* pmaxvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxVxx( IssmDouble* pmaxvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double maxvx;
-	double node_maxvx;
-	double element_maxvx;
+	IssmDouble maxvx;
+	IssmDouble node_maxvx;
+	IssmDouble element_maxvx;
 
 	/*Go through elements, and request velocity: */
Index: /issm/trunk/src/c/modules/MaxVxx/MaxVxx.h
===================================================================
--- /issm/trunk/src/c/modules/MaxVxx/MaxVxx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxVxx/MaxVxx.h	(revision 13395)
@@ -6,8 +6,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MaxVxx( double* pmaxvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxVxx( IssmDouble* pmaxvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXVXX_H */
Index: /issm/trunk/src/c/modules/MaxVyx/MaxVyx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MaxVyx/MaxVyx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxVyx/MaxVyx.cpp	(revision 13395)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxVyx( double* pmaxvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxVyx( IssmDouble* pmaxvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 
 	int i;
-	double maxvy;
-	double node_maxvy;
-	double element_maxvy;
+	IssmDouble maxvy;
+	IssmDouble node_maxvy;
+	IssmDouble element_maxvy;
 
 	/*Go through elements, and request velocity: */
Index: /issm/trunk/src/c/modules/MaxVyx/MaxVyx.h
===================================================================
--- /issm/trunk/src/c/modules/MaxVyx/MaxVyx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxVyx/MaxVyx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MaxVyx( double* pmaxvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxVyx( IssmDouble* pmaxvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXVYX_H */
Index: /issm/trunk/src/c/modules/MaxVzx/MaxVzx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MaxVzx/MaxVzx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxVzx/MaxVzx.cpp	(revision 13395)
@@ -10,10 +10,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MaxVzx( double* pmaxvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MaxVzx( IssmDouble* pmaxvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double maxvz;
-	double node_maxvz;
-	double element_maxvz;
+	IssmDouble maxvz;
+	IssmDouble node_maxvz;
+	IssmDouble element_maxvz;
 
 	/*Go through elements, and request velocity: */
Index: /issm/trunk/src/c/modules/MaxVzx/MaxVzx.h
===================================================================
--- /issm/trunk/src/c/modules/MaxVzx/MaxVzx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MaxVzx/MaxVzx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MaxVzx( double* pmaxvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MaxVzx( IssmDouble* pmaxvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MAXVZX_H */
Index: /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp	(revision 13395)
@@ -7,8 +7,8 @@
 #include "./Mergesolutionfromftogx.h"
 
-void	Mergesolutionfromftogx( Vector** pug, Vector* uf, Vector* ys, Nodes* nodes, Parameters* parameters, bool flag_ys0){
+void	Mergesolutionfromftogx( Vector<IssmDouble>** pug, Vector<IssmDouble>* uf, Vector<IssmDouble>* ys, Nodes* nodes, Parameters* parameters, bool flag_ys0){
 
 	/*output: */
-	Vector* ug=NULL;
+	Vector<IssmDouble>* ug=NULL;
 
 	/*intermediary: */
@@ -34,5 +34,5 @@
 
 	/*initialize ug: */
-	ug=new Vector(gsize);
+	ug=new Vector<IssmDouble>(gsize);
 
 	/*Merge f set back into g set: */
Index: /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h
===================================================================
--- /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h	(revision 13395)
@@ -6,8 +6,8 @@
 #define _MERGESOLUTIONFROMFTOGX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void	Mergesolutionfromftogx( Vector** pug, Vector* uf, Vector* ys, Nodes* nodes, Parameters* parameters, bool flag_ys0=false);
+void	Mergesolutionfromftogx( Vector<IssmDouble>** pug, Vector<IssmDouble>* uf, Vector<IssmDouble>* ys, Nodes* nodes, Parameters* parameters, bool flag_ys0=false);
 
 #endif  /* _MERGESOLUTIONFROMFTOGX_H */
Index: sm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.cpp	(revision 13394)
+++ 	(revision )
@@ -1,115 +1,0 @@
-/*!\file:  MeshPartition.cpp
- * \brief partition elements and nodes across a cluster of size numprocs. 
- */
-
-#include "./MeshPartitionx.h"
-#include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../toolkits/toolkits.h"
-#include "../../EnumDefinitions/EnumDefinitions.h"
-
-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;
-	int i,j;
-
-	/*Metis partitioning: */
-	int* epart=NULL;
-	int* npart=NULL;
-	int* index=NULL;
-
-	int* epart2d=NULL;
-	int* npart2d=NULL;
-	int* index2d=NULL;
-	int  count=0;
-
-	int  etype=1; //tria mesh see metis/Programs/Io.c
-	int  etype2d=1; //tria mesh see metis/Programs/Io.c
-	int  numflag=0;
-	int  edgecut=1;
-
-	if(dim==2){
-		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)=reCast<int>(*(elements+elements_width*i+j))-1; //-1 for C indexing in Metis
-			}
-		}
-
-		/*Partition using Metis:*/
-		if (num_procs>1){
-			#ifdef _HAVE_METIS_
-			METIS_PartMeshNodalPatch(&numberofelements,&numberofnodes, index, &etype, &numflag, &num_procs, &edgecut, epart, npart);
-			#endif
-		}
-		else if (num_procs==1){
-			/*METIS does not know how to deal with one cpu only!*/
-			for (i=0;i<numberofelements;i++) epart[i]=0;
-			for (i=0;i<numberofnodes;i++)    npart[i]=0;
-		}
-		else _error2_("At least one processor is required");
-	}
-	else{
-		/*We have a 3d mesh, made of a regularly extruded 2d mesh. We first partition the 2d mesh, then we extrude the partition: */
-
-		/*First build concatenated 2d mesh  from 2d_coll and 2d_noncoll: */
-		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)=reCast<int>(*(elements2d+3*i+j))-1; //-1 for C indexing in Metis
-			}
-		}
-
-		/*Partition using Metis:*/
-		if (num_procs>1){
-			#ifdef _HAVE_METIS_
-			METIS_PartMeshNodalPatch(&numberofelements2d,&numberofnodes2d, index2d, &etype2d, &numflag, &num_procs, &edgecut, epart2d, npart2d);
-			#endif
-		}
-		else if (num_procs==1){
-			/*METIS does not know how to deal with one cpu only!*/
-			for (i=0;i<numberofelements2d;i++) epart2d[i]=0;
-			for (i=0;i<numberofnodes2d;i++)    npart2d[i]=0;
-		}
-		else _error2_("At least one processor is required");
-
-		/*Extrude epart2d to epart, using numlayers: */
-		epart=xNew<int>(numberofelements);
-		
-		count=0;
-		for(i=0;i<(numlayers-1);i++){
-			for(j=0;j<numberofelements2d;j++){
-				epart[count]=epart2d[j];
-				count++;
-			}
-		}
-
-		/*Extrude npart2d to npart, using numlayers: */
-		npart=xNew<int>(numberofnodes);
-		
-		count=0;
-		for(i=0;i<(numlayers);i++){
-			for(j=0;j<numberofnodes2d;j++){
-				npart[count]=npart2d[j];
-				count++;
-			}
-		}
-	}
-	
-	/*Assign output pointer:*/
-	*pepart=epart;
-	*pnpart=npart;
-
-	/*Free ressources: */
-	xDelete<int>(index);
-	xDelete<int>(epart2d);
-	xDelete<int>(npart2d);
-	xDelete<int>(index2d);
-	return noerr;
-}
Index: /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h
===================================================================
--- /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 13395)
@@ -7,9 +7,117 @@
 
 #include "../../include/include.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
 
 /* local prototypes: */
-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);
+template <class doubletype> 
+int MeshPartitionx(int** pepart, int** pnpart, int numberofelements,int numberofnodes,doubletype* elements,
+		int numberofelements2d,int numberofnodes2d,doubletype* elements2d,int numlayers,int elements_width, int dim,int num_procs){
+
+	int noerr=1;
+	int i,j;
+
+	/*Metis partitioning: */
+	int* epart=NULL;
+	int* npart=NULL;
+	int* index=NULL;
+
+	int* epart2d=NULL;
+	int* npart2d=NULL;
+	int* index2d=NULL;
+	int  count=0;
+
+	int  etype=1; //tria mesh see metis/Programs/Io.c
+	int  etype2d=1; //tria mesh see metis/Programs/Io.c
+	int  numflag=0;
+	int  edgecut=1;
+
+	if(dim==2){
+		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)=reCast<int>(*(elements+elements_width*i+j))-1; //-1 for C indexing in Metis
+			}
+		}
+
+		/*Partition using Metis:*/
+		if (num_procs>1){
+			#ifdef _HAVE_METIS_
+			METIS_PartMeshNodalPatch(&numberofelements,&numberofnodes, index, &etype, &numflag, &num_procs, &edgecut, epart, npart);
+			#else
+			_error_("metis has not beed installed. Cannot run with more than 1 cpu");
+			#endif
+		}
+		else if (num_procs==1){
+			/*METIS does not know how to deal with one cpu only!*/
+			for (i=0;i<numberofelements;i++) epart[i]=0;
+			for (i=0;i<numberofnodes;i++)    npart[i]=0;
+		}
+		else _error_("At least one processor is required");
+	}
+	else{
+		/*We have a 3d mesh, made of a regularly extruded 2d mesh. We first partition the 2d mesh, then we extrude the partition: */
+
+		/*First build concatenated 2d mesh  from 2d_coll and 2d_noncoll: */
+		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)=reCast<int>(*(elements2d+3*i+j))-1; //-1 for C indexing in Metis
+			}
+		}
+
+		/*Partition using Metis:*/
+		if (num_procs>1){
+			#ifdef _HAVE_METIS_
+			METIS_PartMeshNodalPatch(&numberofelements2d,&numberofnodes2d, index2d, &etype2d, &numflag, &num_procs, &edgecut, epart2d, npart2d);
+			#else
+			_error_("metis has not beed installed. Cannot run with more than 1 cpu");
+			#endif
+		}
+		else if (num_procs==1){
+			/*METIS does not know how to deal with one cpu only!*/
+			for (i=0;i<numberofelements2d;i++) epart2d[i]=0;
+			for (i=0;i<numberofnodes2d;i++)    npart2d[i]=0;
+		}
+		else _error_("At least one processor is required");
+
+		/*Extrude epart2d to epart, using numlayers: */
+		epart=xNew<int>(numberofelements);
+		
+		count=0;
+		for(i=0;i<(numlayers-1);i++){
+			for(j=0;j<numberofelements2d;j++){
+				epart[count]=epart2d[j];
+				count++;
+			}
+		}
+
+		/*Extrude npart2d to npart, using numlayers: */
+		npart=xNew<int>(numberofnodes);
+		
+		count=0;
+		for(i=0;i<(numlayers);i++){
+			for(j=0;j<numberofnodes2d;j++){
+				npart[count]=npart2d[j];
+				count++;
+			}
+		}
+	}
 	
+	/*Assign output pointer:*/
+	*pepart=epart;
+	*pnpart=npart;
+
+	/*Free ressources: */
+	xDelete<int>(index);
+	xDelete<int>(epart2d);
+	xDelete<int>(npart2d);
+	xDelete<int>(index2d);
+	return noerr;
+}	
 #endif /* _MESHPARTITIONX_H */
-
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp	(revision 13395)
@@ -38,5 +38,5 @@
 	if(    (edge1==IntersectEnum) && (edge2==IntersectEnum) && (edge3==IntersectEnum)   ){
 		/*This case is impossible: */
-		_error2_("error: a line cannot go through 3 different vertices!");
+		_error_("error: a line cannot go through 3 different vertices!");
 	}
 	else if(    ((edge1==IntersectEnum) && (edge2==IntersectEnum)) || ((edge2==IntersectEnum) && (edge3==IntersectEnum)) || ((edge3==IntersectEnum) && (edge1==IntersectEnum))   ){
@@ -55,5 +55,5 @@
 			yfinal[1]=ysegment[0]+coord2*(ysegment[1]-ysegment[0]);
 
-			segments_dataset->AddObject(new  Segment(el+1,xfinal[0],yfinal[0],xfinal[1],yfinal[1]));
+			segments_dataset->AddObject(new  Segment<double>(el+1,xfinal[0],yfinal[0],xfinal[1],yfinal[1]));
 		}
 		else{
@@ -83,10 +83,10 @@
 		yfinal[1]=ysegment[0]+coord2*(ysegment[1]-ysegment[0]);
 
-		segments_dataset->AddObject(new  Segment(el+1,xfinal[0],yfinal[0],xfinal[1],yfinal[1]));
+		segments_dataset->AddObject(new  Segment<double>(el+1,xfinal[0],yfinal[0],xfinal[1],yfinal[1]));
 	}
 	else{
 		/*No interesections, but the segment might be entirely inside this triangle!: */
 		if ( (NodeInElement(xnodes,ynodes,xsegment[0],ysegment[0])) && (NodeInElement(xnodes,ynodes,xsegment[1],ysegment[1])) ){
-			segments_dataset->AddObject(new  Segment(el+1,xsegment[0],ysegment[0],xsegment[1],ysegment[1]));
+			segments_dataset->AddObject(new  Segment<double>(el+1,xsegment[0],ysegment[0],xsegment[1],ysegment[1]));
 		}
 	}
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 13395)
@@ -4,5 +4,5 @@
 #include "./MeshProfileIntersectionx.h"
 
-void MeshProfileIntersectionx( double** psegments, int* pnumsegs, int* index, double* x, double* y, int nel, int nods,  Contour** contours,int numcontours){
+void MeshProfileIntersectionx( double** psegments, int* pnumsegs, int* index, double* x, double* y, int nel, int nods,  Contour<IssmPDouble>** contours,int numcontours){
 
 	int i,j,k;
@@ -10,5 +10,5 @@
 
 	/*Contour:*/
-	Contour* contouri=NULL;
+	Contour<IssmPDouble>* contouri=NULL;
 	int      numnodes;
 	double*  xc=NULL;
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 13395)
@@ -8,8 +8,8 @@
 
 #include "../../shared/shared.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MeshProfileIntersectionx( double** psegments, int* pnumseg, int* index, double* x, double* y, int nel, int nods,  Contour** contours,int numcontours);
+void MeshProfileIntersectionx( double** psegments, int* pnumseg, int* index, double* x, double* y, int nel, int nods,  Contour<IssmPDouble>** contours,int numcontours);
 void MeshSegmentsIntersection(double** psegments, int* pnumsegs,int* index, double* x, double* y, int nel, int nods, double* xc, double* yc, int numnodes);
 void ElementSegmentsIntersection(DataSet* segments_dataset,int el, double* xnodes,double* ynodes,double* xc,double* yc,int numnodes);
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 	/*output: */
 	double*  segments=NULL;
-	Segment* segment=NULL;
+	Segment<double>* segment=NULL;
 	int     numsegs;
 	
@@ -34,5 +34,5 @@
 	segments=xNew<double>(5*numsegs);
 	for(i=0;i<numsegs;i++){
-		Segment* segment=(Segment*)segments_dataset->GetObjectByOffset(i);
+		Segment<double>* segment=(Segment<double>*)segments_dataset->GetObjectByOffset(i);
 		
 		/*x1,y1,x2,y2 then element_id: */
Index: /issm/trunk/src/c/modules/MinVelx/MinVelx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MinVelx/MinVelx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MinVelx/MinVelx.cpp	(revision 13395)
@@ -10,10 +10,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MinVelx( double* pminvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MinVelx( IssmDouble* pminvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double minvel;
-	double node_minvel;
-	double element_minvel;
+	IssmDouble minvel;
+	IssmDouble node_minvel;
+	IssmDouble element_minvel;
 
 	/*Go through elements, and request velocity: */
Index: /issm/trunk/src/c/modules/MinVelx/MinVelx.h
===================================================================
--- /issm/trunk/src/c/modules/MinVelx/MinVelx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MinVelx/MinVelx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MinVelx( double* pminvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MinVelx( IssmDouble* pminvel, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MINVELX_H */
Index: /issm/trunk/src/c/modules/MinVxx/MinVxx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MinVxx/MinVxx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MinVxx/MinVxx.cpp	(revision 13395)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MinVxx( double* pminvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MinVxx( IssmDouble* pminvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double minvx;
-	double node_minvx;
-	double element_minvx;
+	IssmDouble minvx;
+	IssmDouble node_minvx;
+	IssmDouble element_minvx;
 
 	/*Go through elements, and request velocity: */
Index: /issm/trunk/src/c/modules/MinVxx/MinVxx.h
===================================================================
--- /issm/trunk/src/c/modules/MinVxx/MinVxx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MinVxx/MinVxx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MinVxx( double* pminvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MinVxx( IssmDouble* pminvx, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MINVX_H */
Index: /issm/trunk/src/c/modules/MinVyx/MinVyx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MinVyx/MinVyx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MinVyx/MinVyx.cpp	(revision 13395)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MinVyx( double* pminvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MinVyx( IssmDouble* pminvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double minvy;
-	double node_minvy;
-	double element_minvy;
+	IssmDouble minvy;
+	IssmDouble node_minvy;
+	IssmDouble element_minvy;
 
 	/*Go through elements, and request velocity: */
Index: /issm/trunk/src/c/modules/MinVyx/MinVyx.h
===================================================================
--- /issm/trunk/src/c/modules/MinVyx/MinVyx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MinVyx/MinVyx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MinVyx( double* pminvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MinVyx( IssmDouble* pminvy, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MINVYX_H */
Index: /issm/trunk/src/c/modules/MinVzx/MinVzx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MinVzx/MinVzx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/MinVzx/MinVzx.cpp	(revision 13395)
@@ -9,10 +9,10 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void MinVzx( double* pminvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+void MinVzx( IssmDouble* pminvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
 	
 	int i;
-	double minvz;
-	double node_minvz;
-	double element_minvz;
+	IssmDouble minvz;
+	IssmDouble node_minvz;
+	IssmDouble element_minvz;
 
 	/*Go through elements, and request velocity: */
Index: /issm/trunk/src/c/modules/MinVzx/MinVzx.h
===================================================================
--- /issm/trunk/src/c/modules/MinVzx/MinVzx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/MinVzx/MinVzx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void MinVzx( double* pminvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+void MinVzx( IssmDouble* pminvz, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
 
 #endif  /* _MINVZX_H */
Index: /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 13395)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 13395)
@@ -0,0 +1,65 @@
+/*!\file: CreateParametersAutodiff.cpp
+ * \brief driver for creating parameters dataset, for autodiff analysis.
+ */ 
+
+#include "../../../Container/Container.h"
+#include "../../../toolkits/toolkits.h"
+#include "../../../io/io.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../classes/objects/objects.h"
+#include "../../../shared/shared.h"
+#include "../../../include/include.h"
+#include "../ModelProcessorx.h"
+
+void CreateParametersAutodiff(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
+	
+	int         i,j;
+	Parameters *parameters       = NULL;
+	bool        autodiff_analysis;
+	int*        dependents       = NULL;
+	int         num_dependents;
+	int*        independents       = NULL;
+	int         num_independents;
+	int         numberofvertices;
+	IssmDouble* xp=NULL;
+	
+	/*Get parameters: */
+	parameters=*pparameters;
+
+	/*retrieve some parameters: */
+	iomodel->Constant(&autodiff_analysis,AutodiffIsautodiffEnum);
+	
+	if(autodiff_analysis){
+
+		iomodel->Constant(&num_independents,AutodiffNumIndependentsEnum);
+		iomodel->Constant(&num_dependents,AutodiffNumDependentsEnum);
+		iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+
+		/*recover dependents: */
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffNumDependentsEnum));
+		if(num_dependents){
+			iomodel->FetchData(&dependents,NULL,&num_dependents,AutodiffDependentsEnum);
+			parameters->AddObject(new IntVecParam(AutodiffDependentsEnum,dependents,num_dependents));
+		}
+
+		/*recover independents: */
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffNumIndependentsEnum));
+		if(num_independents){
+			iomodel->FetchData(&independents,NULL,&num_independents,AutodiffIndependentsEnum);
+			parameters->AddObject(new IntVecParam(AutodiffIndependentsEnum,independents,num_independents));
+
+			/*Build state vector, value at which we compute our gradients of dependent variables in adolc: the xp vector  */
+			xp=xNew<IssmDouble>(num_independents*numberofvertices);
+			for(i=0;i<num_independents;i++){
+				IssmDouble* values=iomodel->data[independents[i]];
+				for(j=0;j<numberofvertices;j++){
+					xp[i*numberofvertices+j]=values[j];
+				}
+			}
+			parameters->AddObject(new DoubleVecParam(AutodiffXpEnum,xp,num_independents*numberofvertices));
+		}
+
+		/*Assign output pointer: */
+		*pparameters=parameters;
+	}
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 13395)
@@ -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"
@@ -42,5 +42,5 @@
 
 			/*Get left and right elements*/
-			element=(int)iomodel->Data(MeshEdgesEnum)[4*i+2]-1; //edges are [node1 node2 elem1 elem2]
+			element=reCast<int,IssmDouble>(iomodel->Data(MeshEdgesEnum)[4*i+2])-1; //edges are [node1 node2 elem1 elem2]
 
 			/*Now, if this element is not in the partition, pass: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 13395)
@@ -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) _error2_("DG 3d not implemented yet");
+	if(stabilization==3 && dim==3) _error_("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,IssmDouble>(*(iomodel->Data(MeshElementsEnum)+3*i+j)); //(Matlab indexing)
 					io_index=vertex_id-1;                      //(C indexing)
 					_assert_(vertex_id>0 && vertex_id<=numberofvertices);
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 13395)
@@ -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"
@@ -21,8 +21,8 @@
 	int         num_cm_responses;
 	int        *control_type     = NULL;
-	double     *cm_responses     = NULL;
-	double     *cm_jump          = NULL;
-	double     *optscal          = NULL;
-	double     *maxiter          = NULL;
+	IssmDouble     *cm_responses     = NULL;
+	IssmDouble     *cm_jump          = NULL;
+	IssmDouble     *optscal          = NULL;
+	IssmDouble     *maxiter          = NULL;
 
 	/*Get parameters: */
@@ -64,8 +64,8 @@
 
 		xDelete<int>(control_type);
-		xDelete<double>(cm_responses);
-		xDelete<double>(cm_jump);
-		xDelete<double>(optscal);
-		xDelete<double>(maxiter);
+		iomodel->DeleteData(cm_responses,InversionCostFunctionsEnum);
+		iomodel->DeleteData(cm_jump,InversionStepThresholdEnum);
+		iomodel->DeleteData(optscal,InversionGradientScalingEnum);
+		iomodel->DeleteData(maxiter,InversionMaxiterPerStepEnum);
 	}
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 13395)
@@ -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"
@@ -42,5 +42,5 @@
 	iomodel->FetchData(4,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
 	for(i=0;i<num_control_type;i++){
-		switch((int)iomodel->Data(InversionControlParametersEnum)[i]){
+		switch(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])){
 			case BalancethicknessThickeningRateEnum: iomodel->FetchData(1,BalancethicknessThickeningRateEnum); break;
 			case VxEnum:   iomodel->FetchData(1,VxEnum); break;
@@ -48,5 +48,6 @@
 			case FrictionCoefficientEnum: iomodel->FetchData(1,FrictionCoefficientEnum); break;
 			case MaterialsRheologyBbarEnum:    iomodel->FetchData(1,MaterialsRheologyBEnum); break;
-			default: _error2_("Control " << EnumToStringx((int)iomodel->Data(InversionControlParametersEnum)[i]) << " not implemented yet");
+			case MaterialsRheologyZbarEnum:    iomodel->FetchData(1,MaterialsRheologyZEnum); break;
+			default: _error_("Control " << EnumToStringx(reCast<int,IssmDouble>(iomodel->Data(InversionControlParametersEnum)[i])) << " not implemented yet");
 		}
 	}
@@ -66,4 +67,4 @@
 	
 	/*Free data: */
-	iomodel->DeleteData(1+4+5,MeshElementsEnum,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum,BalancethicknessThickeningRateEnum,VxEnum,VyEnum,FrictionCoefficientEnum,MaterialsRheologyBEnum);
+	iomodel->DeleteData(1+4+6,MeshElementsEnum,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum,BalancethicknessThickeningRateEnum,VxEnum,VyEnum,FrictionCoefficientEnum,MaterialsRheologyBEnum,MaterialsRheologyZEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../../include/include.h"
@@ -16,5 +16,5 @@
 
 
-void CreateDataSets(Elements** pelements,Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,const int solution_type,const int analysis_type,const int nummodels,int analysis_counter){
+void CreateDataSets(Elements** pelements,Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,const int analysis_type,const int nummodels,int analysis_counter){
 
 	bool        continuous = true;
@@ -124,5 +124,5 @@
 
 		default:
-			_error2_("analysis_type: " << EnumToStringx(analysis_type) << " not supported yet!");
+			_error_("analysis_type: " << EnumToStringx(analysis_type) << " not supported yet!");
 	}
 
@@ -133,5 +133,5 @@
 
 	/*Generate objects that are not dependent on any analysis_type: */
-	CreateParameters(pparameters,iomodel,solution_type,analysis_type,analysis_counter);
+	CreateParameters(pparameters,iomodel,rootpath,solution_type,analysis_type,analysis_counter);
 
 	/*Update Elements in case we are running a transient solution: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 13395)
@@ -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"
@@ -17,5 +17,5 @@
 	/*Intermediary*/
 	int i,j,k,n;
-	int dim;
+	int dim,materials_type;
 	int numberofelements;
 	int numberofvertices;
@@ -23,7 +23,7 @@
 
 	/*DataSets: */
-	Elements*     elements  = NULL;
-	Vertices*     vertices = NULL;
-	Materials*    materials = NULL;
+	Elements  *elements  = NULL;
+	Vertices  *vertices  = NULL;
+	Materials *materials = NULL;
 
 	/*Fetch parameters: */
@@ -32,4 +32,5 @@
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	iomodel->Constant(&materials_type,MaterialsEnum);
 
 	/*Did we already create the elements? : */
@@ -44,6 +45,5 @@
 	ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
 	
-	/*Fetch data needed: */
-	iomodel->FetchData(4,MeshElementsEnum,MeshElementconnectivityEnum,MaterialsRheologyBEnum,MaterialsRheologyNEnum);
+	iomodel->FetchData(2,MeshElementsEnum,MeshElementconnectivityEnum);
 	#ifdef _HAVE_3D_
 	if(dim==3)iomodel->FetchData(2,MeshUpperelementsEnum,MeshLowerelementsEnum);
@@ -51,5 +51,5 @@
 	if(control_analysis)iomodel->FetchData(3,InversionControlParametersEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
 	
-	/*Create elements and materials: */
+	/*Create elements*/
 	for (i=0;i<numberofelements;i++){
 		if(iomodel->my_elements[i]){
@@ -60,15 +60,27 @@
 			else       elements->AddObject(new Penta(i+1,i,i,iomodel,nummodels));
 	        #endif
-
-			/*Create and add material property to materials dataset: */
-			materials->AddObject(new Matice(i+1,i,iomodel));
 		}
 	}
 	
+	/*Create materials*/
+	switch(materials_type){
+		case MaticeEnum:
+			iomodel->FetchData(2,MaterialsRheologyBEnum,MaterialsRheologyNEnum);
+			for (i=0;i<numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matice(i+1,i,iomodel));
+			break;
+		case MatdamageiceEnum:
+			iomodel->FetchData(3,MaterialsRheologyBEnum,MaterialsRheologyNEnum,MaterialsRheologyZEnum);
+			for (i=0;i<numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matdamageice(i+1,i,iomodel));
+			break;
+		default:
+			_error_("Materials "<<EnumToStringx(materials_type)<<" not supported");
+	}
+
 	/*Free data: */
-	iomodel->DeleteData(9,MeshElementsEnum,MeshElementconnectivityEnum,MeshUpperelementsEnum,MeshLowerelementsEnum,
-				MaterialsRheologyBEnum,MaterialsRheologyNEnum,InversionControlParametersEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
+	iomodel->DeleteData(10,MeshElementsEnum,MeshElementconnectivityEnum,MeshUpperelementsEnum,MeshLowerelementsEnum,
+				MaterialsRheologyBEnum,MaterialsRheologyNEnum,MaterialsRheologyZEnum,InversionControlParametersEnum,InversionMinParametersEnum,
+				InversionMaxParametersEnum);
 
-	/*Add new constrant material property tgo materials, at the end: */
+	/*Add new constant material property to materials, at the end: */
 	materials->AddObject(new Matpar(numberofelements+1,iomodel));//put it at the end of the materials
 	
@@ -81,5 +93,5 @@
 	for (i=0;i<numberofvertices;i++){
 
-		/*vertices and nodes (same number, as we are running continuous galerkin formulation: */
+		/*vertices and nodes (same number, as we are running continuous galerkin formulation): */
 		if(iomodel->my_vertices[i]){
 			
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 13395)
@@ -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"
@@ -19,11 +19,12 @@
 #include "./ModelProcessorx.h"
 
-void CreateParameters(Parameters** pparameters,IoModel* iomodel,const int solution_type,int analysis_type,int analysis_counter){
+void CreateParameters(Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,int analysis_type,int analysis_counter){
 	
 	int         i;
 	int         numoutputs;
 	Parameters *parameters       = NULL;
-	IssmDouble     *requestedoutputs = NULL;
-	
+	IssmDouble *requestedoutputs = NULL;
+	bool        isdelta18o;
+
 	if(*pparameters)return; //do not create parameters twice!
 
@@ -35,4 +36,5 @@
 	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIshutterEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsmacayealpattynEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsl1l2Enum));
 	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsstokesEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsOutputFrequencyEnum));
@@ -84,11 +86,29 @@
 	parameters->AddObject(iomodel->CopyConstantObject(MaterialsRheologyLawEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(AutodiffIsautodiffEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(AutodiffForwardEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(AutodiffReverseEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(QmuIsdakotaEnum));
 	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));
+		iomodel->DeleteData(temp,SurfaceforcingsDelta18oEnum);
+
+		iomodel->FetchData(&temp,&N,&M,SurfaceforcingsDelta18oSurfaceEnum); _assert_(N==2);
+		for(i=0;i<M;i++) temp[M+i]=yts*temp[M+i];
+		parameters->AddObject(new TransientParam(SurfaceforcingsDelta18oSurfaceEnum,&temp[0],&temp[M],M));
+		iomodel->DeleteData(temp,SurfaceforcingsDelta18oSurfaceEnum);
+	}
 
 	/*some parameters that did not come with the iomodel: */
@@ -106,13 +126,13 @@
 	parameters->AddObject(new IntParam(DiagnosticNumRequestedOutputsEnum,numoutputs));
 	if(numoutputs)parameters->AddObject(new IntVecParam(DiagnosticRequestedOutputsEnum,requestedoutputs,numoutputs));
-	xDelete<IssmDouble>(requestedoutputs);
+	iomodel->DeleteData(requestedoutputs,DiagnosticRequestedOutputsEnum);
 	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,TransientRequestedOutputsEnum);
 	parameters->AddObject(new IntParam(TransientNumRequestedOutputsEnum,numoutputs));
 	if(numoutputs)parameters->AddObject(new IntVecParam(TransientRequestedOutputsEnum,requestedoutputs,numoutputs));
-	xDelete<IssmDouble>(requestedoutputs);
+	iomodel->DeleteData(requestedoutputs,TransientRequestedOutputsEnum);
 	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,SteadystateRequestedOutputsEnum);
 	parameters->AddObject(new IntParam(SteadystateNumRequestedOutputsEnum,numoutputs));
 	if(numoutputs)parameters->AddObject(new IntVecParam(SteadystateRequestedOutputsEnum,requestedoutputs,numoutputs));
-	xDelete<IssmDouble>(requestedoutputs);
+	iomodel->DeleteData(requestedoutputs,SteadystateRequestedOutputsEnum);
 	
 	/*Before returning, create parameters in case we are running Qmu or control types runs: */
@@ -122,5 +142,9 @@
 
 	#ifdef _HAVE_DAKOTA_
-	CreateParametersDakota(&parameters,iomodel,solution_type,analysis_type);
+	CreateParametersDakota(&parameters,iomodel,rootpath,solution_type,analysis_type);
+	#endif
+
+ 	#ifdef _HAVE_ADOLC_
+	CreateParametersAutodiff(&parameters,iomodel,solution_type,analysis_type);
 	#endif
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 13395)
@@ -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"
@@ -13,5 +13,5 @@
 #include "../ModelProcessorx.h"
 
-void CreateParametersDakota(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
+void CreateParametersDakota(Parameters** pparameters,IoModel* iomodel,char* rootpath,int solution_type,int analysis_type){
 
 	/*variable declarations: {{{*/
@@ -74,14 +74,14 @@
 
 		/*name of qmu input, error and output files:{{{*/
-		qmuinname=xNew<char>((strlen(name)+strlen(".qmu.in")+1));
-		sprintf(qmuinname,"%s%s",name,".qmu.in");
+		qmuinname=xNew<char>((strlen(rootpath)+strlen(name)+strlen(".qmu.in")+1));
+		sprintf(qmuinname,"%s%s%s",rootpath,name,".qmu.in");
 		parameters->AddObject(new   StringParam(QmuInNameEnum,qmuinname));
 
-		qmuoutname=xNew<char>((strlen(name)+strlen(".qmu.out")+1));
-		sprintf(qmuoutname,"%s%s",name,".qmu.out");
+		qmuoutname=xNew<char>((strlen(rootpath)+strlen(name)+strlen(".qmu.out")+1));
+		sprintf(qmuoutname,"%s%s%s",rootpath,name,".qmu.out");
 		parameters->AddObject(new   StringParam(QmuOutNameEnum,qmuoutname));
 
-		qmuerrname=xNew<char>((strlen(name)+strlen(".qmu.err")+1));
-		sprintf(qmuerrname,"%s%s",name,".qmu.err");
+		qmuerrname=xNew<char>((strlen(rootpath)+strlen(name)+strlen(".qmu.err")+1));
+		sprintf(qmuerrname,"%s%s%s",rootpath,name,".qmu.err");
 		parameters->AddObject(new   StringParam(QmuErrNameEnum,qmuerrname));
 		/*}}}*/
@@ -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)_error2_("qmu_mass_flux_num_profiles is 0, when MassFlux computations were requested!");
+			if(qmu_mass_flux_num_profiles==0)_error_("qmu_mass_flux_num_profiles is 0, when MassFlux computations were requested!");
 
 			/*Go through segments, and extract those that belong to this cpu: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp	(revision 13395)
@@ -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"
@@ -16,28 +16,28 @@
 	int     i,j;
 	int     count;
-	double  yts;
-	double  g;
-	double  rho_ice;
-	double  stokesreconditioning;
-	bool    isstokes,ismacayealpattyn;
+	IssmDouble  yts;
+	IssmDouble  g;
+	IssmDouble  rho_ice;
+	IssmDouble  stokesreconditioning;
+	bool    isstokes,isl1l2,ismacayealpattyn;
    bool    spcpresent=false;
 	int Mx,Nx;
 	int My,Ny;
 	int Mz,Nz;
-	double *spcvx          = NULL;
-	double *spcvy          = NULL;
-	double *spcvz          = NULL;
-	double *nodeonmacayeal = NULL;
-	double *nodeonpattyn   = NULL;
-	double *nodeonstokes   = NULL;
-	double *nodeonbed      = NULL;
-	double *nodeonicesheet = NULL;
-	double *vertices_type  = NULL;
-	double *surface        = NULL;
-	double *z              = NULL;
-	double *timesx=NULL;
-	double *timesy=NULL;
-	double *timesz=NULL;
-   double* values=NULL;
+	IssmDouble *spcvx          = NULL;
+	IssmDouble *spcvy          = NULL;
+	IssmDouble *spcvz          = NULL;
+	IssmDouble *nodeonmacayeal = NULL;
+	IssmDouble *nodeonpattyn   = NULL;
+	IssmDouble *nodeonstokes   = NULL;
+	IssmDouble *nodeonbed      = NULL;
+	IssmDouble *nodeonicesheet = NULL;
+	IssmDouble *vertices_type  = NULL;
+	IssmDouble *surface        = NULL;
+	IssmDouble *z              = NULL;
+	IssmDouble *timesx=NULL;
+	IssmDouble *timesy=NULL;
+	IssmDouble *timesz=NULL;
+   IssmDouble* values=NULL;
 
 	/*Output*/
@@ -56,4 +56,5 @@
 	iomodel->Constant(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
 	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&isl1l2,FlowequationIsl1l2Enum);
 	iomodel->Constant(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
 
@@ -65,5 +66,5 @@
 	
 	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
-	if (!ismacayealpattyn & !isstokes){
+	if(!ismacayealpattyn & !isstokes & !isl1l2){
 		*pconstraints=constraints;
 		return;
@@ -87,5 +88,5 @@
 
 	/*figure out times: */
-	timesx=xNew<double>(Nx);
+	timesx=xNew<IssmDouble>(Nx);
 	for(j=0;j<Nx;j++){
 		timesx[j]=spcvx[(Mx-1)*Nx+j];
@@ -94,5 +95,5 @@
 	UnitConversion(timesx,Nx,ExtToIuEnum,TimeEnum);
 	/*figure out times: */
-	timesy=xNew<double>(Ny);
+	timesy=xNew<IssmDouble>(Ny);
 	for(j=0;j<Ny;j++){
 		timesy[j]=spcvy[(My-1)*Ny+j];
@@ -101,5 +102,5 @@
 	UnitConversion(timesy,Ny,ExtToIuEnum,TimeEnum);
 	/*figure out times: */
-	timesz=xNew<double>(Nz);
+	timesz=xNew<IssmDouble>(Nz);
 	for(j=0;j<Nz;j++){
 		timesz[j]=spcvz[(Mz-1)*Nz+j];
@@ -113,7 +114,7 @@
 
 			/*Start with adding spcs of coupling: zero at the border macayeal/pattyn for the appropriate dofs*/
-			if ((int)vertices_type[i]==MacAyealPattynApproximationEnum){
+			if (reCast<int,IssmDouble>(vertices_type[i]==MacAyealPattynApproximationEnum)){
 				/*If grionmacayeal, spc pattyn dofs: 3 & 4*/
-					if ((int)nodeonpattyn[i]){
+					if (reCast<int,IssmDouble>(nodeonpattyn[i])){
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
@@ -130,5 +131,5 @@
 
 					}
-					else if ((int)nodeonmacayeal[i]){
+					else if (reCast<int,IssmDouble>(nodeonmacayeal[i])){
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
@@ -145,10 +146,10 @@
 
 					}
-					else _error2_("if vertices_type is MacAyealPattyn, you shoud have nodeonpattyn or nodeonmacayeal");
+					else _error_("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*/
-			else if ((int)vertices_type[i]==PattynStokesApproximationEnum){
+			else if (reCast<int,IssmDouble>(vertices_type[i])==PattynStokesApproximationEnum){
 				/*If grion,pattyn spc stokes dofs: 3 4 & 5*/
-					if ((int)nodeonpattyn[i]){
+					if (reCast<int,IssmDouble>(nodeonpattyn[i])){
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
@@ -167,5 +168,5 @@
 
 					}
-					else if ((int)nodeonstokes[i]){ //spc pattyn nodes: 1 & 2
+					else if (reCast<int,IssmDouble>(nodeonstokes[i])){ //spc pattyn nodes: 1 & 2
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
@@ -185,10 +186,10 @@
 						}
 					}
-					else _error2_("if vertices_type is PattynStokes, you shoud have nodeonpattyn or nodeonstokes");
+					else _error_("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*/
-			else if ((int)vertices_type[i]==MacAyealStokesApproximationEnum){
+			else if (reCast<int,IssmDouble>(vertices_type[i])==MacAyealStokesApproximationEnum){
 				/*If grion,pattyn spc stokes dofs: 3 4 & 5*/
-					if ((int)nodeonmacayeal[i]){
+					if (reCast<int,IssmDouble>(nodeonmacayeal[i])){
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
@@ -207,5 +208,5 @@
 
 					}
-					else if ((int)nodeonstokes[i]){ //spc macayeal nodes: 1 & 2
+					else if (reCast<int,IssmDouble>(nodeonstokes[i])){ //spc macayeal nodes: 1 & 2
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
 						count++;
@@ -225,5 +226,5 @@
 						}
 					}
-					else _error2_("if vertices_type is MacAyealStokes, you shoud have nodeonmacayeal or nodeonstokes");
+					else _error_("if vertices_type is MacAyealStokes, you shoud have nodeonmacayeal or nodeonstokes");
 			}
 			/*Now add the regular spcs*/
@@ -235,5 +236,5 @@
 				else if (Mx==numberofvertices+1) {
 					/*figure out times and values: */
-					values=xNew<double>(Nx);
+					values=xNew<IssmDouble>(Nx);
 					spcpresent=false;
 					for(j=0;j<Nx;j++){
@@ -246,5 +247,5 @@
 						count++;
 					}
-					xDelete<double>(values);
+					xDelete<IssmDouble>(values);
 				}
 				else if (vertices_type[i]==HutterApproximationEnum){
@@ -259,5 +260,5 @@
 				else if (My==numberofvertices+1){
 					/*figure out times and values: */
-					values=xNew<double>(Ny);
+					values=xNew<IssmDouble>(Ny);
 					spcpresent=false;
 					for(j=0;j<Ny;j++){
@@ -269,5 +270,5 @@
 						count++;
 					}
-					xDelete<double>(values);
+					xDelete<IssmDouble>(values);
 				}
 				else if (vertices_type[i]==HutterApproximationEnum){
@@ -276,5 +277,5 @@
 				}
 
-				if ((int)vertices_type[i]==StokesApproximationEnum ||  ((int)vertices_type[i]==NoneApproximationEnum)){
+				if (reCast<int,IssmDouble>(vertices_type[i])==StokesApproximationEnum ||  (reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum)){
 					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
@@ -283,5 +284,5 @@
 					else if (Mz==numberofvertices+1){
 						/*figure out times and values: */
-						values=xNew<double>(Nz);
+						values=xNew<IssmDouble>(Nz);
 						spcpresent=false;
 						for(j=0;j<Nz;j++){
@@ -293,9 +294,9 @@
 							count++;
 						}
-						xDelete<double>(values);
-					}
-
-				}
-				if ((int)vertices_type[i]==NoneApproximationEnum){
+						xDelete<IssmDouble>(values);
+					}
+
+				}
+				if (reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
 					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,g*rho_ice*(surface[i]-z[i])/stokesreconditioning,DiagnosticHorizAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
 					count++;
@@ -304,6 +305,6 @@
 
 			/*Constraint at the bedrock interface (v.n = vz = 0) (Coordinates will be updated according to the bed slope)*/
-			if (dim==3) if(nodeonbed[i] && nodeonicesheet[i] && nodeonstokes[i]){
-				 switch((int)vertices_type[i]){
+			if (dim==3) if(reCast<int,IssmDouble>(nodeonbed[i]) && reCast<int,IssmDouble>(nodeonicesheet[i]) && reCast<int,IssmDouble>(nodeonstokes[i])){
+				 switch(reCast<int,IssmDouble>(vertices_type[i])){
 					case MacAyealStokesApproximationEnum:
 						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0.,DiagnosticHorizAnalysisEnum));
@@ -318,5 +319,5 @@
 						count++;
 						break;
-					default: _error2_("Vertex approximation " << EnumToStringx((int)vertices_type[i]) << " not supported");
+					default: _error_("Vertex approximation " << EnumToStringx(reCast<int,IssmDouble>(vertices_type[i])) << " not supported");
 				}
 			}
@@ -325,21 +326,21 @@
 	  
 	/*Free data: */
-	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);
+	iomodel->DeleteData(spcvx,DiagnosticSpcvxEnum);
+	iomodel->DeleteData(spcvy,DiagnosticSpcvyEnum);
+	iomodel->DeleteData(spcvz,DiagnosticSpcvzEnum);
+	iomodel->DeleteData(nodeonmacayeal,FlowequationBordermacayealEnum);
+	if(dim==3)iomodel->DeleteData(nodeonpattyn,FlowequationBorderpattynEnum);
+	if(dim==3)iomodel->DeleteData(nodeonstokes,FlowequationBorderstokesEnum);
+	if(dim==3)iomodel->DeleteData(nodeonbed,MeshVertexonbedEnum);
+	if(dim==3)iomodel->DeleteData(nodeonicesheet,MaskVertexongroundediceEnum);
+	iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
+	iomodel->DeleteData(surface,SurfaceEnum);
+	iomodel->DeleteData(z,MeshZEnum);
 
 	/*Free resources:*/
-	xDelete<double>(timesx);
-	xDelete<double>(timesy);
-	xDelete<double>(timesz);
-	xDelete<double>(values);
+	xDelete<IssmDouble>(timesx);
+	xDelete<IssmDouble>(timesy);
+	xDelete<IssmDouble>(timesz);
+	xDelete<IssmDouble>(values);
 
 	/*Assign output pointer: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp	(revision 13395)
@@ -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"
@@ -27,19 +27,20 @@
 	int dim;
 	int numberofvertices;
-	bool ismacayealpattyn,isstokes;
+	bool ismacayealpattyn,isstokes,isl1l2;
 	int  numpenalties,numberofpressureloads,numrifts,numriftsegments;
-	double *pressureload   = NULL;
-	double *elements_type  = NULL;
-	double *nodeoniceshelf = NULL;
-	double *riftinfo       = NULL;
-	double *nodeonbed      = NULL;
-	double *nodeonstokes   = NULL;
-	double *nodeonicesheet = NULL;
-	double *vertices_type  = NULL;
-	double *penalties      = NULL;
+	IssmDouble *pressureload   = NULL;
+	IssmDouble *elements_type  = NULL;
+	IssmDouble *nodeoniceshelf = NULL;
+	IssmDouble *riftinfo       = NULL;
+	IssmDouble *nodeonbed      = NULL;
+	IssmDouble *nodeonstokes   = NULL;
+	IssmDouble *nodeonicesheet = NULL;
+	IssmDouble *vertices_type  = NULL;
+	IssmDouble *penalties      = NULL;
 
 	/*Fetch parameters: */
 	iomodel->Constant(&dim,MeshDimensionEnum);
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	iomodel->Constant(&isl1l2,FlowequationIsl1l2Enum);
 	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
 	iomodel->Constant(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
@@ -53,5 +54,5 @@
 
 	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
-	if (!ismacayealpattyn & !isstokes){
+	if(!ismacayealpattyn & !isstokes & !isl1l2){
 		*ploads=loads;
 		return;
@@ -73,5 +74,5 @@
 		if (dim==2) segment_width=4; 
 		else segment_width=6;
-		element=(int)(*(pressureload+segment_width*i+segment_width-2)-1); //element is in the penultimate column (node1 node2 ... elem fill)
+		element=reCast<int,IssmDouble>(*(pressureload+segment_width*i+segment_width-2)-1); //element is in the penultimate column (node1 node2 ... elem fill)
 
 		/*Now, if this element is not in the partition, pass: */
@@ -79,24 +80,32 @@
 		
 		/*Do not create ice front if Hutter or Stokes elements*/
-		if ((int)*(elements_type+element)==HutterApproximationEnum) continue;
+		if (reCast<int,IssmDouble>(*(elements_type+element))==HutterApproximationEnum) continue;
 
 		/*Create and  add load: */
-		if ((int)*(elements_type+element)==(MacAyealApproximationEnum) && dim==2){
+		if (reCast<int,IssmDouble>(*(elements_type+element))==(MacAyealApproximationEnum) && dim==2){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal2dIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
 		}
-		else if ((int)*(elements_type+element)==(MacAyealApproximationEnum) && dim==3){
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(MacAyealApproximationEnum) && dim==3){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal3dIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
 		}
-		else if ((int)*(elements_type+element)==(PattynApproximationEnum)){
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(L1L2ApproximationEnum)){
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal3dIceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+		}
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(PattynApproximationEnum)){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,PattynIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
 		}
-		else if ((int)*(elements_type+element)==(StokesApproximationEnum)){
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(L1L2ApproximationEnum)){
+			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,L1L2IceFrontEnum,DiagnosticHorizAnalysisEnum));
+			count++;
+		}
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(StokesApproximationEnum)){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,StokesIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
 		}
-		else if ((int)*(elements_type+element)==(MacAyealPattynApproximationEnum)){
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(MacAyealPattynApproximationEnum)){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal3dIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
@@ -104,5 +113,5 @@
 			count++;
 		}
-		else if ((int)*(elements_type+element)==(PattynStokesApproximationEnum)){
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(PattynStokesApproximationEnum)){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,PattynIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
@@ -110,5 +119,5 @@
 			count++;
 		}
-		else if ((int)*(elements_type+element)==(MacAyealStokesApproximationEnum)){
+		else if (reCast<int,IssmDouble>(*(elements_type+element))==(MacAyealStokesApproximationEnum)){
 			loads->AddObject(new Icefront(iomodel->loadcounter+count+1,i,iomodel,MacAyeal3dIceFrontEnum,DiagnosticHorizAnalysisEnum));
 			count++;
@@ -120,6 +129,7 @@
 	/*Free data: */
 	iomodel->DeleteData(3,DiagnosticIcefrontEnum,ThicknessEnum,BedEnum);
-	xDelete<double>(elements_type);
-	xDelete<double>(pressureload);
+	iomodel->DeleteData(elements_type,FlowequationElementEquationEnum);
+	iomodel->DeleteData(pressureload,DiagnosticIcefrontEnum);
+
 
 	/*Create Penpair for penalties: */
@@ -128,5 +138,5 @@
 	for(i=0;i<numpenalties;i++){
 
-		if(iomodel->my_vertices[(int)penalties[2*i+0]-1]){
+		if(iomodel->my_vertices[reCast<int,IssmDouble>(penalties[2*i+0]-1)]){
 
 			/*In debugging mode, check that the second node is in the same cpu*/
@@ -134,6 +144,6 @@
 
 			/*Get node ids*/
-			penpair_ids[0]=iomodel->nodecounter+(int)penalties[2*i+0];
-			penpair_ids[1]=iomodel->nodecounter+(int)penalties[2*i+1];
+			penpair_ids[0]=iomodel->nodecounter+reCast<int,IssmDouble>(penalties[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int,IssmDouble>(penalties[2*i+1]);
 
 			/*Create Load*/
@@ -144,5 +154,5 @@
 
 	/*free ressources: */
-	xDelete<double>(penalties);
+	iomodel->DeleteData(penalties,DiagnosticVertexPairingEnum);
 
 	/*Create Riffront loads for rifts: */
@@ -151,5 +161,5 @@
 		iomodel->FetchData(5,RiftsRiftstructEnum,ThicknessEnum,BedEnum,SurfaceEnum,MaskVertexonfloatingiceEnum);
 		for(i=0;i<numriftsegments;i++){
-			if(iomodel->my_elements[(int)*(riftinfo+RIFTINFOSIZE*i+2)-1]){
+			if(iomodel->my_elements[reCast<int,IssmDouble>(*(riftinfo+RIFTINFOSIZE*i+2))-1]){
 				loads->AddObject(new Riftfront(iomodel->loadcounter+count+1,i,iomodel,DiagnosticHorizAnalysisEnum));
 				count++;
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp	(revision 13395)
@@ -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"
@@ -19,5 +19,5 @@
 	bool   continuous_galerkin=true;
 	int    numberofvertices;
-	bool   isstokes,ismacayealpattyn;
+	bool   isstokes,isl1l2,ismacayealpattyn;
 
 	/*DataSets: */
@@ -27,4 +27,5 @@
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&isl1l2,FlowequationIsl1l2Enum);
 	iomodel->Constant(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
 
@@ -36,5 +37,5 @@
 	
 	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
-	if(!ismacayealpattyn & !isstokes){
+	if(!ismacayealpattyn & !isstokes & !isl1l2){
 		*pnodes=nodes;
 		return;
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp	(revision 13395)
@@ -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"
@@ -16,7 +16,8 @@
 void	UpdateElementsDiagnosticHoriz(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
 
-	int    dim;
+	int    dim,materials_type;
 	int    numberofelements;
 	bool   ismacayealpattyn;
+	bool   isl1l2;
 	bool   isstokes;
 	bool   control_analysis;
@@ -25,4 +26,5 @@
 	/*Fetch constants needed: */
 	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&isl1l2,FlowequationIsl1l2Enum);
 	iomodel->Constant(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
 	iomodel->Constant(&dim,MeshDimensionEnum);
@@ -30,7 +32,8 @@
 	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
 	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&materials_type,MaterialsEnum);
 
 	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
-	if(!ismacayealpattyn & !isstokes) return;
+	if(!ismacayealpattyn & !isstokes &!isl1l2) return;
 
 	/*Fetch data needed: */
@@ -61,5 +64,7 @@
 	iomodel->FetchDataToInput(elements,VxEnum);
 	iomodel->FetchDataToInput(elements,VyEnum);
-
+	if(materials_type==MatdamageiceEnum){
+		iomodel->FetchDataToInput(elements,MaterialsRheologyZEnum);
+	}
 	if (dim==3){
 		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp	(revision 13395)
@@ -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"
@@ -16,5 +16,5 @@
 	int i;
 	int count;
-	double yts;
+	IssmDouble yts;
 	int    numberofvertices;
 	bool   ishutter;
@@ -51,5 +51,5 @@
 		/*keep only this partition's nodes:*/
 		if((iomodel->my_vertices[i])){
-			if (!(int)iomodel->Data(FlowequationVertexEquationEnum)[i]==HutterApproximationEnum){
+			if (!reCast<int,IssmDouble>(iomodel->Data(FlowequationVertexEquationEnum)[i])==HutterApproximationEnum){
 
 				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticHutterAnalysisEnum));
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp	(revision 13395)
@@ -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"
@@ -17,5 +17,5 @@
 	int dim;
 	int count;
-	double yts;
+	IssmDouble yts;
 	int    numberofvertices;
 
@@ -52,5 +52,5 @@
 		if(iomodel->my_vertices[i]){
 
-			if ((int)iomodel->Data(FlowequationBorderstokesEnum)[i]){
+			if (reCast<int,IssmDouble>(iomodel->Data(FlowequationBorderstokesEnum)[i])){
 				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,DiagnosticVertAnalysisEnum)); //spc to zero as vertical velocity is done in Horiz for Stokes
 				count++;
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 13395)
@@ -19,4 +19,7 @@
 	if (analysis_type==DiagnosticHorizAnalysisEnum){
 		if (vertices_type[0]==MacAyealApproximationEnum){
+			numdofs=2;
+		}
+		else if (vertices_type[0]==L1L2ApproximationEnum){
 			numdofs=2;
 		}
@@ -61,5 +64,5 @@
 			doftype[5]=StokesApproximationEnum;
 		}
-		else _error2_("Approximationtype " << reCast<int>(*vertices_type) << " (" << EnumToStringx(reCast<int>(*vertices_type)) << ") not implemented yet for DiagnosticHoriz");
+		else _error_("Approximationtype " << reCast<int>(*vertices_type) << " (" << EnumToStringx(reCast<int>(*vertices_type)) << ") not implemented yet for DiagnosticHoriz");
 	}
 	else if (analysis_type==DiagnosticVertAnalysisEnum){
@@ -90,5 +93,5 @@
 		numdofs=1;
 	}
-	else _error2_("analysis type: " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not implemented yet");
+	else _error_("analysis type: " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not implemented yet");
 
 	/*Now initialize the index*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 
 #include <string.h>
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
@@ -76,6 +76,6 @@
 
 	/*Free elements and elements2d: */
-	xDelete<IssmDouble>(elements);
-	xDelete<IssmDouble>(elements2d);
+	iomodel->DeleteData(elements,MeshElementsEnum);
+	iomodel->DeleteData(elements2d,MeshElements2dEnum);
 
 	/*Deal with rifts, they have to be included into one partition only, not several: */
@@ -87,5 +87,5 @@
 			epart[el2]=epart[el1]; //ensures that this pair of elements will be in the same partition, as well as the corresponding vertices;
 		}
-		xDelete<IssmDouble>(riftinfo); 
+		iomodel->DeleteData(riftinfo,RiftsRiftstructEnum);
 	}
 
@@ -119,5 +119,5 @@
 	}//for (i=0;i<numberofelements;i++)
 	/*Free data : */
-	xDelete<IssmDouble>(elements);
+	iomodel->DeleteData(elements,MeshElementsEnum);
 
 	/*We might have vertex_pairing in which case, some vertices have to be cloned:
@@ -130,5 +130,5 @@
 		}
 	}
-	xDelete<IssmDouble>(vertex_pairing);
+	iomodel->DeleteData(vertex_pairing,DiagnosticVertexPairingEnum);
 	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,PrognosticVertexPairingEnum);
 	for(i=0;i<numvertex_pairing;i++){
@@ -137,5 +137,5 @@
 		}
 	}
-	xDelete<IssmDouble>(vertex_pairing);
+	iomodel->DeleteData(vertex_pairing,PrognosticVertexPairingEnum);
 
 	/*Free ressources:*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 13395)
@@ -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"
@@ -21,6 +21,6 @@
 	int    numberofvertices;
 	bool   spcpresent=false;
-	double heatcapacity;
-	double referencetemperature;
+	IssmDouble heatcapacity;
+	IssmDouble referencetemperature;
 	
 	/*Output*/
@@ -106,9 +106,9 @@
 	}
 	else{
-		_error2_("Size of field " << EnumToStringx(ThermalSpctemperatureEnum) << " not supported");
+		_error_("Size of field " << EnumToStringx(ThermalSpctemperatureEnum) << " not supported");
 	}
 
 	/*Free ressources:*/
-	xDelete<IssmDouble>(spcvector);
+	iomodel->DeleteData(spcvector,ThermalSpctemperatureEnum);
 	xDelete<IssmDouble>(times);
 	xDelete<IssmDouble>(values);
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 13395)
@@ -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) _error2_("2d meshes not supported yet");
+	if (dim==2) _error_("2d meshes not supported yet");
 
 	/*Recover pointer: */
@@ -40,5 +40,5 @@
 	for (i=0;i<numberofvertices;i++){
 		if((iomodel->my_vertices[i]==1)){
-			if (iomodel->Data(MeshVertexonbedEnum)[i]){ 
+			if (reCast<int>(iomodel->Data(MeshVertexonbedEnum)[i])){
 				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,MeltingAnalysisEnum));
 			}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../../io/io.h"
@@ -17,8 +17,8 @@
 #include "../../modules/modules.h"
 
-void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* IOMODEL,const int solution_type,const int nummodels,const int* analysis_type_list){
+void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* IOMODEL,char* rootpath,const int solution_type,const int nummodels,const int* analysis_type_list){
 
 	int   i,analysis_type,dim,verbose;
-	bool  isthermal,isprognostic,isdiagnostic,isgroundingline,isenthalpy;
+	bool  isthermal,isprognostic,isdiagnostic,isgroundingline,isenthalpy,autodiff;
 	
 	/*output: */
@@ -43,5 +43,11 @@
 	iomodel->Constant(&isdiagnostic,TransientIsdiagnosticEnum);
 	iomodel->Constant(&isgroundingline,TransientIsgroundinglineEnum);
-	
+	iomodel->Constant(&autodiff,AutodiffIsautodiffEnum);
+
+	/*If we are running in AD mode, we need to declare our independent variables now, before 
+	 *and prevent them from being erased during successive calls to iomodel->FetchData and 
+	 iomodel->DeleteData:*/
+	if(autodiff)iomodel->DeclareIndependents();
+
 	SetVerbosityLevel(verbose);
 
@@ -69,8 +75,8 @@
 	
 		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);
+		CreateDataSets(&elements,&nodes,&vertices,&materials,&constraints,&loads,&parameters,iomodel,rootpath,solution_type,analysis_type,nummodels,i);
 	}
 
-	/*Free ressources:*/
+	/*Free resources:*/
 	delete iomodel;
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 13395)
@@ -11,14 +11,17 @@
 class IoModel;
 class Parameters;
+class DofIndexing;
+
 #include "../../io/io.h"
 
-void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* iomodel_handle,const int solution_type,const int nummodels,const int* analysis_type_list);
+void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* iomodel_handle,char* rootpath,const int solution_type,const int nummodels,const int* analysis_type_listh);
 
 /*Creation of fem datasets: general drivers*/
-void  CreateDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,const int solution_type,int analysis_type,const int nummodels,int analysis_counter);
+void  CreateDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,int analysis_type,const int nummodels,int analysis_counter);
 void  CreateElementsVerticesAndMaterials(Elements** pelements,Vertices** pvertices,Materials** pmaterials, IoModel* iomodel,const int nummodels);
-void  CreateParameters(Parameters** pparameters,IoModel* iomodel,const int solution_type,int analysis_type,int analysis_counter);
+void  CreateParameters(Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,int analysis_type,int analysis_counter);
 void  CreateParametersControl(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
-void  CreateParametersDakota(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
+void  CreateParametersDakota(Parameters** pparameters,IoModel* iomodel,char* rootpath,int solution_type,int analysis_type);
+void  CreateParametersAutodiff(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
 void  UpdateElementsAndMaterialsControl(Elements* elements,Materials* materials, IoModel* iomodel);
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 
 #include <string.h>
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
@@ -103,5 +103,5 @@
 	}
 	else{
-		_error2_("not implemented yet");
+		_error_("not implemented yet");
 	}
 
@@ -111,5 +111,5 @@
 	iomodel->FetchData(&edges,&numberofedges,&cols,MeshEdgesEnum);
 	iomodel->FetchData(&elements,NULL,NULL,MeshElementsEnum);
-	if (cols!=4) _error2_("field edges should have 4 columns");
+	if (cols!=4) _error_("field edges should have 4 columns");
 
 	/*!All elements have been partitioned above, only create elements for this CPU: */
@@ -152,5 +152,5 @@
 			}
 			else{
-				_error2_("Problem in edges creation");
+				_error_("Problem in edges creation");
 			}
 		}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp	(revision 13395)
@@ -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"
@@ -90,6 +90,6 @@
 
 	/*free ressources: */
-	xDelete<IssmDouble>(vertex_pairing);
-	xDelete<IssmDouble>(nodeonbed);
+	iomodel->DeleteData(vertex_pairing,PrognosticVertexPairingEnum);
+	iomodel->DeleteData(nodeonbed,MeshVertexonbedEnum);
 
 	/*Assign output pointer: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp	(revision 13395)
@@ -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) _error2_("DG 3d not implemented yet");
+	if(stabilization==3 && dim==3) _error_("DG 3d not implemented yet");
 
 	/*First fetch data: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp	(revision 13395)
@@ -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,6 +20,7 @@
 	int    stabilization;
 	bool   dakota_analysis;
+	bool   issmbgradients;
 	bool   ispdd;
-	bool   issmbgradients;
+	bool   isdelta18o;
 
 	/*Fetch data needed: */
@@ -28,7 +29,8 @@
 	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);
-	iomodel->Constant(&ispdd,SurfaceforcingsIspddEnum);
-	iomodel->Constant(&issmbgradients,SurfaceforcingsIssmbgradientsEnum);
 
 	/*Update elements: */
@@ -69,20 +71,26 @@
 		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,VyEnum); 
-	  iomodel->FetchDataToInput(elements,ThermalSpctemperatureEnum);
-	  iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationEnum);
-	  iomodel->FetchDataToInput(elements,SurfaceforcingsMonthlytemperaturesEnum);
+		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(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);
-	}
-	else{
+	if(~ispdd & ~issmbgradients){
 		iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
 	}
Index: /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../../include/include.h"
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 13395)
@@ -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) _error2_("2d meshes not supported yet");
+	if (dim==2) _error_("2d meshes not supported yet");
 
 	//create penalties for nodes: no node can have a temperature over the melting point
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 13395)
@@ -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/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../shared/shared.h"
 #include "../../include/include.h"
Index: /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp
===================================================================
--- /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 13395)
@@ -38,5 +38,5 @@
 	#ifdef _HAVE_MPI_
 	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
-	if(!sumfound)_error2_("could not find element with vertex with id" << index << " to compute nodal value " << EnumToStringx(natureofdataenum));
+	if(!sumfound)_error_("could not find element with vertex with id" << index << " to compute nodal value " << EnumToStringx(natureofdataenum));
 	#endif
 
Index: /issm/trunk/src/c/modules/NodalValuex/NodalValuex.h
===================================================================
--- /issm/trunk/src/c/modules/NodalValuex/NodalValuex.h	(revision 13394)
+++ /issm/trunk/src/c/modules/NodalValuex/NodalValuex.h	(revision 13395)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp
===================================================================
--- /issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 13395)
@@ -71,5 +71,5 @@
 	 * warn the user to increase the connectivity width: */
 	for(i=0;i<nods;i++){
-		if (*(connectivity+width*i+maxels)>maxels)_error2_("max connectivity width reached (" << *(connectivity+width*i+maxels) << ")! increase width of connectivity table");
+		if (*(connectivity+width*i+maxels)>maxels)_error_("max connectivity width reached (" << *(connectivity+width*i+maxels) << ")! increase width of connectivity table");
 	}
 
Index: /issm/trunk/src/c/modules/NodesDofx/NodesDofx.h
===================================================================
--- /issm/trunk/src/c/modules/NodesDofx/NodesDofx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/NodesDofx/NodesDofx.h	(revision 13395)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Orthx/Orthx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Orthx/Orthx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Orthx/Orthx.cpp	(revision 13395)
@@ -5,11 +5,11 @@
 #include "./Orthx.h"
 
-void	Orthx( Vector** pnewgradj, Vector* gradj, Vector* oldgradj){
+void	Orthx( Vector<IssmDouble>** pnewgradj, Vector<IssmDouble>* gradj, Vector<IssmDouble>* oldgradj){
 	
 	/*output: */
-	Vector* newgradj=NULL;
+	Vector<IssmDouble>* newgradj=NULL;
 
 	/*intermediary:*/
-	double norm_new,norm_old,dot_product;;
+	IssmDouble norm_new,norm_old,dot_product;;
 
 	/*Initialize output*/
Index: /issm/trunk/src/c/modules/Orthx/Orthx.h
===================================================================
--- /issm/trunk/src/c/modules/Orthx/Orthx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Orthx/Orthx.h	(revision 13395)
@@ -6,10 +6,10 @@
 #define _ORTHX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../include/include.h"
 #include "../../shared/shared.h"
 
 /* local prototypes: */
-void	Orthx( Vector** pnewgradj, Vector* gradj, Vector* oldgradj);
+void	Orthx( Vector<IssmDouble>** pnewgradj, Vector<IssmDouble>* gradj, Vector<IssmDouble>* oldgradj);
 
 #endif  /* _ORTHX_H */
Index: /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 13395)
@@ -14,5 +14,5 @@
 #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){
@@ -45,5 +45,5 @@
 		parameters->FindParam(&solutiontype,SolutionTypeEnum);
 		EnumToStringx(&solutiontypestring,solutiontype);
-		results->AddObject(new StringExternalResult(results->Size()+1,SolutionTypeEnum,solutiontypestring,1,0));
+		results->AddObject(new GenericExternalResult<char*>(results->Size()+1,SolutionTypeEnum,solutiontypestring,1,0));
 		xDelete<char>(solutiontypestring);
 	}
Index: /issm/trunk/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp	(revision 13395)
@@ -106,5 +106,5 @@
 		char* string=strings[i];
 		if(my_rank==0){
-			if(string==NULL) _error2_("PETSc options for analysis " << EnumToStringx(reCast<int>(analyses[i])) << " have been declared but were not found");
+			if(string==NULL) _error_("PETSc options for analysis " << EnumToStringx(reCast<int>(analyses[i])) << " have been declared but were not found");
 		}
 		if(my_rank==0)stringlength=(strlen(string)+1)*sizeof(char);
Index: /issm/trunk/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.h
===================================================================
--- /issm/trunk/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.h	(revision 13395)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp	(revision 13395)
@@ -4,9 +4,9 @@
 #include "./PointCloudFindNeighborsx.h"
 
-int PointCloudFindNeighborsx( Vector** pflags,double* x, double* y, int nods, double mindistance,double multithread){
+int PointCloudFindNeighborsx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, double mindistance,double multithread){
 
 	/*output: */
-	Vector* flags=NULL;
-	flags=new Vector(nods);
+	SeqVec<IssmPDouble>* flags=NULL;
+	flags=new SeqVec<IssmPDouble>(nods);
 
 	/*threading: */
Index: /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h
===================================================================
--- /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h	(revision 13395)
@@ -8,8 +8,8 @@
 
 #include "../../shared/shared.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-int PointCloudFindNeighborsx( Vector** pflags,double* x, double* y, int nods, double mindistance,double multithread);
+int PointCloudFindNeighborsx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, double mindistance,double multithread);
 
 /*threading: */
@@ -20,6 +20,5 @@
 	int nods;
 	double mindistance;
-	Vector* flags;
-
+	SeqVec<IssmPDouble>* flags;
 
 } PointCloudFindNeighborsThreadStruct;
Index: /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 13395)
@@ -17,5 +17,5 @@
 	int     nods;
 	double  mindistance;
-	Vector*     flags;
+	SeqVec<IssmPDouble>*     flags;
 
 	/*recover handle and gate: */
Index: /issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.h
===================================================================
--- /issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.h	(revision 13395)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 13395)
@@ -12,9 +12,9 @@
 #include "../../io/io.h"
 
-void	Reduceloadx( Vector* pf, Matrix* Kfs, Vector* y_s,bool flag_ys0){
+void	Reduceloadx( Vector<IssmDouble>* pf, Matrix<IssmDouble>* Kfs, Vector<IssmDouble>* y_s,bool flag_ys0){
 
 	/*intermediary*/
-	Vector*     y_s0   = NULL;
-	Vector*     Kfsy_s = NULL;
+	Vector<IssmDouble>*     y_s0   = NULL;
+	Vector<IssmDouble>*     Kfsy_s = NULL;
 	int         Kfsm,Kfsn;
 	int         global_m,global_n;
@@ -32,5 +32,5 @@
 		/*pf = pf - Kfs * y_s;*/
 		Kfs->GetLocalSize(&Kfsm,&Kfsn);
-		Kfsy_s=new Vector(Kfsm,fromlocalsize);
+		Kfsy_s=new Vector<IssmDouble>(Kfsm,fromlocalsize);
 		if (flag_ys0){
 
Index: /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.h
===================================================================
--- /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.h	(revision 13395)
@@ -6,8 +6,8 @@
 #define _REDUCELOADX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void	Reduceloadx( Vector* pf, Matrix* Kfs, Vector* ys,bool flag_ys0=false);
+void	Reduceloadx( Vector<IssmDouble>* pf, Matrix<IssmDouble>* Kfs, Vector<IssmDouble>* ys,bool flag_ys0=false);
 
 #endif  /* _REDUCELOADX_H */
Index: /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 13395)
@@ -6,8 +6,8 @@
 #include "./Reducevectorgtofx.h"
  
-void Reducevectorgtofx(Vector** puf, Vector* ug, Nodes* nodes,Parameters* parameters){
+void Reducevectorgtofx(Vector<IssmDouble>** puf, Vector<IssmDouble>* ug, Nodes* nodes,Parameters* parameters){
 
 	/*output: */
-	Vector* uf=NULL;
+	Vector<IssmDouble>* uf=NULL;
 
 	/*variables: */
@@ -26,5 +26,5 @@
 	else{
 		/*allocate: */
-		uf=new Vector(fsize);
+		uf=new Vector<IssmDouble>(fsize);
 
 		if(nodes->NumberOfNodes(configuration_type)){ 
Index: /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h	(revision 13395)
@@ -7,8 +7,8 @@
 #define _REDUCEVECTORGTOFX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void Reducevectorgtofx(Vector** puf, Vector* ug, Nodes* nodes,Parameters* parameters);
+void Reducevectorgtofx(Vector<IssmDouble>** puf, Vector<IssmDouble>* ug, Nodes* nodes,Parameters* parameters);
 
 #endif  /* _REDUCEVECTORGTOFX_H */
Index: /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp	(revision 13395)
@@ -6,8 +6,8 @@
 #include "./Reducevectorgtosx.h"
 
-void Reducevectorgtosx(Vector** pys, Vector* yg, Nodes* nodes,Parameters* parameters){
+void Reducevectorgtosx(Vector<IssmDouble>** pys, Vector<IssmDouble>* yg, Nodes* nodes,Parameters* parameters){
 
 	/*output: */
-	Vector* ys=NULL;
+	Vector<IssmDouble>* ys=NULL;
 
 	/*variables: */
@@ -15,5 +15,5 @@
 	int configuration_type;
 	int ssize;
-	double* yg_serial=NULL;
+	IssmDouble* yg_serial=NULL;
 
 	/*first figure out ssize: */
@@ -26,5 +26,5 @@
 	else{
 		/*allocate: */
-		ys=new Vector(ssize);
+		ys=new Vector<IssmDouble>(ssize);
 
 		if(nodes->NumberOfNodes(configuration_type)){ 
@@ -51,5 +51,5 @@
 
 	/*Free ressources:*/
-	xDelete<double>(yg_serial);
+	xDelete<IssmDouble>(yg_serial);
 
 	/*Assign output pointers:*/
Index: /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h	(revision 13395)
@@ -7,8 +7,8 @@
 #define _REDUCEVECTORGTOSX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void Reducevectorgtosx(Vector** pys, Vector* yg, Nodes* nodes,Parameters* parameters);
+void Reducevectorgtosx(Vector<IssmDouble>** pys, Vector<IssmDouble>* yg, Nodes* nodes,Parameters* parameters);
 
 #endif  /* _REDUCEVECTORGTOSX_H */
Index: /issm/trunk/src/c/modules/RequestedDependentsx/RequestedDependentsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/RequestedDependentsx/RequestedDependentsx.cpp	(revision 13395)
+++ /issm/trunk/src/c/modules/RequestedDependentsx/RequestedDependentsx.cpp	(revision 13395)
@@ -0,0 +1,45 @@
+/*!\file RequestedDependentsx
+ * \brief: compute outputs that were requested specifically for this solution, such as BasalStress, StrainHeating, etc ...
+ */
+
+#include "../../modules/modules.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void RequestedDependentsx(Results* results,Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters){
+
+
+
+	int         i;
+	int         output_enum;
+	bool        isautodiff      = false;
+	IssmDouble  output_value;
+	Element    *element         = NULL;
+	int        *dependent_enums = NULL;
+
+	int         num_dependents;
+	IssmPDouble *dependents;
+
+	/*AD mode on?: */
+	parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
+
+	if(isautodiff){
+		#ifdef _HAVE_ADOLC_
+		parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
+		if(num_dependents){
+			dependents=xNew<IssmPDouble>(num_dependents);
+			parameters->FindParam(&dependent_enums,&num_dependents,AutodiffDependentsEnum);
+
+			/*Go through our dependent variables, and compute the response:*/
+			for(i=0;i<num_dependents;i++){
+				Responsex(&output_value,elements,nodes,vertices,loads,materials,parameters,dependent_enums[i],false,0);
+				output_value>>=dependents[i];
+			}
+		}
+		#else
+		_error_("Should not be requesting dependents when an AD library is not available!");
+		#endif
+	}
+}
Index: /issm/trunk/src/c/modules/RequestedDependentsx/RequestedDependentsx.h
===================================================================
--- /issm/trunk/src/c/modules/RequestedDependentsx/RequestedDependentsx.h	(revision 13395)
+++ /issm/trunk/src/c/modules/RequestedDependentsx/RequestedDependentsx.h	(revision 13395)
@@ -0,0 +1,14 @@
+/*!\file:  RequestedDependentsx.h
+ * \brief header file for  requesting AD dependents
+ */ 
+
+#ifndef _REQUESTED_DEPENDENTSX_H_
+#define _REQUESTED_DEPENDENTSX_H_
+
+#include "../../Container/Container.h"
+
+/* local prototypes: */
+void RequestedDependentsx(Results* results,Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters);
+
+#endif  /* _INPUTTORESULTX_H */
+
Index: /issm/trunk/src/c/modules/RequestedOutputsx/RequestedOutputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/RequestedOutputsx/RequestedOutputsx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/RequestedOutputsx/RequestedOutputsx.cpp	(revision 13395)
@@ -30,5 +30,9 @@
 				case IceVolumeEnum:
 					Responsex(&output_value,elements,nodes,vertices,loads,materials,parameters,"IceVolume",false,0);
-					results->AddObject(new DoubleExternalResult(results->Size()+1,IceVolumeEnum,output_value,step,time));
+					results->AddObject(new GenericExternalResult<double>(results->Size()+1,IceVolumeEnum,reCast<IssmPDouble>(output_value),step,time));
+					break;
+				case TotalSmbEnum:
+					Responsex(&output_value,elements,nodes,vertices,loads,materials,parameters,"TotalSmb",false,0);
+					results->AddObject(new GenericExternalResult<double>(results->Size()+1,TotalSmbEnum,reCast<IssmPDouble>(output_value),step,time));
 					break;
 				default:
Index: /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 13395)
@@ -30,5 +30,5 @@
 	 * management routine, otherwise, skip : */
 	if (RiftIsPresent(loads,analysis_type)){
-		_error2_("rift constraints reset not supported yet!");
+		_error_("rift constraints reset not supported yet!");
 	}
 	else if(ThermalIsPresent(loads,analysis_type)){
Index: /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 13395)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h
===================================================================
--- /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.h	(revision 13395)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Responsex/Responsex.cpp
===================================================================
--- /issm/trunk/src/c/modules/Responsex/Responsex.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Responsex/Responsex.cpp	(revision 13395)
@@ -14,9 +14,19 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 #include "../../toolkits/toolkits.h"
+#include "./Responsex.h"
 #include "../modules.h"
 
 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)){
+	int response_descriptor_enum;
+
+	response_descriptor_enum=StringToEnumx(response_descriptor);
+	Responsex(responses, elements, nodes,  vertices, loads, materials,  parameters,response_descriptor_enum, process_units, weight_index);
+
+}
+
+void Responsex(IssmDouble* responses,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,int response_descriptor_enum,bool process_units,int weight_index){
+
+	switch (response_descriptor_enum){
 
 		#ifdef _HAVE_RESPONSES_
@@ -41,4 +51,7 @@
 		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 ThicknessAlongGradientEnum:   ThicknessAlongGradientx(    responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case ThicknessAcrossGradientEnum:   ThicknessAcrossGradientx(    responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case 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 +59,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: _error2_("response descriptor \"" << response_descriptor << "\" not supported yet!"); break;
+		default: _error_("response descriptor \"" << EnumToStringx(response_descriptor_enum) << "\" not supported yet!"); break;
 		#else
-		default: _error2_("ISSM was not compiled with responses capabilities, exiting!");
+		default: _error_("ISSM was not compiled with responses capabilities, exiting!");
 		#endif
 	}
Index: /issm/trunk/src/c/modules/Responsex/Responsex.h
===================================================================
--- /issm/trunk/src/c/modules/Responsex/Responsex.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Responsex/Responsex.h	(revision 13395)
@@ -6,8 +6,9 @@
 #define _RESPONSESX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 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);
+void Responsex(IssmDouble* presponse,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,int response_descriptor_enum,bool process_units,int weight_index);
 
 #endif  /* _RESPONSESXX_H */
Index: /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void RheologyBbarAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void RheologyBbarAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/Scotchx/Scotchx.h
===================================================================
--- /issm/trunk/src/c/modules/Scotchx/Scotchx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Scotchx/Scotchx.h	(revision 13395)
@@ -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/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vector){
+void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* vector){
 
 	int  num_controls;
@@ -28,7 +28,7 @@
 }
 
-void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector* vector){
+void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* vector){
 	
-	double* serial_vector=NULL;
+	IssmDouble* serial_vector=NULL;
 
 	serial_vector=vector->ToMPISerial();
@@ -37,4 +37,4 @@
 
 	/*Free ressources:*/
-	xDelete<double>(serial_vector);
+	xDelete<IssmDouble>(serial_vector);
 }
Index: /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h
===================================================================
--- /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h	(revision 13395)
@@ -5,10 +5,10 @@
 #define _SETCONTROLINPUTSXFROMVECTOR_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
 /* local prototypes: */
-void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector* vector);
-void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,double* vector);
+void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector<IssmDouble>* vector);
+void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,IssmDouble* vector);
 
 #endif 
Index: /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 13395)
@@ -75,5 +75,5 @@
 
 	hSHP = SHPOpen( filshp, "rb" );
-	if (!hSHP) _error2_("Error opening shp/shx files.");
+	if (!hSHP) _error_("Error opening shp/shx files.");
 
 /*  read header and print out file bounds  */
Index: /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.h
===================================================================
--- /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.h	(revision 13395)
@@ -19,5 +19,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.h
===================================================================
--- /issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.h	(revision 13395)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/SmearFunctionx/SmearFunctionx.h
===================================================================
--- /issm/trunk/src/c/modules/SmearFunctionx/SmearFunctionx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/SmearFunctionx/SmearFunctionx.h	(revision 13395)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Solverx/Solverx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Solverx/Solverx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Solverx/Solverx.cpp	(revision 13395)
@@ -14,5 +14,5 @@
 #endif
 
-void	Solverx(Vector** puf, Matrix* Kff, Vector* pf, Vector* uf0,Vector* df, Parameters* parameters){
+void	Solverx(Vector<IssmDouble>** puf, Matrix<IssmDouble>* Kff, Vector<IssmDouble>* pf, Vector<IssmDouble>* uf0,Vector<IssmDouble>* df, Parameters* parameters){
 
 	/*Intermediary: */
@@ -20,5 +20,5 @@
 
 	/*output: */
-	Vector *uf=NULL;
+	Vector<IssmDouble> *uf=NULL;
 
 	/*In debugging mode, check that stiffness matrix and load vectors are not NULL (they can be empty)*/
@@ -26,38 +26,26 @@
 	_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<IssmDouble>();
 
-		/*In serial mode, the Petsc Options database has not been initialized properly: */
+	/*According to matrix type, use specific solvers: */
+	switch(Kff->type){
+		#ifdef _HAVE_PETSC_
+		case PetscMatType:{
+			PetscVec* uf0_vector = NULL;
+			PetscVec* df_vector  = NULL;
+			if(uf0) uf0_vector = uf0->pvector;
+			if(df)  df_vector  = df->pvector;
+			SolverxPetsc(&uf->pvector,Kff->pmatrix,pf->pvector,uf0_vector,df_vector,parameters);
+			break;}
+		#endif
+		case SeqMatType:{
+			SolverxSeq(&uf->svector,Kff->smatrix,pf->svector,parameters);
+			break;}
+		default:
+			  _error_("Matrix type: " << Kff->type << " not supported yet!");
+	}
 
-		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
-			_error2_("GSL support not compiled in!");
-		#endif
-	#endif
-
-	/*Assign output pointers: */
+	/*Assign output pointers:*/
 	*puf=uf;
 }
Index: /issm/trunk/src/c/modules/Solverx/Solverx.h
===================================================================
--- /issm/trunk/src/c/modules/Solverx/Solverx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/Solverx/Solverx.h	(revision 13395)
@@ -12,17 +12,27 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void	Solverx(Vector** puf, Matrix* Kff, Vector* pf, Vector* uf0,Vector* df, Parameters* parameters);
+void	Solverx(Vector<IssmDouble>** puf, Matrix<IssmDouble>* Kff, Vector<IssmDouble>* pf, Vector<IssmDouble>* uf0,Vector<IssmDouble>* df, Parameters* parameters);
 
 #ifdef _HAVE_PETSC_
+void	SolverxPetsc(PetscVec** puf, PetscMat* Kff, PetscVec* pf, PetscVec* uf0,PetscVec* df, Parameters* parameters);
 void	SolverxPetsc(Vec* puf, Mat Kff, Vec pf, Vec uf0,Vec df, Parameters* parameters);
 void  DofTypesToIndexSet(IS* pisv, IS* pisp, Vec df,int typeenum);
 #endif
 
-#ifdef _HAVE_GSL_
-void SolverxGsl(SeqVec** puf,SeqMat* Kff, SeqVec* pf);
-void SolverxGsl(IssmDouble** pX,IssmDouble* A,IssmDouble* B,int n);
+void SolverxSeq(SeqVec<IssmDouble>** puf,SeqMat<IssmDouble>* Kff, SeqVec<IssmDouble>* pf,Parameters* parameters);
+void SolverxSeq(IssmPDouble **pX, IssmPDouble *A, IssmPDouble *B,int n);
+void SolverxSeq(IssmPDouble *X, IssmPDouble *A, IssmPDouble *B,int n);
+
+#ifdef _HAVE_ADOLC_
+void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters);
+// call back functions:
+ADOLC_ext_fct EDF_for_solverx;
+ADOLC_ext_fct_fos_forward EDF_fos_forward_for_solverx;
+ADOLC_ext_fct_fos_reverse EDF_fos_reverse_for_solverx;
+ADOLC_ext_fct_fov_forward EDF_fov_forward_for_solverx;
+ADOLC_ext_fct_fov_reverse EDF_fov_reverse_for_solverx;
 #endif
 
Index: sm/trunk/src/c/modules/Solverx/SolverxGsl.cpp
===================================================================
--- /issm/trunk/src/c/modules/Solverx/SolverxGsl.cpp	(revision 13394)
+++ 	(revision )
@@ -1,78 +1,0 @@
-/*!\file SolverxGsl
- * \brief Gsl implementation of solver
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-#include <cstring>
-#include <gsl/gsl_linalg.h>
-
-#include "./Solverx.h"
-#include "../../shared/shared.h"
-#include "../../include/include.h"
-#include "../../io/io.h"
-
-void SolverxGsl(SeqVec** puf,SeqMat* Kff, SeqVec* pf){/*{{{*/
-
-	/*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!");
-
-	SolverxGsl(&x,Kff->matrix,pf->vector,N);
-	uf=new SeqVec(x,N);
-
-	/*Assign output pointers:*/
-	*puf=uf;
-}/*}}}*/
-void SolverxGsl(IssmDouble** pX,IssmDouble* A,IssmDouble* B,int n){/*{{{*/
-
-	/*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_("SolverxGsl: 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
-}/*}}}*/
Index: /issm/trunk/src/c/modules/Solverx/SolverxPetsc.cpp
===================================================================
--- /issm/trunk/src/c/modules/Solverx/SolverxPetsc.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Solverx/SolverxPetsc.cpp	(revision 13395)
@@ -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){
 
@@ -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_
-			_error2_("requested MUMPS solver, which was not compiled into ISSM!\n");
+			_error_("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)_error2_("need doftypes for Stokes solver!\n");
+		if(!df)_error_("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) _error2_("Solver diverged at iteration number: " << -iteration_number);
+	if (iteration_number<0) _error_("Solver diverged at iteration number: " << -iteration_number);
 
 	/*Free resources:*/
Index: /issm/trunk/src/c/modules/Solverx/SolverxSeq.cpp
===================================================================
--- /issm/trunk/src/c/modules/Solverx/SolverxSeq.cpp	(revision 13395)
+++ /issm/trunk/src/c/modules/Solverx/SolverxSeq.cpp	(revision 13395)
@@ -0,0 +1,212 @@
+/*!\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
+
+#ifdef _HAVE_ADOLC_
+#include "../../shared/Numerics/adolc_edf.h"
+#endif
+
+void SolverxSeq(SeqVec<IssmDouble>** puf,SeqMat<IssmDouble>* Kff, SeqVec<IssmDouble>* pf, Parameters* parameters){/*{{{*/
+
+#ifdef _HAVE_GSL_
+	/*Intermediary: */
+	int M,N,N2,s;
+	SeqVec<IssmDouble> *uf = NULL;
+
+	Kff->GetSize(&M,&N);
+	pf->GetSize(&N2);
+
+	if(N!=N2)_error_("Right hand side vector of size " << N2 << ", when matrix is of size " << M << "-" << N << " !");
+	if(M!=N)_error_("Stiffness matrix should be square!");
+	IssmDouble *x  = xNew<IssmDouble>(N);
+
+#ifdef _HAVE_ADOLC_
+	SolverxSeq(x,Kff->matrix,pf->vector,N,parameters);
+#else
+	SolverxSeq(x,Kff->matrix,pf->vector,N);
+#endif
+
+	uf=new SeqVec<IssmDouble>(x,N);
+	xDelete(x);
+
+	/*Assign output pointers:*/
+	*puf=uf;
+
+#else
+	_error_("GSL support not compiled in!");
+#endif
+
+}/*}}}*/
+void SolverxSeq(IssmPDouble **pX, IssmPDouble *A, IssmPDouble *B,int n){ /*{{{*/
+
+	/*Allocate output*/
+	double* X = xNew<double>(n); 
+
+	/*Solve*/
+	SolverxSeq(X,A,B,n);
+
+	/*Assign output pointer*/
+	*pX=X;
+}
+/*}}}*/
+
+#ifdef _HAVE_ADOLC_
+int EDF_for_solverx(int n, IssmPDouble *x, int m, IssmPDouble *y){ /*{{{*/
+    SolverxSeq(y,x, x+m*m, m); // x is where the matrix starts, x+m*m is where the right-hand side starts
+    return 0;
+} /*}}}*/
+int EDF_fos_forward_for_solverx(int n, IssmPDouble *inVal, IssmPDouble *inDeriv, int m, IssmPDouble *outVal, IssmPDouble *outDeriv) { /*{{{*/
+#ifdef _HAVE_GSL_
+  // the matrix will be modified by LU decomposition. Use gsl_A copy
+  double* Acopy = xNew<double>(m*m);
+  xMemCpy(Acopy,inVal,m*m);
+  /*Initialize gsl matrices and vectors: */
+  gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
+  gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
+  gsl_permutation *perm_p = gsl_permutation_alloc (m);
+  int  signPerm;
+  // factorize
+  gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
+  gsl_vector *gsl_x_p = gsl_vector_alloc (m);
+  // solve for the value
+  gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
+  /*Copy result*/
+  xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
+  gsl_vector_free(gsl_x_p);
+  // solve for the derivatives acc. to A * dx = r  with r=db - dA * x
+  // compute the RHS
+  double* r=xNew<double>(m);
+  for (int i=0; i<m; i++) {
+    r[i]=inDeriv[m*m+i]; // this is db[i]
+    for (int j=0;j<m; j++) {
+      r[i]-=inDeriv[i*m+j]*outVal[j]; // this is dA[i][j]*x[j]
+    }
+  }
+  gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
+  gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
+  gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
+  xMemCpy(outDeriv,gsl_vector_ptr(gsl_dx_p,0),m);
+  gsl_vector_free(gsl_dx_p);
+  xDelete(r);
+  gsl_permutation_free(perm_p);
+  xDelete(Acopy);
+  #endif
+  return 0;
+} /*}}}*/
+int EDF_fov_forward_for_solverx(int n, IssmPDouble *inVal, int directionCount, IssmPDouble **inDeriv, int m, IssmPDouble *outVal, IssmPDouble **outDeriv) { /*{{{*/
+#ifdef _HAVE_GSL_
+  // the matrix will be modified by LU decomposition. Use gsl_A copy
+  double* Acopy = xNew<double>(m*m);
+  xMemCpy(Acopy,inVal,m*m);
+  /*Initialize gsl matrices and vectors: */
+  gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
+  gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
+  gsl_permutation *perm_p = gsl_permutation_alloc (m);
+  int  signPerm;
+  // factorize
+  gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
+  gsl_vector *gsl_x_p = gsl_vector_alloc (m);
+  // solve for the value
+  gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
+  /*Copy result*/
+  xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
+  gsl_vector_free(gsl_x_p);
+  // solve for the derivatives acc. to A * dx = r  with r=db - dA * x
+  double* r=xNew<double>(m);
+  gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
+  for (int dir=0;dir<directionCount;++dir) {
+    // compute the RHS
+    for (int i=0; i<m; i++) {
+      r[i]=inDeriv[m*m+i][dir]; // this is db[i]
+      for (int j=0;j<m; j++) {
+        r[i]-=inDeriv[i*m+j][dir]*outVal[j]; // this is dA[i][j]*x[j]
+      }
+    }
+    gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
+    gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
+    // reuse r
+    xMemCpy(r,gsl_vector_ptr(gsl_dx_p,0),m);
+    for (int i=0; i<m; i++) {
+      outDeriv[i][dir]=r[i];
+    }
+  }
+  gsl_vector_free(gsl_dx_p);
+  xDelete(r);
+  gsl_permutation_free(perm_p);
+  xDelete(Acopy);
+  #endif
+  return 0;
+}
+/*}}}*/
+int EDF_fos_reverse_for_solverx(int m, double *dp_U, int n, double *dp_Z) { /*{{{*/
+  return 0;
+}
+/*}}}*/
+void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters){/*{{{*/
+	// pack inputs to conform to the EDF-prescribed interface
+        IssmDouble*  adoubleEDFin=xNew<IssmDouble>(n*(n+1));  // packed inputs, i.e. matrix and right hand side
+        for(int i=0; i<n*n;i++)adoubleEDFin[i]    =A[i];      // pack matrix
+        for(int i=0; i<n;  i++)adoubleEDFin[i+n*n]=B[i];      // pack the right hand side
+        IssmPDouble* pdoubleEDFin=xNew<IssmPDouble>(n*(n+1)); // provide space to transfer inputs during call_ext_fct
+	IssmPDouble* pdoubleEDFout=xNew<IssmPDouble>(n);           // provide space to transfer outputs during call_ext_fct
+	// call the wrapped solver through the registry entry we retrieve from parameters
+	call_ext_fct(dynamic_cast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
+	             n*(n+1), pdoubleEDFin, adoubleEDFin,
+	             n, pdoubleEDFout,X);
+	xDelete(adoubleEDFin);
+	xDelete(pdoubleEDFin);
+	xDelete(pdoubleEDFout);
+}
+/*}}}*/
+#endif
+void SolverxSeq(IssmPDouble *X, IssmPDouble *A, IssmPDouble *B,int n){ /*{{{*/
+#ifdef _HAVE_GSL_
+	/*GSL Matrices and vectors: */
+	int              s;
+	gsl_matrix_view  a;
+	gsl_vector_view  b;
+	gsl_vector      *x = NULL;
+	gsl_permutation *p = NULL;
+	/*A will be modified by LU decomposition. Use copy*/
+	double* Acopy = xNew<double>(n*n);
+	xMemCpy(Acopy,A,n*n);
+
+	/*Initialize gsl matrices and vectors: */
+	a = gsl_matrix_view_array (Acopy,n,n);
+	b = gsl_vector_view_array (B,n);
+	x = gsl_vector_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*/
+	xMemCpy(X,gsl_vector_ptr(x,0),n);
+
+	/*Clean up and assign output pointer*/
+	xDelete(Acopy);
+	gsl_permutation_free(p);
+	gsl_vector_free(x);
+#endif
+}
+/*}}}*/
Index: /issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.h
===================================================================
--- /issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.h	(revision 13395)
@@ -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/trunk/src/c/modules/StringToEnumx/StringToEnumx.cpp
===================================================================
--- /issm/trunk/src/c/modules/StringToEnumx/StringToEnumx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/StringToEnumx/StringToEnumx.cpp	(revision 13395)
@@ -18,7 +18,12 @@
 
    if(stage==1){
-	      if (strcmp(name,"AutodiffForward")==0) return AutodiffForwardEnum;
-	      else if (strcmp(name,"AutodiffIsautodiff")==0) return AutodiffIsautodiffEnum;
-	      else if (strcmp(name,"AutodiffReverse")==0) return AutodiffReverseEnum;
+	      if (strcmp(name,"AutodiffIsautodiff")==0) return AutodiffIsautodiffEnum;
+	      else if (strcmp(name,"AutodiffDependents")==0) return AutodiffDependentsEnum;
+	      else if (strcmp(name,"AutodiffNumDependents")==0) return AutodiffNumDependentsEnum;
+	      else if (strcmp(name,"AutodiffIndependents")==0) return AutodiffIndependentsEnum;
+	      else if (strcmp(name,"AutodiffNumIndependents")==0) return AutodiffNumIndependentsEnum;
+	      else if (strcmp(name,"AutodiffJacobian")==0) return AutodiffJacobianEnum;
+	      else if (strcmp(name,"AutodiffXp")==0) return AutodiffXpEnum;
+	      else if (strcmp(name,"AutodiffFosForwardOutput")==0) return AutodiffFosForwardOutputEnum;
 	      else if (strcmp(name,"BalancethicknessSpcthickness")==0) return BalancethicknessSpcthicknessEnum;
 	      else if (strcmp(name,"BalancethicknessStabilization")==0) return BalancethicknessStabilizationEnum;
@@ -56,4 +61,5 @@
 	      else if (strcmp(name,"FlowequationElementEquation")==0) return FlowequationElementEquationEnum;
 	      else if (strcmp(name,"FlowequationIshutter")==0) return FlowequationIshutterEnum;
+	      else if (strcmp(name,"FlowequationIsl1l2")==0) return FlowequationIsl1l2Enum;
 	      else if (strcmp(name,"FlowequationIsmacayealpattyn")==0) return FlowequationIsmacayealpattynEnum;
 	      else if (strcmp(name,"FlowequationIsstokes")==0) return FlowequationIsstokesEnum;
@@ -107,4 +113,6 @@
 	      else if (strcmp(name,"MaterialsRheologyLaw")==0) return MaterialsRheologyLawEnum;
 	      else if (strcmp(name,"MaterialsRheologyN")==0) return MaterialsRheologyNEnum;
+	      else if (strcmp(name,"MaterialsRheologyZ")==0) return MaterialsRheologyZEnum;
+	      else if (strcmp(name,"MaterialsRheologyZbar")==0) return MaterialsRheologyZbarEnum;
 	      else if (strcmp(name,"MaterialsRhoIce")==0) return MaterialsRhoIceEnum;
 	      else if (strcmp(name,"MaterialsRhoWater")==0) return MaterialsRhoWaterEnum;
@@ -130,5 +138,8 @@
 	      else if (strcmp(name,"MeshUpperelements")==0) return MeshUpperelementsEnum;
 	      else if (strcmp(name,"MeshVertexonbed")==0) return MeshVertexonbedEnum;
-	      else if (strcmp(name,"MeshVertexonsurface")==0) return MeshVertexonsurfaceEnum;
+         else stage=2;
+   }
+   if(stage==2){
+	      if (strcmp(name,"MeshVertexonsurface")==0) return MeshVertexonsurfaceEnum;
 	      else if (strcmp(name,"MeshX")==0) return MeshXEnum;
 	      else if (strcmp(name,"MeshY")==0) return MeshYEnum;
@@ -138,8 +149,5 @@
 	      else if (strcmp(name,"PrognosticMinThickness")==0) return PrognosticMinThicknessEnum;
 	      else if (strcmp(name,"PrognosticPenaltyFactor")==0) return PrognosticPenaltyFactorEnum;
-         else stage=2;
-   }
-   if(stage==2){
-	      if (strcmp(name,"PrognosticSpcthickness")==0) return PrognosticSpcthicknessEnum;
+	      else if (strcmp(name,"PrognosticSpcthickness")==0) return PrognosticSpcthicknessEnum;
 	      else if (strcmp(name,"PrognosticStabilization")==0) return PrognosticStabilizationEnum;
 	      else if (strcmp(name,"PrognosticVertexPairing")==0) return PrognosticVertexPairingEnum;
@@ -158,4 +166,10 @@
 	      else if (strcmp(name,"SettingsResultsAsPatches")==0) return SettingsResultsAsPatchesEnum;
 	      else if (strcmp(name,"SettingsWaitonlock")==0) return SettingsWaitonlockEnum;
+	      else if (strcmp(name,"SurfaceforcingsDelta18o")==0) return SurfaceforcingsDelta18oEnum;
+	      else if (strcmp(name,"SurfaceforcingsDelta18oSurface")==0) return SurfaceforcingsDelta18oSurfaceEnum;
+	      else if (strcmp(name,"SurfaceforcingsIsdelta18o")==0) return SurfaceforcingsIsdelta18oEnum;
+	      else if (strcmp(name,"SurfaceforcingsPrecipitationsPresentday")==0) return SurfaceforcingsPrecipitationsPresentdayEnum;
+	      else if (strcmp(name,"SurfaceforcingsTemperaturesPresentday")==0) return SurfaceforcingsTemperaturesPresentdayEnum;
+	      else if (strcmp(name,"SurfaceforcingsTemperaturesLgm")==0) return SurfaceforcingsTemperaturesLgmEnum;
 	      else if (strcmp(name,"DebugProfiling")==0) return DebugProfilingEnum;
 	      else if (strcmp(name,"ProfilingCurrentMem")==0) return ProfilingCurrentMemEnum;
@@ -235,9 +249,10 @@
 	      else if (strcmp(name,"TransientSolution")==0) return TransientSolutionEnum;
 	      else if (strcmp(name,"Approximation")==0) return ApproximationEnum;
+	      else if (strcmp(name,"NoneApproximation")==0) return NoneApproximationEnum;
 	      else if (strcmp(name,"HutterApproximation")==0) return HutterApproximationEnum;
 	      else if (strcmp(name,"MacAyealApproximation")==0) return MacAyealApproximationEnum;
 	      else if (strcmp(name,"MacAyealPattynApproximation")==0) return MacAyealPattynApproximationEnum;
 	      else if (strcmp(name,"MacAyealStokesApproximation")==0) return MacAyealStokesApproximationEnum;
-	      else if (strcmp(name,"NoneApproximation")==0) return NoneApproximationEnum;
+	      else if (strcmp(name,"L1L2Approximation")==0) return L1L2ApproximationEnum;
 	      else if (strcmp(name,"PattynApproximation")==0) return PattynApproximationEnum;
 	      else if (strcmp(name,"PattynStokesApproximation")==0) return PattynStokesApproximationEnum;
@@ -246,8 +261,13 @@
 	      else if (strcmp(name,"Loads")==0) return LoadsEnum;
 	      else if (strcmp(name,"Materials")==0) return MaterialsEnum;
-	      else if (strcmp(name,"Nodes")==0) return NodesEnum;
+         else stage=3;
+   }
+   if(stage==3){
+	      if (strcmp(name,"Nodes")==0) return NodesEnum;
 	      else if (strcmp(name,"Parameters")==0) return ParametersEnum;
 	      else if (strcmp(name,"Vertices")==0) return VerticesEnum;
 	      else if (strcmp(name,"Results")==0) return ResultsEnum;
+	      else if (strcmp(name,"GenericParam")==0) return GenericParamEnum;
+	      else if (strcmp(name,"AdolcParam")==0) return AdolcParamEnum;
 	      else if (strcmp(name,"BoolInput")==0) return BoolInputEnum;
 	      else if (strcmp(name,"BoolParam")==0) return BoolParamEnum;
@@ -261,8 +281,5 @@
 	      else if (strcmp(name,"DoubleParam")==0) return DoubleParamEnum;
 	      else if (strcmp(name,"DoubleVecParam")==0) return DoubleVecParamEnum;
-         else stage=3;
-   }
-   if(stage==3){
-	      if (strcmp(name,"Element")==0) return ElementEnum;
+	      else if (strcmp(name,"Element")==0) return ElementEnum;
 	      else if (strcmp(name,"ElementResult")==0) return ElementResultEnum;
 	      else if (strcmp(name,"ExternalResult")==0) return ExternalResultEnum;
@@ -274,11 +291,14 @@
 	      else if (strcmp(name,"IntParam")==0) return IntParamEnum;
 	      else if (strcmp(name,"IntVecParam")==0) return IntVecParamEnum;
+	      else if (strcmp(name,"TransientParam")==0) return TransientParamEnum;
 	      else if (strcmp(name,"MacAyeal2dIceFront")==0) return MacAyeal2dIceFrontEnum;
 	      else if (strcmp(name,"MacAyeal3dIceFront")==0) return MacAyeal3dIceFrontEnum;
 	      else if (strcmp(name,"Matice")==0) return MaticeEnum;
+	      else if (strcmp(name,"Matdamageice")==0) return MatdamageiceEnum;
 	      else if (strcmp(name,"Matpar")==0) return MatparEnum;
 	      else if (strcmp(name,"Node")==0) return NodeEnum;
 	      else if (strcmp(name,"Numericalflux")==0) return NumericalfluxEnum;
 	      else if (strcmp(name,"Param")==0) return ParamEnum;
+	      else if (strcmp(name,"L1L2IceFront")==0) return L1L2IceFrontEnum;
 	      else if (strcmp(name,"PattynIceFront")==0) return PattynIceFrontEnum;
 	      else if (strcmp(name,"Pengrid")==0) return PengridEnum;
@@ -351,4 +371,6 @@
 	      else if (strcmp(name,"TemperatureOld")==0) return TemperatureOldEnum;
 	      else if (strcmp(name,"TemperaturePicard")==0) return TemperaturePicardEnum;
+	      else if (strcmp(name,"TemperatureSurface")==0) return TemperatureSurfaceEnum;
+	      else if (strcmp(name,"TemperatureBasal")==0) return TemperatureBasalEnum;
 	      else if (strcmp(name,"ThicknessAbsMisfit")==0) return ThicknessAbsMisfitEnum;
 	      else if (strcmp(name,"Type")==0) return TypeEnum;
@@ -362,5 +384,8 @@
 	      else if (strcmp(name,"VyPicard")==0) return VyPicardEnum;
 	      else if (strcmp(name,"Vz")==0) return VzEnum;
-	      else if (strcmp(name,"VzMacAyeal")==0) return VzMacAyealEnum;
+         else stage=4;
+   }
+   if(stage==4){
+	      if (strcmp(name,"VzMacAyeal")==0) return VzMacAyealEnum;
 	      else if (strcmp(name,"VzPattyn")==0) return VzPattynEnum;
 	      else if (strcmp(name,"VzPicard")==0) return VzPicardEnum;
@@ -372,4 +397,6 @@
 	      else if (strcmp(name,"EnthalpyPicard")==0) return EnthalpyPicardEnum;
 	      else if (strcmp(name,"ThicknessAbsGradient")==0) return ThicknessAbsGradientEnum;
+	      else if (strcmp(name,"ThicknessAlongGradient")==0) return ThicknessAlongGradientEnum;
+	      else if (strcmp(name,"ThicknessAcrossGradient")==0) return ThicknessAcrossGradientEnum;
 	      else if (strcmp(name,"StepResponses")==0) return StepResponsesEnum;
 	      else if (strcmp(name,"IntMatParam")==0) return IntMatParamEnum;
@@ -384,8 +411,5 @@
 	      else if (strcmp(name,"QmuTemperature")==0) return QmuTemperatureEnum;
 	      else if (strcmp(name,"HydrologyWaterVx")==0) return HydrologyWaterVxEnum;
-         else stage=4;
-   }
-   if(stage==4){
-	      if (strcmp(name,"HydrologyWaterVy")==0) return HydrologyWaterVyEnum;
+	      else if (strcmp(name,"HydrologyWaterVy")==0) return HydrologyWaterVyEnum;
 	      else if (strcmp(name,"StressTensor")==0) return StressTensorEnum;
 	      else if (strcmp(name,"StressTensorxx")==0) return StressTensorxxEnum;
@@ -395,5 +419,4 @@
 	      else if (strcmp(name,"StressTensoryz")==0) return StressTensoryzEnum;
 	      else if (strcmp(name,"StressTensorzz")==0) return StressTensorzzEnum;
-	      else if (strcmp(name,"IceVolume")==0) return IceVolumeEnum;
 	      else if (strcmp(name,"P0")==0) return P0Enum;
 	      else if (strcmp(name,"P1")==0) return P1Enum;
@@ -429,4 +452,6 @@
 	      else if (strcmp(name,"MaxVz")==0) return MaxVzEnum;
 	      else if (strcmp(name,"MaxAbsVz")==0) return MaxAbsVzEnum;
+	      else if (strcmp(name,"IceVolume")==0) return IceVolumeEnum;
+	      else if (strcmp(name,"TotalSmb")==0) return TotalSmbEnum;
 	      else if (strcmp(name,"Relative")==0) return RelativeEnum;
 	      else if (strcmp(name,"Absolute")==0) return AbsoluteEnum;
@@ -468,4 +493,5 @@
 	      else if (strcmp(name,"XYZP")==0) return XYZPEnum;
 	      else if (strcmp(name,"Option")==0) return OptionEnum;
+	      else if (strcmp(name,"GenericOption")==0) return GenericOptionEnum;
 	      else if (strcmp(name,"OptionCell")==0) return OptionCellEnum;
 	      else if (strcmp(name,"OptionChar")==0) return OptionCharEnum;
@@ -478,4 +504,4 @@
    }
 	/*If we reach this point, the string provided has not been found*/
-	_error2_("Enum " << name << " not found");
+	_error_("Enum " << name << " not found");
 }
Index: /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SurfaceAbsVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void SurfaceAbsVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceAbsVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 13394)
+++ /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _SURFACEAREAX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Container.h"
 
Index: /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 13395)
@@ -11,5 +11,5 @@
 #include "../SurfaceAreax/SurfaceAreax.h"
 
-void SurfaceAverageVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceAverageVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
 
 	/*Intermediary*/
@@ -18,6 +18,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute surface area and add to elements inputs */
Index: /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void SurfaceAverageVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceAverageVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SurfaceLogVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void SurfaceLogVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceLogVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SurfaceLogVxVyMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void SurfaceLogVxVyMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceLogVxVyMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void SurfaceRelVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
+void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units,int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void SurfaceRelVelMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void SurfaceRelVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-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){
+void SystemMatricesx(Matrix<IssmDouble>** pKff, Matrix<IssmDouble>** pKfs, Vector<IssmDouble>** ppf, Vector<IssmDouble>** 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: */
@@ -21,8 +21,8 @@
 	
 	/*output: */
-	Matrix*    Kff  = NULL;
-	Matrix*    Kfs  = NULL;
-	Vector*    pf   = NULL;
-	Vector*    df=NULL;
+	Matrix<IssmDouble>*    Kff  = NULL;
+	Matrix<IssmDouble>*    Kfs  = NULL;
+	Vector<IssmDouble>*    pf   = NULL;
+	Vector<IssmDouble>*    df=NULL;
 	IssmDouble kmax = 0;
 
@@ -49,7 +49,7 @@
 	if(kflag){
 
-		Kff=new Matrix(fsize,fsize,connectivity,numberofdofspernode);
-		Kfs=new Matrix(fsize,ssize,connectivity,numberofdofspernode);
-		df=new Vector(fsize);
+		Kff=new Matrix<IssmDouble>(fsize,fsize,connectivity,numberofdofspernode);
+		Kfs=new Matrix<IssmDouble>(fsize,ssize,connectivity,numberofdofspernode);
+		df=new Vector<IssmDouble>(fsize);
 
 		/*Fill stiffness matrix from elements: */
@@ -73,5 +73,5 @@
 	if(pflag){
 
-		pf=new Vector(fsize);
+		pf=new Vector<IssmDouble>(fsize);
 
 		/*Fill right hand side vector, from elements: */
Index: /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.h
===================================================================
--- /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.h	(revision 13395)
@@ -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, IssmDouble* pkmax,Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters,
+void SystemMatricesx(Matrix<IssmDouble>** pKff, Matrix<IssmDouble>** pKfs, Vector<IssmDouble>** ppf, Vector<IssmDouble>** 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/trunk/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ThicknessAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void ThicknessAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/trunk/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void ThicknessAbsGradientx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void ThicknessAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void ThicknessAbsMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
 
 	/*Intermediary*/
@@ -17,6 +17,6 @@
 
 	/*output: */
-	double J=0;
-	double J_sum;
+	IssmDouble J=0;
+	IssmDouble J_sum;
 
 	/*Compute Misfit: */
Index: /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void ThicknessAbsMisfitx( double* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+void ThicknessAbsMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
 
 #endif
Index: /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 13395)
+++ /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 13395)
@@ -0,0 +1,37 @@
+/*!\file ThicknessAcrossGradientx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./ThicknessAcrossGradientx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+
+	/*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*output: */
+	IssmDouble J=0;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		J+=element->ThicknessAcrossGradient(process_units,weight_index);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	#ifdef _HAVE_MPI_
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	J=J_sum;
+	#endif
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
Index: /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h	(revision 13395)
+++ /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h	(revision 13395)
@@ -0,0 +1,14 @@
+/*!\file:  ThicknessAcrossGradientx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _THICKNESSACROSSGRADIENT_H
+#define _THICKNESSACROSSGRADIENT_H
+
+#include "../../Container/Container.h"
+#include "../../classes/objects/objects.h"
+
+/* local prototypes: */
+void ThicknessAcrossGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+
+#endif
Index: /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 13395)
+++ /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 13395)
@@ -0,0 +1,37 @@
+/*!\file ThicknessAlongGradientx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./ThicknessAlongGradientx.h"
+
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+
+void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){
+
+	/*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*output: */
+	IssmDouble J=0;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for (i=0;i<elements->Size();i++){
+		element=(Element*)elements->GetObjectByOffset(i);
+		J+=element->ThicknessAlongGradient(process_units,weight_index);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	#ifdef _HAVE_MPI_
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	J=J_sum;
+	#endif
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
Index: /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h	(revision 13395)
+++ /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h	(revision 13395)
@@ -0,0 +1,14 @@
+/*!\file:  ThicknessAlongGradientx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _THICKNESSALONGGRADIENT_H
+#define _THICKNESSALONGGRADIENT_H
+
+#include "../../Container/Container.h"
+#include "../../classes/objects/objects.h"
+
+/* local prototypes: */
+void ThicknessAlongGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units,int weight_index);
+
+#endif
Index: /issm/trunk/src/c/modules/TimeAdaptx/TimeAdaptx.h
===================================================================
--- /issm/trunk/src/c/modules/TimeAdaptx/TimeAdaptx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/TimeAdaptx/TimeAdaptx.h	(revision 13395)
@@ -6,5 +6,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/TotalSmbx/TotalSmbx.cpp
===================================================================
--- /issm/trunk/src/c/modules/TotalSmbx/TotalSmbx.cpp	(revision 13395)
+++ /issm/trunk/src/c/modules/TotalSmbx/TotalSmbx.cpp	(revision 13395)
@@ -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(IssmDouble* pSmb, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units){
+
+	IssmDouble local_smb = 0;
+	IssmDouble 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/trunk/src/c/modules/TotalSmbx/TotalSmbx.h
===================================================================
--- /issm/trunk/src/c/modules/TotalSmbx/TotalSmbx.h	(revision 13395)
+++ /issm/trunk/src/c/modules/TotalSmbx/TotalSmbx.h	(revision 13395)
@@ -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(IssmDouble* pSmb, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units);
+
+#endif
Index: /issm/trunk/src/c/modules/TriMeshx/TriMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/TriMeshx/TriMeshx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/TriMeshx/TriMeshx.cpp	(revision 13395)
@@ -20,5 +20,5 @@
 /*}}}*/
 
-void TriMeshx(Matrix** pindex,Vector** px,Vector** py,Matrix** psegments,Vector** psegmentmarkerlist,DataSet* domain,DataSet* rifts,double area){
+void TriMeshx(SeqMat<IssmPDouble>** pindex,SeqVec<IssmPDouble>** px,SeqVec<IssmPDouble>** py,SeqMat<IssmPDouble>** psegments,SeqVec<IssmPDouble>** psegmentmarkerlist,DataSet* domain,DataSet* rifts,double area){
 
 	/*indexing: */
@@ -26,15 +26,15 @@
 
 	/*output: */
-	double* index=NULL;
-	Matrix* index_matrix=NULL;
-	double* x=NULL;
-	double* y=NULL;
-	double* segments=NULL;
-	Matrix* segments_matrix=NULL;
-	double* segmentmarkerlist=NULL;
+	IssmPDouble         *index             = NULL;
+	SeqMat<IssmPDouble> *index_matrix      = NULL;
+	double              *x                 = NULL;
+	double              *y                 = NULL;
+	double              *segments          = NULL;
+	SeqMat<IssmPDouble> *segments_matrix   = NULL;
+	double              *segmentmarkerlist = NULL;
 
 	/*intermediary: */
-	int      counter,counter2,backcounter;
-	Contour* contour=NULL;
+	int counter,counter2,backcounter;
+	Contour<IssmPDouble> *contour = NULL;
 
 	/* Triangle structures needed to call Triangle library routines: */
@@ -45,9 +45,9 @@
 	in.numberofpoints=0;
 	for (i=0;i<domain->Size();i++){
-		contour=(Contour*)domain->GetObjectByOffset(i);
+		contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i);
 		in.numberofpoints+=contour->nods-1;
 	}
 	for (i=0;i<rifts->Size();i++){
-		contour=(Contour*)rifts->GetObjectByOffset(i);
+		contour=(Contour<IssmPDouble>*)rifts->GetObjectByOffset(i);
 		in.numberofpoints+=contour->nods;
 	}
@@ -61,5 +61,5 @@
 	counter=0;
 	for (i=0;i<domain->Size();i++){
-		contour=(Contour*)domain->GetObjectByOffset(i);
+		contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i);
 		for (j=0;j<contour->nods-1;j++){
 			in.pointlist[2*counter+0]=contour->x[j];
@@ -69,5 +69,5 @@
 	}
 	for (i=0;i<rifts->Size();i++){
-		contour=(Contour*)rifts->GetObjectByOffset(i);
+		contour=(Contour<IssmPDouble>*)rifts->GetObjectByOffset(i);
 		for (j=0;j<contour->nods;j++){
 			in.pointlist[2*counter+0]=contour->x[j];
@@ -88,9 +88,9 @@
 	in.numberofsegments=0;
 	for (i=0;i<domain->Size();i++){
-		contour=(Contour*)domain->GetObjectByOffset(i);
+		contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i);
 		in.numberofsegments+=contour->nods-1;
 	}
 	for(i=0;i<rifts->Size();i++){
-		contour=(Contour*)rifts->GetObjectByOffset(i);
+		contour=(Contour<IssmPDouble>*)rifts->GetObjectByOffset(i);
 		/*for rifts, we have one less segment as we have vertices*/
 		in.numberofsegments+=contour->nods-1;
@@ -102,5 +102,5 @@
 	backcounter=0;
 	for (i=0;i<domain->Size();i++){
-		contour=(Contour*)domain->GetObjectByOffset(i);
+		contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i);
 		for (j=0;j<contour->nods-2;j++){
 			in.segmentlist[2*counter+0]=counter;
@@ -118,5 +118,5 @@
 	counter2=counter;
 	for (i=0;i<rifts->Size();i++){
-		contour=(Contour*)rifts->GetObjectByOffset(i);
+		contour=(Contour<IssmPDouble>*)rifts->GetObjectByOffset(i);
 		for (j=0;j<(contour->nods-1);j++){
 			in.segmentlist[2*counter2+0]=counter;
@@ -137,5 +137,5 @@
 		in.holelist = xNew<REAL>(in.numberofholes*2);
 		for (i=0;i<domain->Size()-1;i++){
-			contour=(Contour*)domain->GetObjectByOffset(i+1);
+			contour=(Contour<IssmPDouble>*)domain->GetObjectByOffset(i+1);
 			GridInsideHole(&in.holelist[2*i+0],&in.holelist[2*i+1],contour->nods-1,contour->x,contour->y);
 		}
@@ -192,13 +192,12 @@
 
 	/*Output : */
-	index_matrix=new Matrix(index,out.numberoftriangles,3,1); 
-	index_matrix->Convert(DENSE_SEQUENTIAL);
+	index_matrix=new SeqMat<IssmPDouble>(index,out.numberoftriangles,3,1.0);
 	*pindex=index_matrix;
 	
-	segments_matrix=new Matrix(segments,out.numberofsegments,3,1); segments_matrix->Convert(DENSE_SEQUENTIAL);
+	segments_matrix=new SeqMat<IssmPDouble>(segments,out.numberofsegments,3,1.0);
 	*psegments=segments_matrix;
 
-	*px=new Vector(x,out.numberofpoints);
-	*py=new Vector(y,out.numberofpoints);
-	*psegmentmarkerlist=new Vector(segmentmarkerlist,out.numberofsegments);
+	*px=new SeqVec<IssmPDouble>(x,out.numberofpoints);
+	*py=new SeqVec<IssmPDouble>(y,out.numberofpoints);
+	*psegmentmarkerlist=new SeqVec<IssmPDouble>(segmentmarkerlist,out.numberofsegments);
 }
Index: /issm/trunk/src/c/modules/TriMeshx/TriMeshx.h
===================================================================
--- /issm/trunk/src/c/modules/TriMeshx/TriMeshx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/TriMeshx/TriMeshx.h	(revision 13395)
@@ -8,8 +8,8 @@
 #include "string.h"
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void TriMeshx(Matrix** pindex,Vector** px,Vector** py,Matrix** psegments,Vector** psegmentmarkerlist,DataSet* domain,DataSet* rifts,double area);
+void TriMeshx(SeqMat<IssmPDouble>** pindex,SeqVec<IssmPDouble>** px,SeqVec<IssmPDouble>** py,SeqMat<IssmPDouble>** psegments,SeqVec<IssmPDouble>** psegmentmarkerlist,DataSet* domain,DataSet* rifts,double area);
 
 #endif  /* _TRIMESHX_H */
Index: /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.cpp
===================================================================
--- /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.cpp	(revision 13395)
@@ -7,5 +7,5 @@
 #include "../../include/include.h"
 #include "../../toolkits/toolkits.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../modules.h"
 
Index: /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.h
===================================================================
--- /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _TRIASEARCHX_H
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/UpdateConstraintsx/UpdateConstraintsx.h	(revision 13395)
@@ -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/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 
-void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vector* yg){
+void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vector<IssmDouble>* yg){
 	
 	int configuration_type;
Index: /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h	(revision 13395)
@@ -7,7 +7,7 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
-void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vector* yg);
+void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vector<IssmDouble>* yg);
 
 #endif  /* _UPDATESPCSX_H */
Index: /issm/trunk/src/c/modules/UpdateVertexPositionsx/UpdateVertexPositionsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/UpdateVertexPositionsx/UpdateVertexPositionsx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/UpdateVertexPositionsx/UpdateVertexPositionsx.cpp	(revision 13395)
@@ -13,5 +13,5 @@
 
 	int     i;
-	Vector*     vz        = NULL;
+	Vector<IssmDouble>*     vz        = NULL;
 	Vertex *vertex    = NULL;
 	IssmDouble *thickness = NULL;
@@ -23,5 +23,5 @@
 
 	/*Allocate vector*/
-	vz=new Vector(vertices->NumberOfVertices());
+	vz=new Vector<IssmDouble>(vertices->NumberOfVertices());
 
 	/*Update verices new geometry: */
Index: /issm/trunk/src/c/modules/VecMergex/VecMergex.cpp
===================================================================
--- /issm/trunk/src/c/modules/VecMergex/VecMergex.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/VecMergex/VecMergex.cpp	(revision 13395)
@@ -9,6 +9,5 @@
 #include "../../toolkits/toolkits.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
-
-void VecMergex(Vector* ug, Vector* uf, Nodes* nodes, Parameters* parameters, int SetEnum){
+void VecMergex(Vector<IssmDouble>* ug, Vector<IssmDouble>* uf, Nodes* nodes, Parameters* parameters, int SetEnum){
 
 	/*variables: */
Index: /issm/trunk/src/c/modules/VecMergex/VecMergex.h
===================================================================
--- /issm/trunk/src/c/modules/VecMergex/VecMergex.h	(revision 13394)
+++ /issm/trunk/src/c/modules/VecMergex/VecMergex.h	(revision 13395)
@@ -7,8 +7,8 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
-void VecMergex(Vector* ug, Vector* uf, Nodes* nodes, Parameters* parameters, int SetEnum);
+void VecMergex(Vector<IssmDouble>* ug, Vector<IssmDouble>* uf, Nodes* nodes, Parameters* parameters, int SetEnum);
 
 #endif  /* _VECMERGEX_H */
Index: /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.h
===================================================================
--- /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.h	(revision 13394)
+++ /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.h	(revision 13395)
@@ -7,5 +7,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 /* local prototypes: */
Index: /issm/trunk/src/c/modules/Xy2llx/Xy2llx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Xy2llx/Xy2llx.cpp	(revision 13394)
+++ /issm/trunk/src/c/modules/Xy2llx/Xy2llx.cpp	(revision 13395)
@@ -53,5 +53,5 @@
 	double  sl,rho,cm,T,chi;
 
-	if((sgn!=1) && (sgn!=-1)) _error2_("Sign should be either +1 or -1.\n");
+	if((sgn!=1) && (sgn!=-1)) _error_("Sign should be either +1 or -1.\n");
 
 	delta = central_meridian;
@@ -131,5 +131,5 @@
 		if(flag) _pprintLine_("Warning: expecting coordinates in polar stereographic (Std Latitude: 71S Meridian: 0).");
 	}
-	else _error2_("Sign should be either +1 or -1.\n");
+	else _error_("Sign should be either +1 or -1.\n");
 
 	return;
Index: /issm/trunk/src/c/modules/modules.h
===================================================================
--- /issm/trunk/src/c/modules/modules.h	(revision 13394)
+++ /issm/trunk/src/c/modules/modules.h	(revision 13395)
@@ -8,4 +8,5 @@
 /*Modules: */
 #include "./AddExternalResultx/AddExternalResultx.h"
+#include "./AutodiffDriversx/AutodiffDriversx.h"
 #include "./AverageFilterx/AverageFilterx.h"
 #include "./AverageOntoPartitionx/AverageOntoPartitionx.h"
@@ -25,4 +26,5 @@
 #include "./CreateNodalConstraintsx/CreateNodalConstraintsx.h"
 #include "./DakotaResponsesx/DakotaResponsesx.h"
+#include "./Delta18oParameterizationx/Delta18oParameterizationx.h"
 #include "./DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
 #include "./ElementConnectivityx/ElementConnectivityx.h"
@@ -36,4 +38,5 @@
 #include "./GroundinglineMigrationx/GroundinglineMigrationx.h"
 #include "./HoleFillerx/HoleFillerx.h"
+#include "./TotalSmbx/TotalSmbx.h"
 #include "./IceVolumex/IceVolumex.h"
 #include "./InputControlUpdatex/InputControlUpdatex.h"
@@ -101,4 +104,5 @@
 #include "./Reducevectorgtofx/Reducevectorgtofx.h"
 #include "./RequestedOutputsx/RequestedOutputsx.h"
+#include "./RequestedDependentsx/RequestedDependentsx.h"
 #include "./ResetConstraintsx/ResetConstraintsx.h"
 #include "./ResetCoordinateSystemx/ResetCoordinateSystemx.h"
@@ -117,4 +121,6 @@
 #include "./ThicknessAbsMisfitx/ThicknessAbsMisfitx.h"
 #include "./ThicknessAbsGradientx/ThicknessAbsGradientx.h"
+#include "./ThicknessAlongGradientx/ThicknessAlongGradientx.h"
+#include "./ThicknessAcrossGradientx/ThicknessAcrossGradientx.h"
 #include "./UpdateVertexPositionsx/UpdateVertexPositionsx.h"
 #include "./UpdateConstraintsx/UpdateConstraintsx.h"
Index: /issm/trunk/src/c/python/include/python_macros.h
===================================================================
--- /issm/trunk/src/c/python/include/python_macros.h	(revision 13394)
+++ /issm/trunk/src/c/python/include/python_macros.h	(revision 13395)
@@ -20,12 +20,25 @@
 /*The following macros hide the error exception handling in a matlab module. Just put 
  * MODULEBOOT(); and MODULEEND(); at the beginning and end of a module, and c++ exceptions 
- * will be trapped. Really nifty!*/
+ * will be trapped*/
+#define MODULEBOOT(); \
+	PyObject *output = PyTuple_New(NLHS);        \
+	int       nrhs   = (int)PyTuple_Size(args);  \
+	if(!output) return NULL;\
+	 try{ \
 
-#define MODULEBOOT(); ModuleBoot();  \
-	PyObject* output = PyTuple_New(NLHS); if (!output) return NULL;\
-			int nrhs = (int)PyTuple_Size(args);
-
-#define MODULEEND();  ModuleEnd(); \
-						 return output;
+#define MODULEEND(); }\
+  catch(ErrorException &exception){\
+	  PyErr_SetString(PyExc_TypeError,"ISSM Error"); \
+	  return NULL;\
+  } \
+	catch (exception &e){\
+		PyErr_SetString(PyExc_TypeError,exprintf("Standard exception: %s\n",e.what()));\
+		return NULL;\
+	}\
+	catch(...){\
+		PyErr_SetString(PyExc_TypeError,"An unexpected error occurred");\
+		return NULL;\
+	}\
+	return output;
 //}}}
 #if _PYTHON_MAJOR_ >=3
Index: /issm/trunk/src/c/python/io/CheckNumPythonArguments.cpp
===================================================================
--- /issm/trunk/src/c/python/io/CheckNumPythonArguments.cpp	(revision 13394)
+++ /issm/trunk/src/c/python/io/CheckNumPythonArguments.cpp	(revision 13395)
@@ -27,9 +27,9 @@
 	if (size==0){
 		function();
-		_error2_("usage: see above");
+		_error_("usage: see above");
 	}
 	else if (size!=NRHS ) {
 		function(); 
-		_error2_("usage error.");
+		_error_("usage error.");
 	}
 	return 1;
Index: /issm/trunk/src/c/python/io/FetchPythonData.cpp
===================================================================
--- /issm/trunk/src/c/python/io/FetchPythonData.cpp	(revision 13394)
+++ /issm/trunk/src/c/python/io/FetchPythonData.cpp	(revision 13395)
@@ -15,4 +15,6 @@
 #include "../../include/include.h"
 #include "../../shared/shared.h"
+#include "../../io/io.h"
+void FetchData(char** pstring,PyObject* py_string);
 
 /*Primitive data types*/
@@ -47,5 +49,5 @@
 	
 	/*check this is indeed a subtype of long type: */
-	if(!PyBool_Check(py_boolean))_error2_("expecting a boolean in input!");
+	if(!PyBool_Check(py_boolean))_error_("expecting a boolean in input!");
 
 	/*extract boolean: */
@@ -61,4 +63,5 @@
 
 	/*output: */
+	double* dmatrix=NULL;
 	double* matrix=NULL;
 	int M,N;
@@ -68,10 +71,14 @@
 	/*retrive dimensions: */
 	ndim=PyArray_NDIM((const PyArrayObject*)py_matrix);
-	if(ndim!=2)_error2_("expecting an MxN matrix in input!");
+	if(ndim!=2)_error_("expecting an MxN matrix in input!");
 	dims=PyArray_DIMS((PyArrayObject*)py_matrix);
 	M=dims[0]; N=dims[1];
 	
 	/*retrieve internal value: */
-	matrix=(double*)PyArray_DATA((PyArrayObject*)py_matrix);
+	dmatrix=(double*)PyArray_DATA((PyArrayObject*)py_matrix);
+
+	/*copy matrix: */
+	matrix=xNew<double>(M*N);
+	memcpy(matrix,dmatrix,(M*N)*sizeof(double));
 
 	/*output: */
@@ -81,8 +88,41 @@
 }
 /*}}}*/
+/*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)_error_("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){
 
 	/*output: */
+	double* dvector=NULL;
 	double* vector=NULL;
 	int M;
@@ -92,14 +132,180 @@
 	/*retrive dimensions: */
 	ndim=PyArray_NDIM((const PyArrayObject*)py_vector);
-	if(ndim!=1)_error2_("expecting an Mx1 vector in input!");
+	if(ndim!=1)_error_("expecting an Mx1 vector in input!");
 	dims=PyArray_DIMS((PyArrayObject*)py_vector);
 	M=dims[0]; 
 	
 	/*retrieve internal value: */
-	vector=(double*)PyArray_DATA((PyArrayObject*)py_vector);
+	dvector=(double*)PyArray_DATA((PyArrayObject*)py_vector);
+
+	/*copy vector: */
+	vector=xNew<double>(M);
+	memcpy(vector,dvector,(M)*sizeof(double));
 
 	/*output: */
 	if(pM)*pM=M;
 	if(pvector)*pvector=vector;
+}
+/*}}}*/
+
+/*ISSM objects*/
+/*FUNCTION FetchData(BamgGeom** pbamggeom,PyObject* py_dict){{{*/
+void FetchData(BamgGeom** pbamggeom,PyObject* py_dict){
+
+	/*Initialize output*/
+	BamgGeom* bamggeom=new BamgGeom();
+
+	/*Fetch all fields*/
+	FetchData(&bamggeom->Vertices,&bamggeom->VerticesSize[0],&bamggeom->VerticesSize[1],PyDict_GetItemString(py_dict,"Vertices"));
+	FetchData(&bamggeom->Edges, &bamggeom->EdgesSize[0], &bamggeom->EdgesSize[1], PyDict_GetItemString(py_dict,"Edges"));
+	FetchData(&bamggeom->Corners, &bamggeom->CornersSize[0], &bamggeom->CornersSize[1], PyDict_GetItemString(py_dict,"Corners"));
+	FetchData(&bamggeom->RequiredVertices,&bamggeom->RequiredVerticesSize[0],&bamggeom->RequiredVerticesSize[1],PyDict_GetItemString(py_dict,"RequiredVertices"));
+	FetchData(&bamggeom->RequiredEdges, &bamggeom->RequiredEdgesSize[0], &bamggeom->RequiredEdgesSize[1], PyDict_GetItemString(py_dict,"RequiredEdges"));
+	FetchData(&bamggeom->CrackedEdges,&bamggeom->CrackedEdgesSize[0],&bamggeom->CrackedEdgesSize[1],PyDict_GetItemString(py_dict,"CrackedEdges"));
+	FetchData(&bamggeom->SubDomains,&bamggeom->SubDomainsSize[0],&bamggeom->SubDomainsSize[1],PyDict_GetItemString(py_dict,"SubDomains"));
+
+	/*Assign output pointers:*/
+	*pbamggeom=bamggeom;
+}
+/*}}}*/
+/*FUNCTION FetchData(BamgMesh** pbamgmesh,PyObject* py_dict){{{*/
+void FetchData(BamgMesh** pbamgmesh,PyObject* py_dict){
+
+	/*Initialize output*/
+	BamgMesh* bamgmesh=new BamgMesh();
+
+	/*Fetch all fields*/
+	FetchData(&bamgmesh->Vertices,&bamgmesh->VerticesSize[0],&bamgmesh->VerticesSize[1],PyDict_GetItemString(py_dict,"Vertices"));
+	FetchData(&bamgmesh->Edges, &bamgmesh->EdgesSize[0], &bamgmesh->EdgesSize[1], PyDict_GetItemString(py_dict,"Edges"));
+	FetchData(&bamgmesh->Triangles, &bamgmesh->TrianglesSize[0], &bamgmesh->TrianglesSize[1], PyDict_GetItemString(py_dict,"Triangles"));
+	FetchData(&bamgmesh->CrackedEdges,&bamgmesh->CrackedEdgesSize[0],&bamgmesh->CrackedEdgesSize[1],PyDict_GetItemString(py_dict,"CrackedEdges"));
+	FetchData(&bamgmesh->VerticesOnGeomEdge,&bamgmesh->VerticesOnGeomEdgeSize[0],&bamgmesh->VerticesOnGeomEdgeSize[1],PyDict_GetItemString(py_dict,"VerticesOnGeomEdge"));
+	FetchData(&bamgmesh->VerticesOnGeomVertex,&bamgmesh->VerticesOnGeomVertexSize[0],&bamgmesh->VerticesOnGeomVertexSize[1],PyDict_GetItemString(py_dict,"VerticesOnGeomVertex"));
+	FetchData(&bamgmesh->EdgesOnGeomEdge, &bamgmesh->EdgesOnGeomEdgeSize[0], &bamgmesh->EdgesOnGeomEdgeSize[1], PyDict_GetItemString(py_dict,"EdgesOnGeomEdge"));
+	FetchData(&bamgmesh->IssmSegments,&bamgmesh->IssmSegmentsSize[0],&bamgmesh->IssmSegmentsSize[1],PyDict_GetItemString(py_dict,"IssmSegments"));
+
+	/*Assign output pointers:*/
+	*pbamgmesh=bamgmesh;
+}
+/*}}}*/
+/*FUNCTION FetchData(BamgOpts** pbamgopts,PyObject* py_dict){{{*/
+void FetchData(BamgOpts** pbamgopts,PyObject* py_dict){
+
+	/*Initialize output*/
+	BamgOpts* bamgopts=new BamgOpts();
+
+	/*Fetch all fields*/
+	FetchData(&bamgopts->anisomax,PyDict_GetItemString(py_dict,"anisomax"));
+	FetchData(&bamgopts->cutoff,PyDict_GetItemString(py_dict,"cutoff"));
+	FetchData(&bamgopts->coeff,PyDict_GetItemString(py_dict,"coeff"));
+	FetchData(&bamgopts->errg,PyDict_GetItemString(py_dict,"errg"));
+	FetchData(&bamgopts->gradation,PyDict_GetItemString(py_dict,"gradation"));
+	FetchData(&bamgopts->Hessiantype,PyDict_GetItemString(py_dict,"Hessiantype"));
+	FetchData(&bamgopts->MaxCornerAngle,PyDict_GetItemString(py_dict,"MaxCornerAngle"));
+	FetchData(&bamgopts->maxnbv,PyDict_GetItemString(py_dict,"maxnbv"));
+	FetchData(&bamgopts->maxsubdiv,PyDict_GetItemString(py_dict,"maxsubdiv"));
+	FetchData(&bamgopts->Metrictype,PyDict_GetItemString(py_dict,"Metrictype"));
+	FetchData(&bamgopts->nbjacobi,PyDict_GetItemString(py_dict,"nbjacobi"));
+	FetchData(&bamgopts->nbsmooth,PyDict_GetItemString(py_dict,"nbsmooth"));
+	FetchData(&bamgopts->omega,PyDict_GetItemString(py_dict,"omega"));
+	FetchData(&bamgopts->power,PyDict_GetItemString(py_dict,"power"));
+	FetchData(&bamgopts->verbose,PyDict_GetItemString(py_dict,"verbose"));
+
+	FetchData(&bamgopts->Crack,PyDict_GetItemString(py_dict,"Crack"));
+	FetchData(&bamgopts->geometricalmetric,PyDict_GetItemString(py_dict,"geometricalmetric"));
+	FetchData(&bamgopts->KeepVertices,PyDict_GetItemString(py_dict,"KeepVertices"));
+	FetchData(&bamgopts->splitcorners,PyDict_GetItemString(py_dict,"splitcorners"));
+
+	FetchData(&bamgopts->hmin,PyDict_GetItemString(py_dict,"hmin"));
+	FetchData(&bamgopts->hmax,PyDict_GetItemString(py_dict,"hmax"));
+	FetchData(&bamgopts->hminVertices,&bamgopts->hminVerticesSize[0],&bamgopts->hminVerticesSize[1],PyDict_GetItemString(py_dict,"hminVertices"));
+	FetchData(&bamgopts->hmaxVertices,&bamgopts->hmaxVerticesSize[0],&bamgopts->hmaxVerticesSize[1],PyDict_GetItemString(py_dict,"hmaxVertices"));
+	FetchData(&bamgopts->hVertices,&bamgopts->hVerticesSize[0],&bamgopts->hVerticesSize[1],PyDict_GetItemString(py_dict,"hVertices"));
+	FetchData(&bamgopts->metric,&bamgopts->metricSize[0],&bamgopts->metricSize[1],PyDict_GetItemString(py_dict,"metric"));
+	FetchData(&bamgopts->field,&bamgopts->fieldSize[0],&bamgopts->fieldSize[1],PyDict_GetItemString(py_dict,"field"));
+	FetchData(&bamgopts->err,&bamgopts->errSize[0],&bamgopts->errSize[1],PyDict_GetItemString(py_dict,"err"));
+
+	/*Additional checks*/
+	bamgopts->Check();
+
+	/*Assign output pointers:*/
+	*pbamgopts=bamgopts;
+}
+/*}}}*/
+/*FUNCTION FetchData(Options** poptions,int istart, int nrhs,PyObject* py_tuple){{{*/
+void FetchData(Options** poptions,int istart, int nrhs,PyObject* py_tuple){
+
+	char   *name   = NULL;
+	Option *option = NULL;
+
+	/*Initialize output*/
+	Options* options=new Options();
+
+	/*Fetch all options*/
+	for (int i=istart; i<nrhs; i=i+2){
+		if (!PyString_Check(PyTuple_GetItem(py_tuple,(Py_ssize_t)i))) _error_("Argument " << i+1 << " must be name of option");
+
+		FetchData(&name,PyTuple_GetItem(py_tuple,(Py_ssize_t)i));
+		if(i+1 == nrhs) _error_("Argument " << i+2 << " must exist and be value of option \"" << name << "\".");
+
+		_pprintLine_("FetchData for Options not implemented yet, ignoring option \"" << name << "\"!");
+
+//		option=(Option*)OptionParse(name,&PyTuple_GetItem(py_tuple,(Py_ssize_t)(i+1)));
+//		options->AddOption(option);
+//		option=NULL;
+	}
+
+	/*Assign output pointers:*/
+	*poptions=options;
+}
+/*}}}*/
+/*FUNCTION FetchData(DataSet** pcontours,PyObject* py_list){{{*/
+void FetchData(DataSet** pcontours,PyObject* py_list){
+
+	int              numcontours,test1,test2;
+	char            *contourname = NULL;
+	DataSet         *contours    = NULL;
+	Contour<double> *contouri    = NULL;
+	PyObject        *py_dicti    = NULL;
+	PyObject        *py_item     = NULL;
+
+	if (PyString_Check(py_list)){
+		FetchData(&contourname,py_list);
+		contours=DomainOutlineRead<double>(contourname);
+	}
+	else if(PyList_Check(py_list)){
+
+		contours=new DataSet(0);
+		numcontours=(int)PyList_Size(py_list);
+
+		for(int i=0;i<numcontours;i++){
+
+			contouri=xNew<Contour<double> >(1);
+			py_dicti=PyList_GetItem(py_list,(Py_ssize_t)i);
+
+			py_item = PyDict_GetItemString(py_dicti,"nods");
+			if(!py_item) _error_("input structure does not have a 'nods' field");
+			FetchData(&contouri->nods,py_item);
+
+			py_item = PyDict_GetItemString(py_dicti,"x");
+			if(!py_item) _error_("input structure does not have a 'x' field");
+			FetchData(&contouri->x,&test1,&test2,py_item);
+			if(test1!=contouri->nods || test2!=1) _error_("field x should be of size ["<<contouri->nods<<" 1]");
+
+			py_item = PyDict_GetItemString(py_dicti,"y");
+			if(!py_item) _error_("input structure does not have a 'y' field");
+			FetchData(&contouri->y,&test1,&test2,py_item);
+			if(test1!=contouri->nods || test2!=1) _error_("field y should be of size ["<<contouri->nods<<" 1]");
+
+			contours->AddObject(contouri);
+		}
+	}
+	else{
+		_error_("Contour is neither a string nor a structure and cannot be loaded");
+	}
+
+	/*clean-up and assign output pointer*/
+	xDelete<char>(contourname);
+	*pcontours=contours;
 }
 /*}}}*/
@@ -113,5 +319,4 @@
 	char* string=NULL;
 
-	
 	/*convert to bytes format: */
 	PyUnicode_FSConverter(py_unicode,&py_bytes);
@@ -131,6 +336,8 @@
 	/*extract internal string: */
 	string=PyString_AsString(py_string);
-	
-	*pstring=string;
+
+	/*copy string (note strlen does not include trailing NULL): */
+	*pstring=xNew<char>(strlen(string)+1);
+	memcpy(*pstring,string,(strlen(string)+1)*sizeof(char));
 }
 /*}}}*/
Index: /issm/trunk/src/c/python/io/WritePythonData.cpp
===================================================================
--- /issm/trunk/src/c/python/io/WritePythonData.cpp	(revision 13394)
+++ /issm/trunk/src/c/python/io/WritePythonData.cpp	(revision 13395)
@@ -19,6 +19,13 @@
 #include "../../io/io.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
+PyObject* PyArrayFromCopiedData(int dims[2],double* data);
 
+/*Primitive data types*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index,int integer){{{*/
+void WriteData(PyObject* py_tuple, int index, int integer){
+	
+	PyTuple_SetItem(py_tuple, index, PyInt_FromSsize_t(integer));
 
+}/*}}}*/
 /*FUNCTION WriteData(PyObject* py_tuple,int index,char* string){{{*/
 void WriteData(PyObject* py_tuple, int index, char* string){
@@ -27,6 +34,82 @@
 
 }/*}}}*/
-/*FUNCTION WriteData(PyObject* tuple,int index,Matrix* matrix){{{*/
-void WriteData(PyObject* tuple,int index,Matrix* matrix){
+/*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){
+
+	npy_intp dims[2]={0,0};
+	PyObject* array=NULL;
+
+	dims[0]=(npy_intp)M;
+	dims[1]=(npy_intp)N;
+	array=PyArray_SimpleNewFromData(2,dims,NPY_DOUBLE,matrix);
+
+	PyTuple_SetItem(tuple, index, array);
+}/*}}}*/
+
+/*ISSM objects*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index,BamgGeom* bamggeom){{{*/
+void WriteData(PyObject* py_tuple,int index,BamgGeom* bamggeom){
+
+	PyObject* dict=NULL;
+
+	dict=PyDict_New();
+
+	PyDict_SetItemString(dict,"Vertices",PyArrayFromCopiedData(bamggeom->VerticesSize,bamggeom->Vertices));
+	PyDict_SetItemString(dict,"Edges",PyArrayFromCopiedData(bamggeom->EdgesSize,bamggeom->Edges));
+	PyDict_SetItemString(dict,"TangentAtEdges",PyArrayFromCopiedData(bamggeom->TangentAtEdgesSize,bamggeom->TangentAtEdges));
+	PyDict_SetItemString(dict,"Corners",PyArrayFromCopiedData(bamggeom->CornersSize,bamggeom->Corners));
+	PyDict_SetItemString(dict,"RequiredVertices",PyArrayFromCopiedData(bamggeom->RequiredVerticesSize,bamggeom->RequiredVertices));
+	PyDict_SetItemString(dict,"RequiredEdges",PyArrayFromCopiedData(bamggeom->RequiredEdgesSize,bamggeom->RequiredEdges));
+	PyDict_SetItemString(dict,"CrackedEdges",PyArrayFromCopiedData(bamggeom->CrackedEdgesSize,bamggeom->CrackedEdges));
+	PyDict_SetItemString(dict,"SubDomains",PyArrayFromCopiedData(bamggeom->SubDomainsSize,bamggeom->SubDomains));
+
+	PyTuple_SetItem(py_tuple, index, dict);
+}
+/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index,BamgMesh* bamgmesh){{{*/
+void WriteData(PyObject* py_tuple,int index,BamgMesh* bamgmesh){
+
+	PyObject* dict=NULL;
+
+	dict=PyDict_New();
+
+	PyDict_SetItemString(dict,"Vertices",PyArrayFromCopiedData(bamgmesh->VerticesSize,bamgmesh->Vertices));
+	PyDict_SetItemString(dict,"Edges",PyArrayFromCopiedData(bamgmesh->EdgesSize,bamgmesh->Edges));
+	PyDict_SetItemString(dict,"Triangles",PyArrayFromCopiedData(bamgmesh->TrianglesSize,bamgmesh->Triangles));
+	PyDict_SetItemString(dict,"Quadrilaterals",PyArrayFromCopiedData(bamgmesh->QuadrilateralsSize,bamgmesh->Quadrilaterals));
+	PyDict_SetItemString(dict,"IssmEdges",PyArrayFromCopiedData(bamgmesh->IssmEdgesSize,bamgmesh->IssmEdges));
+	PyDict_SetItemString(dict,"IssmSegments",PyArrayFromCopiedData(bamgmesh->IssmSegmentsSize,bamgmesh->IssmSegments));
+	PyDict_SetItemString(dict,"VerticesOnGeomVertex",PyArrayFromCopiedData(bamgmesh->VerticesOnGeomVertexSize,bamgmesh->VerticesOnGeomVertex));
+	PyDict_SetItemString(dict,"VerticesOnGeomEdge",PyArrayFromCopiedData(bamgmesh->VerticesOnGeomEdgeSize,bamgmesh->VerticesOnGeomEdge));
+	PyDict_SetItemString(dict,"EdgesOnGeomEdge",PyArrayFromCopiedData(bamgmesh->EdgesOnGeomEdgeSize,bamgmesh->EdgesOnGeomEdge));
+	PyDict_SetItemString(dict,"SubDomains",PyArrayFromCopiedData(bamgmesh->SubDomainsSize,bamgmesh->SubDomains));
+	PyDict_SetItemString(dict,"SubDomainsFromGeom",PyArrayFromCopiedData(bamgmesh->SubDomainsFromGeomSize,bamgmesh->SubDomainsFromGeom));
+	PyDict_SetItemString(dict,"ElementConnectivity",PyArrayFromCopiedData(bamgmesh->ElementConnectivitySize,bamgmesh->ElementConnectivity));
+	PyDict_SetItemString(dict,"NodalConnectivity",PyArrayFromCopiedData(bamgmesh->NodalConnectivitySize,bamgmesh->NodalConnectivity));
+	PyDict_SetItemString(dict,"NodalElementConnectivity",PyArrayFromCopiedData(bamgmesh->NodalElementConnectivitySize,bamgmesh->NodalElementConnectivity));
+	PyDict_SetItemString(dict,"CrackedVertices",PyArrayFromCopiedData(bamgmesh->CrackedVerticesSize,bamgmesh->CrackedVertices));
+	PyDict_SetItemString(dict,"CrackedEdges",PyArrayFromCopiedData(bamgmesh->CrackedEdgesSize,bamgmesh->CrackedEdges));
+
+	PyTuple_SetItem(py_tuple, index, dict);
+}
+/*}}}*/
+/*FUNCTION PyArrayFromCopiedData(int dims[2],double* data){{{*/
+PyObject* PyArrayFromCopiedData(int dims[2],double* data){
+
+	double* pydata;
+	npy_intp pydims[2]={0,0};
+
+	/*  note that PyArray_SimpleNewFromData does not copy the data, so that when the original
+	object (e.g. bamggeom,bamgmesh) is deleted, the data is gone.  */
+
+	pydims[0]=(npy_intp)dims[0];
+	pydims[1]=(npy_intp)dims[1];
+	pydata=xNew<IssmDouble>(dims[0]*dims[1]);
+	memcpy(pydata,data,dims[0]*dims[1]*sizeof(double));
+	return PyArray_SimpleNewFromData(2,pydims,NPY_DOUBLE,pydata);
+}
+/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index,SeqMat<double>* matrix){{{*/
+void WriteData(PyObject* py_tuple,int index,SeqMat<double>* matrix){
 	
 	int M,N;
@@ -41,10 +124,9 @@
 	array=PyArray_SimpleNewFromData(2,dims,NPY_DOUBLE,buffer);
 	
-	PyTuple_SetItem(tuple, index, array);
-
+	PyTuple_SetItem(py_tuple, index, array);
 
 }/*}}}*/
-/*FUNCTION WriteData(PyObject* py_tuple,int index,Vector* vector){{{*/
-void WriteData(PyObject* tuple,int index,Vector* vector){
+/*FUNCTION WriteData(PyObject* py_tuple,int index,SeqVec<double>* vector){{{*/
+void WriteData(PyObject* tuple,int index,SeqVec<double>* vector){
 	
 	int M;
@@ -59,19 +141,4 @@
 	
 	PyTuple_SetItem(tuple, index, array);
-
-
 }
 /*}}}*/
-/*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){
-	
-	npy_intp dims[2]={0,0};
-	PyObject* array=NULL;
-	
-	dims[0]=(npy_intp)M;
-	dims[1]=(npy_intp)N;
-	array=PyArray_SimpleNewFromData(2,dims,NPY_DOUBLE,matrix);
-	
-	PyTuple_SetItem(tuple, index, array);
-
-}/*}}}*/
Index: /issm/trunk/src/c/python/io/pythonio.h
===================================================================
--- /issm/trunk/src/c/python/io/pythonio.h	(revision 13394)
+++ /issm/trunk/src/c/python/io/pythonio.h	(revision 13395)
@@ -12,43 +12,28 @@
 #endif 
 
-
-#include "../../objects/objects.h"
+#include "../../classes/classes.h"
 #include "../../Container/Container.h"
 #include "../../include/include.h"
 
-class DataSet;
-class Parameters;
+void WriteData(PyObject* py_tuple,int index, double* matrix, int M,int N);
+void WriteData(PyObject* py_tuple,int index, int integer);
+void WriteData(PyObject* py_tuple,int index, char* string);
+void WriteData(PyObject* py_tuple,int index, SeqMat<double>* matrix);
+void WriteData(PyObject* py_tuple,int index, SeqVec<double>* vector);
+void WriteData(PyObject* py_tuple,int index, BamgGeom* bamggeom);
+void WriteData(PyObject* py_tuple,int index, BamgMesh* bamgmesh);
 
-//void WriteData(PyObject* py_tuple,DataSet* dataset);
-//void WriteData(PyObject* py_tuple,int*    matrix, int M,int N);
-//void WriteData(PyObject* py_tuple,double* vector, int M);
-//void WriteData(PyObject* py_tuple,int integer);
-//void WriteData(PyObject* py_tuple,bool boolean);
-//void WriteData(PyObject* py_tuple,double scalar);
-//void WriteData(DataHandle* py_tuple,Parameters* parameters);
-void WriteData(PyObject* py_tuple, int index, double* matrix, int M,int N);
-void WriteData(PyObject* py_tuple, int index, char* string);
-void WriteData(PyObject* py_tuple, int index, Matrix* matrix);
-void WriteData(PyObject* py_tuple, int index, Vector* vector);
-
-
-//void FetchData(DataSet** pdataset,PyObject* py_ref);
-//void FetchData(double** pmatrix,int* pnumel,int* pndims,int** psize,PyObject* py_ref);
-//void FetchData(int** pmatrix,int* pM,int *pN,PyObject* py_ref);
-//void FetchData(bool** pmatrix,int* pM,int *pN,PyObject* py_ref);
-//void FetchData(bool** pmatrix,int* pnumel,int* pndims,int** psize,PyObject* py_ref);
-//void FetchData(Matrix** pmatrix,PyObject* py_ref);
-//void FetchData(int** pvector,int* pM,PyObject* py_ref);
-//void FetchData(float** pvector,int* pM,PyObject* py_ref);
-//void FetchData(bool** pvector,int* pM,PyObject* py_ref);
-//void FetchData(Vector** pvector,PyObject* py_ref);
-//void FetchData(char** pmatrix,int* pnumel,int* pndims,int** psize,PyObject* py_ref);
-//void FetchData(Parameters** pparameters, DataHandle py_ref);
 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(BamgGeom** bamggeom,PyObject* py_dict);
+void FetchData(BamgMesh** bamgmesh,PyObject* py_dict);
+void FetchData(BamgOpts** bamgopts,PyObject* py_dict);
+void FetchData(Options** poptions,int istart, int nrhs,PyObject* py_tuple);
+void FetchData(DataSet** pcontours,PyObject* py_list);
 
 int CheckNumPythonArguments(PyObject* inputs,int NRHS, void (*function)( void ));
Index: /issm/trunk/src/c/shared/Alloc/alloc.cpp
===================================================================
--- /issm/trunk/src/c/shared/Alloc/alloc.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Alloc/alloc.cpp	(revision 13395)
@@ -25,42 +25,7 @@
 #include "../Exceptions/exceptions.h"
 #include "../../include/include.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
-void* xmalloc(int size){
-
-	void* memptr=NULL;
-
-	if(!size)_error2_("attempting to 0 size allocation!");
-
-	/* Use the c library to do the allocation: */
-	memptr=malloc(size);
-	if(!memptr) _error2_("memory allocation failed!");
-
-	return memptr;
-}
-
-void* xcalloc(int n,int size){
-
-	void* memptr=NULL;
-	
-	if(!size)_error2_("attempting to 0 size allocation!");
-
-	/* Use the c library to do the allocation: */
-	memptr=calloc(n,size);
-	if(!memptr) _error2_("memory allocation failed!");
-
-	return memptr;
-}
-
-void xfree(void* *pv){
-
-	if (pv && *pv){
-		free(*pv);
-
-		*pv=NULL;
-	}
-}
-
-void xdelete(Matrix** pv){
+void xdelete(Matrix<IssmDouble>** pv){
 	
 	if (pv && *pv){
@@ -73,5 +38,5 @@
 }
 
-void xdelete(Vector** pv){
+void xdelete(Vector<IssmDouble>** pv){
 
 	if (pv && *pv){
@@ -83,15 +48,2 @@
 	}
 }
-
-void* xrealloc( void* pv, int size){
-	
-	register void* value=NULL;
-	
-	if(!size)_error2_("attempting to realloc to zero");
-	value = (void*)realloc(pv,size);
-
-	if (value == NULL) {
-		_error2_("virtual memory exhausted");
-	}
-	return value;
-}
Index: /issm/trunk/src/c/shared/Alloc/alloc.h
===================================================================
--- /issm/trunk/src/c/shared/Alloc/alloc.h	(revision 13394)
+++ /issm/trunk/src/c/shared/Alloc/alloc.h	(revision 13395)
@@ -5,12 +5,11 @@
 #ifndef _ALLOC_H_
 #define _ALLOC_H_
-class Matrix;
-class Vector;
-void* xmalloc(int size);
-void* xcalloc(int n,int size);
-void  xfree(void** pvptr);
-void* xrealloc ( void* pv, int size);
-void xdelete(Matrix** pvptr);
-void xdelete(Vector** pvptr);
 
+#include "../../include/include.h"
+#include "./xNewDelete.h"
+
+template <class doubletype> class Matrix;
+template <class doubletype> class Vector;
+void xdelete(Matrix<IssmDouble>** pvptr);
+void xdelete(Vector<IssmDouble>** pvptr);
 #endif
Index: sm/trunk/src/c/shared/Alloc/alloc_module.cpp
===================================================================
--- /issm/trunk/src/c/shared/Alloc/alloc_module.cpp	(revision 13394)
+++ 	(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/trunk/src/c/shared/Alloc/alloc_module.h
===================================================================
--- /issm/trunk/src/c/shared/Alloc/alloc_module.h	(revision 13394)
+++ 	(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/trunk/src/c/shared/Alloc/xNewDelete.h
===================================================================
--- /issm/trunk/src/c/shared/Alloc/xNewDelete.h	(revision 13394)
+++ /issm/trunk/src/c/shared/Alloc/xNewDelete.h	(revision 13395)
@@ -34,4 +34,29 @@
 
 template <class T> 
+T** xNew(unsigned int dim1, unsigned int dim2) {
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+  T* buf=new T[dim1*dim2];
+  assert(buf );
+  T** aT_pp =new T*[dim1];
+  assert(aT_pp );
+  for (unsigned int i=0;i<dim1;++i) {
+    aT_pp [i]=buf;
+    buf+=dim2;
+  }
+  return aT_pp ;
+#else
+  T* buf=(T*)malloc(dim1*dim2*sizeof(T));
+  assert(buf );
+  T** aT_pp =(T**)malloc(dim1*sizeof(T*));
+  assert(aT_pp );
+  for (unsigned int i=0;i<dim1;++i) {
+    aT_pp [i]=buf;
+    buf+=dim2;
+  }
+  return aT_pp ;
+#endif
+}
+
+template <class T>
 T* xNewZeroInit(unsigned int size) {
 #ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
@@ -48,5 +73,19 @@
 
 template <class T>
-void xDelete(T*& aT_p) { 
+void xDelete(T**& aT_pp) {
+  if (aT_pp) {
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+    delete [](*aT_pp);
+    delete [](aT_pp);
+#else
+    free((void*)*aT_pp)
+    free((void**)aT_pp);
+#endif
+  }
+  aT_pp=0;
+}
+
+template <class T>
+void xDelete(T*& aT_p) {
   if (aT_p) 
 #ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
@@ -61,34 +100,34 @@
 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;
+	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;
+	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 
 }
Index: /issm/trunk/src/c/shared/Bamg/OppositeAngle.h
===================================================================
--- /issm/trunk/src/c/shared/Bamg/OppositeAngle.h	(revision 13394)
+++ /issm/trunk/src/c/shared/Bamg/OppositeAngle.h	(revision 13395)
@@ -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/trunk/src/c/shared/Bamg/det.h
===================================================================
--- /issm/trunk/src/c/shared/Bamg/det.h	(revision 13394)
+++ /issm/trunk/src/c/shared/Bamg/det.h	(revision 13395)
@@ -2,5 +2,5 @@
 #define _BAMGDET_H_
 
-#include "../../objects/Bamg/include.h"
+#include "../../classes/bamg/include.h"
 
 namespace bamg {
Index: /issm/trunk/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp	(revision 13395)
+++ /issm/trunk/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp	(revision 13395)
@@ -0,0 +1,32 @@
+/* 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;
+
+  glacialindex = 0;//(Delta18oTime-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceTime-Delta18oSurfacePresent))
+  //  /(Delta18oLgm-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceLgm-Delta18oSurfacePresent));
+
+  for (int imonth = 0; imonth<12; imonth++){  
+    monthlytemperaturestmp[imonth] = glacialindex*TemperaturesLgm[imonth] + (1-glacialindex)*TemperaturesPresentday[imonth];
+    //monthlyprectmp[imonth] = 1.5*pow(2,((monthlytemperaturestmp[imonth]-273.15-0)/10)); //equation from rob's paper
+    monthlyprectmp[imonth] = PrecipitationsPresentday[imonth];
+
+    /*Assign output pointer*/
+    *(monthlytemperaturesout+imonth) = monthlytemperaturestmp[imonth];
+    *(monthlyprecout+imonth) = monthlyprectmp[imonth];
+  }
+  // printf(" tempera %f\n",monthlytemperaturestmp[1]);
+}
Index: /issm/trunk/src/c/shared/Elements/CoordinateSystemTransform.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/CoordinateSystemTransform.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Elements/CoordinateSystemTransform.cpp	(revision 13395)
@@ -22,5 +22,5 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
@@ -67,5 +67,5 @@
 				break;
 			default:
-				_error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+				_error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
Index: /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 13395)
@@ -43,5 +43,5 @@
   IssmDouble frzndd = 0.;  
   
-  IssmDouble tstar;                        // monthly mean surface temp
+  IssmDouble tstar;          // monthly mean surface temp
   IssmDouble Tsum= 0.;       // average summer (JJA) temperature
   IssmDouble Tsurf = 0.;     // average annual temperature    
@@ -61,5 +61,5 @@
   
   sconv=(rho_water/rho_ice)/12.; //rhow_rain/rhoi / 12 months
-  
+
   /*PDD constant*/
   siglim = 2.5*signorm; 
@@ -80,5 +80,5 @@
       if (tstar < PDup){
 	pd = 1.;
-	if (tstar >= -siglimc){ pd = pds[int(tstar/DT + siglim0c)];}}
+	if (tstar >= -siglimc){ pd = pds[reCast<int,IssmDouble>(tstar/DT + siglim0c)];}}
       else { 
 	pd = 0.;}
@@ -100,5 +100,5 @@
       if (tstar >= siglim) {pdd = pdd + tstar*deltm;}
       else if (tstar> -siglim){
-	pddsig=pdds[int(tstar/DT + siglim0)];
+	pddsig=pdds[reCast<int,IssmDouble>(tstar/DT + siglim0)];
 	pdd = pdd + pddsig*deltm;
 	frzndd = frzndd - (tstar-pddsig)*deltm;}
Index: /issm/trunk/src/c/shared/Elements/PrintArrays.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/PrintArrays.cpp	(revision 13395)
+++ /issm/trunk/src/c/shared/Elements/PrintArrays.cpp	(revision 13395)
@@ -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/trunk/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp	(revision 13395)
@@ -31,5 +31,5 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
Index: /issm/trunk/src/c/shared/Elements/TransformLoadVectorCoord.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/TransformLoadVectorCoord.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Elements/TransformLoadVectorCoord.cpp	(revision 13395)
@@ -30,5 +30,5 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
Index: /issm/trunk/src/c/shared/Elements/TransformSolutionCoord.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/TransformSolutionCoord.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Elements/TransformSolutionCoord.cpp	(revision 13395)
@@ -31,5 +31,5 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
Index: /issm/trunk/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp	(revision 13395)
@@ -31,5 +31,5 @@
 			case XYEnum:   numdofs+=2; break;
 			case XYZPEnum: numdofs+=4; break;
-			default: _error2_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
 		}
 	}
Index: /issm/trunk/src/c/shared/Elements/elements.h
===================================================================
--- /issm/trunk/src/c/shared/Elements/elements.h	(revision 13394)
+++ /issm/trunk/src/c/shared/Elements/elements.h	(revision 13395)
@@ -4,7 +4,7 @@
 
 #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;
@@ -13,9 +13,16 @@
 IssmDouble Paterson(IssmDouble temperature);
 IssmDouble Arrhenius(IssmDouble temperature,IssmDouble depth,IssmDouble n);
-IssmDouble PddSurfaceMassBlance(IssmDouble* monthlytemperatures,  IssmDouble* monthlyprec, IssmDouble* pdds, IssmDouble* pds, IssmDouble signorm, IssmDouble yts, IssmDouble h, IssmDouble s, IssmDouble rho_ice, IssmDouble rho_water);
+IssmDouble 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(IssmDouble** ptransform,Node** nodes,int numnodes,int* cs_array);
@@ -30,32 +37,7 @@
 #endif
 
-inline void printarray(IssmPDouble* array,int lines,int cols=1){
-	_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_("");
-}
-inline void printarray(int* array,int lines,int cols=1){
-	_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_("");
-}
-inline 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;
-	}
-}
-
+/*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/trunk/src/c/shared/Exceptions/Exceptions.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/Exceptions.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Exceptions/Exceptions.cpp	(revision 13395)
@@ -39,5 +39,5 @@
 }
 
-void ErrorException::Report(){
+void ErrorException::Report() const{
 	extern int my_rank;
 	extern int num_procs;
Index: /issm/trunk/src/c/shared/Exceptions/exceptions.h
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/exceptions.h	(revision 13394)
+++ /issm/trunk/src/c/shared/Exceptions/exceptions.h	(revision 13395)
@@ -27,5 +27,5 @@
 	~ErrorException() throw();
 	virtual const char *what() const throw();
-	void Report();
+	void Report() const;
 
 };
Index: sm/trunk/src/c/shared/Exp/DomainOutlineRead.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exp/DomainOutlineRead.cpp	(revision 13394)
+++ 	(revision )
@@ -1,153 +1,0 @@
-/*!\file:  DomainOutlineRead.cpp
- * \brief DomainOutlineRead.c: read the vertex coordinates defined in a domain 
- * outline from Argus (.exp file). The first contour in the file is for 
- * the outside domain outline. The following contours represent holes in
- * the domain.
- */
-
-#include <stdio.h>
-#include <cstring> 
-#include "../Alloc/alloc.h"
-#include "../../include/include.h"
-#include "../../objects/objects.h"
-#include "../Exceptions/exceptions.h"
-#include "../../Container/DataSet.h"
-
-int DomainOutlineRead(int* pnprof,int** pprofnvertices,double*** ppprofx,double*** ppprofy,bool** pclosed,char* domainname){
-	
-	/*indexing: */
-	int i,counter;
-
-	/*I/O: */
-	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
-
-	/*For each profile: */
-	int     n;
-	double *x  = NULL;
-	double *y  = NULL;
-	bool    cl;
-
-	/*open domain outline file for reading: */
-	if ((fid=fopen(domainname,"r"))==NULL){
-		_error2_("could not find domain file " << domainname); 
-	}
-
-	/*Do a first pass through the domainname file, to figure out how many profiles 
-	 *we need to read: */
-	nprof=1;
-	for(;;){
-		fscanf(fid,"%256s %256s\n",chardummy,chardummy);
-		fscanf(fid,"%256s %256s\n",chardummy,chardummy);
-		fscanf(fid,"%256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy);
-		fscanf(fid,"%20u %256s\n",&n,chardummy);
-		fscanf(fid,"%256s %256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
-		for (i=0;i<n;i++){
-			fscanf(fid,"%20lf %20lf\n",&ddummy,&ddummy);
-		}
-		/*Ok, we have faked one profile reading, check whether we are at the end of the file, otherwise, keep fake reading next profile:*/
-		if (feof(fid)){
-			break;
-		}
-		nprof++;
-	}
-	
-	/*Allocate and initialize all the profiles: */
-	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=xNew<bool>(nprof);
-
-	/*Reaset file pointer to beginning of file: */
-	fseek(fid,0,SEEK_SET);
-
-	/*Start reading profiles: */
-	for(counter=0;counter<nprof;counter++){
-
-		/*Skip header: */
-		fscanf(fid,"%256s %256s\n",chardummy,chardummy);
-		fscanf(fid,"%256s %256s\n",chardummy,chardummy);
-		fscanf(fid,"%256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy);
-		
-		/*Get number of profile vertices: */
-		fscanf(fid,"%20u %256s\n",&n,chardummy);
-	
-		/*Skip next line: */
-		fscanf(fid,"%256s %256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
-
-		/*Allocate vertices: */
-		x=xNew<double>(n);
-		y=xNew<double>(n);
-		
-		/*Read vertices: */
-		for (i=0;i<n;i++){
-			fscanf(fid,"%20lf %20lf\n",&x[i],&y[i]);
-		}
-
-		/*Now check that we are dealing with open contours: */
-		cl=false;
-		if((x[0]==x[n-1]) && (y[0]==y[n-1])){
-			cl=true;
-		}
-
-		/*Assign pointers: */
-		profnvertices[counter]=n;
-		pprofx[counter]=x;
-		pprofy[counter]=y;
-		closed[counter]=cl;
-	}
-
-	/*close domain outline file: */
-	fclose(fid);
-
-	/*Assign output pointers: */
-	*pnprof=nprof;
-	*pprofnvertices=profnvertices;
-	*ppprofx=pprofx;
-	*ppprofy=pprofy;
-	if(pclosed)
-	 *pclosed=closed;
-	else
-	 xDelete<bool>(closed);
-}
-
-DataSet* DomainOutlineRead(char* domainname){
-
-	/*intermediary: */
-	int       nprof;
-	int      *profnvertices = NULL;
-	double  **pprofx        = NULL;
-	double  **pprofy        = NULL;
-	Contour  *contour       = NULL;
-
-	/*output: */
-	DataSet* domain=NULL;
-
-	/*If domainname is an empty string, return empty dataset*/
-	if (strcmp(domainname,"")==0){
-		nprof=0;
-	}
-	else{
-		DomainOutlineRead(&nprof,&profnvertices,&pprofx, &pprofy, NULL,domainname);
-	}
-
-	/*now create dataset of contours: */
-	domain=new DataSet(0);
-
-	for(int i=0;i<nprof;i++){
-		domain->AddObject(new Contour(i,profnvertices[i],pprofx[i],pprofy[i],1));
-	}
-	return domain;
-}
Index: /issm/trunk/src/c/shared/Exp/DomainOutlineWrite.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exp/DomainOutlineWrite.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Exp/DomainOutlineWrite.cpp	(revision 13395)
@@ -12,5 +12,4 @@
 
 int DomainOutlineWrite(int nprof,int* profnvertices,double** pprofx,double** pprofy,bool* closed,char* domainname){
-
 	
 	/*Error management: */
@@ -23,5 +22,5 @@
 	/*open domain outline file for writing: */
 	if ((fid=fopen(domainname,"w"))==NULL){
-		_error2_("could not open domain file " << domainname); 
+		_error_("could not open domain file " << domainname); 
 		noerr=0; goto cleanupandreturn;
 	}
@@ -56,3 +55,2 @@
 	return noerr;
 }
-
Index: /issm/trunk/src/c/shared/Exp/IsInPoly.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exp/IsInPoly.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Exp/IsInPoly.cpp	(revision 13395)
@@ -14,86 +14,4 @@
 #endif
 
-/*IsInPoly {{{*/
-int IsInPoly(Vector* in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue){
-
-	int i;
-	double x0,y0;
-	double value;
-	double xmin=xc[0];
-	double xmax=xc[0];
-	double ymin=yc[0];
-	double ymax=yc[0];
-
-	/*Get extrema*/
-	for (i=1;i<numvertices;i++){
-		if(xc[i]<xmin) xmin=xc[i];
-		if(xc[i]>xmax) xmax=xc[i];
-		if(yc[i]<ymin) ymin=yc[i];
-		if(yc[i]>ymax) ymax=yc[i];
-	}
-
-	/*Go through all vertices of the mesh:*/
-	for (i=i0;i<i1;i++){
-
-		//Get current value of value[i] -> do not change it if != 0
-		in->GetValue(&value,i);
-		if (value){
-			/*this vertex already is inside one of the contours, continue*/
-			continue;
-		}
-
-		/*pick up vertex (x[i],y[i]) and figure out if located inside contour (xc,yc)*/
-		x0=x[i]; y0=y[i];
-		if(x0<xmin || x0>xmax || y0<ymin || y0>ymax){
-			value=0;
-		}
-		else{
-			value=pnpoly(numvertices,xc,yc,x0,y0,edgevalue);
-		}
-		in->SetValue(i,value,INS_VAL);
-	}
-	 return 1;
-}/*}}}*/
-/*IsOutsidePoly {{{*/
-int IsOutsidePoly(Vector* in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue){
-
-	int i,j;
-	double x0,y0;
-	double value;
-	double xmin=xc[0];
-	double xmax=xc[0];
-	double ymin=yc[0];
-	double ymax=yc[0];
-
-	/*Get extrema*/
-	for (i=1;i<numvertices;i++){
-		if(xc[i]<xmin) xmin=xc[i];
-		if(xc[i]>xmax) xmax=xc[i];
-		if(yc[i]<ymin) ymin=yc[i];
-		if(yc[i]>ymax) ymax=yc[i];
-	}
-
-	/*Go through all vertices of the mesh:*/
-	for (i=i0;i<i1;i++){
-
-		//Get current value of value[i] -> do not change it if != 0
-		in->GetValue(&value,i);
-		if (value){
-			/*this vertex already is inside one of the contours, continue*/
-			continue;
-		}
-
-		/*pick up vertex (x[i],y[i]) and figure out if located inside contour (xc,yc)*/
-		x0=x[i]; y0=y[i];
-		if(x0<xmin || x0>xmax || y0<ymin || y0>ymax){
-			value=1;
-		}
-		else{
-			value=1-pnpoly(numvertices,xc,yc,x0,y0,edgevalue);
-		}
-		in->SetValue(i,value,INS_VAL);
-	}
-	return 1;
-}/*}}}*/
 /*pnpoly{{{*/
 int pnpoly(int npol, double *xp, double *yp, double x, double y, int edgevalue) {
Index: /issm/trunk/src/c/shared/Exp/IsInPolySerial.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exp/IsInPolySerial.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Exp/IsInPolySerial.cpp	(revision 13395)
@@ -24,8 +24,8 @@
 		y0=y[i];
 		if (pnpoly(numvertices,xc,yc,x0,y0,edgevalue)){
-			in[i]=1;
+			in[i]=1.;
 		}
 		else{
-			in[i]=0;
+			in[i]=0.;
 		}
 	}
Index: /issm/trunk/src/c/shared/Exp/exp.h
===================================================================
--- /issm/trunk/src/c/shared/Exp/exp.h	(revision 13394)
+++ /issm/trunk/src/c/shared/Exp/exp.h	(revision 13395)
@@ -3,20 +3,192 @@
  */
 
-
 #ifndef _EXP_H_
 #define _EXP_H_
 
-#include "../../objects/objects.h"
-#include "../../toolkits/toolkits.h"
+#include <cstring>
+#include "../../classes/objects/Contour.h"
+#include "../../shared/Numerics/recast.h"
+#include "../../Container/Container.h"
 
-int IsInPoly(Vector* in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue);
-int IsOutsidePoly(Vector* in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue);
 int IsInPolySerial(double* in,double* xc,double* yc,int numvertices,double* x,double* y,int nods, int edgevalue);
 int DomainOutlineWrite(int nprof,int* profnvertices,double** pprofx,double** pprofy,bool* closed,char* domainname);
 int pnpoly(int npol, double *xp, double *yp, double x, double y, int edgevalue);
 
-int      DomainOutlineRead(int* pnprof,int** pprofnvertices,double*** ppprofx,double*** ppprofy,bool** pclosed,char* domainname);
-DataSet* DomainOutlineRead(char* domainname);
+/*IsInPoly {{{*/
+template <class doubletype>
+int IsInPoly(SeqVec<doubletype>* in,double* xc,double* yc,int numvertices,double* x,double* y,int i0,int i1, int edgevalue){
 
+	int i;
+	double x0,y0;
+	doubletype value;
+	double xmin=xc[0];
+	double xmax=xc[0];
+	double ymin=yc[0];
+	double ymax=yc[0];
+
+	/*Get extrema*/
+	for (i=1;i<numvertices;i++){
+		if(xc[i]<xmin) xmin=xc[i];
+		if(xc[i]>xmax) xmax=xc[i];
+		if(yc[i]<ymin) ymin=yc[i];
+		if(yc[i]>ymax) ymax=yc[i];
+	}
+
+	/*Go through all vertices of the mesh:*/
+	for (i=i0;i<i1;i++){
+
+		//Get current value of value[i] -> do not change it if != 0
+		in->GetValue(&value,i);
+		if (reCast<bool,doubletype>(value)){
+			/*this vertex already is inside one of the contours, continue*/
+			continue;
+		}
+
+		/*pick up vertex (x[i],y[i]) and figure out if located inside contour (xc,yc)*/
+		x0=x[i]; y0=y[i];
+		if(x0<xmin || x0>xmax || y0<ymin || y0>ymax){
+			value=0;
+		}
+		else{
+			value=pnpoly(numvertices,xc,yc,x0,y0,edgevalue);
+		}
+		in->SetValue(i,value,INS_VAL);
+	}
+	 return 1;
+}/*}}}*/
+/*DomainOutlineRead{{{*/
+template <class doubletype>
+int DomainOutlineRead(int* pnprof,int** pprofnvertices,doubletype*** ppprofx,doubletype*** ppprofy,bool** pclosed,char* domainname){
+	
+	/*indexing: */
+	int i,counter;
+
+	/*I/O: */
+	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
+	doubletype **pprofx        = NULL; //array of profiles x coordinates
+	doubletype **pprofy        = NULL; //array of profiles y coordinates
+	bool        *closed        = NULL; //array holding closed flags for the nprof profiles
+
+	/*For each profile: */
+	int         n;
+	doubletype *x  = NULL;
+	doubletype *y  = NULL;
+	bool        cl;
+
+	/*open domain outline file for reading: */
+	if ((fid=fopen(domainname,"r"))==NULL){
+		_error_("could not find domain file " << domainname); 
+	}
+
+	/*Do a first pass through the domainname file, to figure out how many profiles we need to read: */
+	nprof=1;
+	for(;;){
+		fscanf(fid,"%256s %256s\n",chardummy,chardummy);
+		fscanf(fid,"%256s %256s\n",chardummy,chardummy);
+		fscanf(fid,"%256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy);
+		fscanf(fid,"%20u %256s\n",&n,chardummy);
+		fscanf(fid,"%256s %256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
+		for (i=0;i<n;i++) fscanf(fid,"%20lf %20lf\n",&ddummy,&ddummy);
+		/*check whether we are at the end of the file, otherwise, keep reading next profile:*/
+		if (feof(fid)) break;
+		nprof++;
+	}
+	
+	/*Allocate and initialize all the profiles: */
+	profnvertices = xNew<int>(nprof);
+	pprofx        = xNew<doubletype*>(nprof);
+	pprofy        = xNew<doubletype*>(nprof);
+	for (i=0;i<nprof;i++){
+		pprofx[i] = NULL;
+		pprofy[i] = NULL;
+	}
+	closed=xNew<bool>(nprof);
+
+	/*Reaset file pointer to beginning of file: */
+	fseek(fid,0,SEEK_SET);
+
+	/*Start reading profiles: */
+	for(counter=0;counter<nprof;counter++){
+
+		/*Skip header: */
+		fscanf(fid,"%256s %256s\n",chardummy,chardummy);
+		fscanf(fid,"%256s %256s\n",chardummy,chardummy);
+		fscanf(fid,"%256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy);
+		
+		/*Get number of profile vertices: */
+		fscanf(fid,"%20u %256s\n",&n,chardummy);
+	
+		/*Skip next line: */
+		fscanf(fid,"%256s %256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
+
+		/*Allocate vertices: */
+		x=xNew<doubletype>(n);
+		y=xNew<doubletype>(n);
+		
+		/*Read vertices: */
+		for (i=0;i<n;i++){
+			fscanf(fid,"%20lf %20lf\n",&x[i],&y[i]);
+		}
+
+		/*Now check that we are dealing with open contours: */
+		cl=false;
+		if((x[0]==x[n-1]) && (y[0]==y[n-1])){
+			cl=true;
+		}
+
+		/*Assign pointers: */
+		profnvertices[counter]=n;
+		pprofx[counter]=x;
+		pprofy[counter]=y;
+		closed[counter]=cl;
+	}
+
+	/*close domain outline file: */
+	fclose(fid);
+
+	/*Assign output pointers: */
+	*pnprof=nprof;
+	*pprofnvertices=profnvertices;
+	*ppprofx=pprofx;
+	*ppprofy=pprofy;
+	if(pclosed) *pclosed=closed;
+	else         xDelete<bool>(closed);
+} /*}}}*/
+/*DataSet* DomainOutlineRead(char* domainname){{{*/
+template <class doubletype>
+DataSet* DomainOutlineRead(char* domainname){
+
+	/*intermediary: */
+	int                  nprof;
+	int                 *profnvertices = NULL;
+	doubletype         **pprofx        = NULL;
+	doubletype         **pprofy        = NULL;
+	Contour<doubletype> *contour       = NULL;
+
+	/*output: */
+	DataSet *domain = NULL;
+
+	/*If domainname is an empty string, return empty dataset*/
+	if (strcmp(domainname,"")==0){
+		nprof=0;
+	}
+	else{
+		DomainOutlineRead(&nprof,&profnvertices,&pprofx, &pprofy, NULL,domainname);
+	}
+
+	/*now create dataset of contours: */
+	domain=new DataSet(0);
+
+	for(int i=0;i<nprof;i++){
+		domain->AddObject(new Contour<doubletype>(i,profnvertices[i],pprofx[i],pprofy[i],1));
+	}
+	return domain;
+} /*}}}*/
 
 #endif
Index: /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp
===================================================================
--- /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp	(revision 13395)
@@ -17,55 +17,46 @@
 
 /*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){
+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;
-	IssmDouble* dtemp;
-
-/*  set up dimensions for triple product  */
-
-	if (!itrna) {
+
+	int         idima,idimb,idimc,idimd;
+	IssmDouble *dtemp;
+
+	/*  set up dimensions for triple product  */
+
+	if (!itrna){
 		idima=nrowa;
 		idimb=ncola;
 	}
-	else {
+	else{
 		idima=ncola;
 		idimb=nrowa;
 	}
 
-	if (!itrnb) {
-		if (nrowb != idimb) {
-			_error2_("Matrix A and B inner vectors not equal size.");
-		}
+	if (!itrnb){
+		if (nrowb != idimb) _error_("Matrix A and B inner vectors not equal size.");
 		idimc=ncolb;
 	}
-	else {
-		if (ncolb != idimb) {
-			_error2_("Matrix A and B inner vectors not equal size.");
-		}
+	else{
+		if (ncolb != idimb) _error_("Matrix A and B inner vectors not equal size.");
 		idimc=nrowb;
 	}
 
 	if (!itrnc) {
-		if (nrowc != idimc) {
-			_error2_("Matrix B and C inner vectors not equal size.");
-		}
+		if (nrowc != idimc) _error_("Matrix B and C inner vectors not equal size.");
 		idimd=ncolc;
 	}
-	else {
-		if (ncolc != idimc) {
-			_error2_("Matrix B and C inner vectors not equal size.");
-		}
+	else{
+		if (ncolc != idimc) _error_("Matrix B and C inner vectors not equal size.");
 		idimd=nrowc;
 	}
 
-/*  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 IssmDoubles, and a*(b*c)
-	requires bd(a+c) multiplies and bd IssmDoubles (both are the same for
-	a symmetric triple product)  */
-
-/*  multiply (a*b)*c+d  */
-
+	/*  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 IssmDoubles, and a*(b*c)
+		 requires bd(a+c) multiplies and bd IssmDoubles (both are the same for
+		 a symmetric triple product)  */
+
+	/*  multiply (a*b)*c+d  */
 	if (idima*idimc*(idimb+idimd) <= idimb*idimd*(idima+idimc)) {
 		dtemp=xNew<IssmDouble>(idima*idimc);
@@ -76,7 +67,6 @@
 	}
 
-/*  multiply a*(b*c)+d  */
-
-	else {
+	/*  multiply a*(b*c)+d  */
+	else{
 		dtemp=xNew<IssmDouble>(idimb*idimd);
 
@@ -89,5 +79,5 @@
 }/*}}}*/
 /*FUNCTION MatrixMuliply {{{*/
-int MatrixMultiply( IssmDouble* a, int nrowa, int ncola, int itrna, IssmDouble* b, int nrowb, int ncolb, int itrnb, IssmDouble* c, int iaddc ){
+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;
@@ -95,5 +85,5 @@
 	int nrowc,ncolc,iinca,jinca,iincb,jincb,ntrma,ntrmb,nterm;
 
-/*  set up dimensions and increments for matrix a  */
+	/*  set up dimensions and increments for matrix a  */
 	if (!itrna) {
 		nrowc=nrowa;
@@ -109,5 +99,5 @@
 	}
 
-/*  set up dimensions and increments for matrix b  */
+	/*  set up dimensions and increments for matrix b  */
 	if (!itrnb) {
 		ncolc=ncolb;
@@ -123,32 +113,23 @@
 	}
 
-	if (ntrma != ntrmb) {
-		_error2_("Matrix A and B inner vectors not equal size");
-	    noerr=0;	
-		return noerr;
-	}
-	else
-		nterm=ntrma;
-
-/*  zero matrix c, if not being added to product  */
-
-	if (!iaddc)
-		for (i=0; i<nrowc*ncolc; i++)
-			*(c+i)=0.;
-
-/*  perform the matrix multiplication  */
-
+	if (ntrma != ntrmb) _error_("Matrix A and B inner vectors not equal size");
+
+	nterm=ntrma;
+
+	/*  zero matrix c, if not being added to product  */
+	if (!iaddc) for (i=0;i<nrowc*ncolc;i++) c[i]=0.;
+
+	/*  perform the matrix multiplication  */
 	iptc=0;
-	for (i=0; i<nrowc; i++) {
-		for (j=0; j<ncolc; j++) {
+	for (i=0; i<nrowc; i++){
+		for (j=0; j<ncolc; j++){
 			ipta=i*iinca;
 			iptb=j*jincb;
 
-			for (k=0; k<nterm; k++) {
-				*(c+iptc)+=*(a+ipta)**(b+iptb);
+			for (k=0; k<nterm; k++){
+				c[iptc]+=a[ipta]*b[iptb];
 				ipta+=jinca;
 				iptb+=iincb;
 			}
-
 			iptc++;
 		}
@@ -159,14 +140,14 @@
 /*FUNCTION MatrixInverse {{{*/
 int MatrixInverse( IssmDouble* a, int ndim, int nrow, IssmDouble* b, int nvec, IssmDouble* pdet ){
-/* MatrixInverse    Perform matrix inversion and linear equation solution.
-
-	This function uses Gaussian elimination on the original matrix
-	augmented by an identity matrix of the same size to calculate
-	the inverse (see for example, "Modern Methods of Engineering
-	Computation", Sec. 6.4).  By noting how the matrices are
-	unpopulated and repopulated, the calculation may be done in place.
-
-	Gaussian elimination is inherently inefficient, and so this is
-	intended for small matrices.  */
+	/* MatrixInverse    Perform matrix inversion and linear equation solution.
+
+		This function uses Gaussian elimination on the original matrix
+		augmented by an identity matrix of the same size to calculate
+		the inverse (see for example, "Modern Methods of Engineering
+		Computation", Sec. 6.4).  By noting how the matrices are
+		unpopulated and repopulated, the calculation may be done in place.
+
+		Gaussian elimination is inherently inefficient, and so this is
+		intended for small matrices.  */
 	int noerr=1;
 	int i,j,k,ipt,jpt,irow,icol,ipiv,ncol;
@@ -175,5 +156,5 @@
 
 	if (!b && nvec) {
-		_error2_("No right-hand side for nvec=" << nvec << ".");
+		_error_("No right-hand side for nvec=" << nvec << ".");
 		noerr=0;
 		return noerr;
@@ -184,5 +165,5 @@
 	_assert_(!(ndim==3 && nrow==3));
 
-/*  initialize local variables and arrays  */
+	/*  initialize local variables and arrays  */
 
 	ncol=nrow;
@@ -192,21 +173,21 @@
 	pindx =xNew<int>(nrow);
 
-/*  loop over the rows/columns of the matrix  */
+	/*  loop over the rows/columns of the matrix  */
 
 	for (i=0; i<nrow; i++) {
 
-/*  search for pivot, finding the term with the greatest magnitude
-	in the rows/columns not yet used  */
+		/*  search for pivot, finding the term with the greatest magnitude
+			 in the rows/columns not yet used  */
 
 		pivot=0.;
 		for (j=0; j<nrow; j++)
-			if (!pindx[j])
-				for (k=0; k<ncol; k++)
-					if (!pindx[k])
-						if (fabs(a[j*ndim+k]) > fabs(pivot)) {
-							irow=j;
-							icol=k;
-							pivot=a[j*ndim+k];
-						}
+		 if (!pindx[j])
+		  for (k=0; k<ncol; k++)
+			if (!pindx[k])
+			 if (fabs(a[j*ndim+k]) > fabs(pivot)) {
+				 irow=j;
+				 icol=k;
+				 pivot=a[j*ndim+k];
+			 }
 
 		if (fabs(pivot) < DBL_EPSILON) {
@@ -214,5 +195,5 @@
 			xDelete<int>(pivrc2);
 			xDelete<int>(pindx);
-			_error2_("Pivot " << pivot << " less than machine epsilon");
+			_error_("Pivot " << pivot << " less than machine epsilon");
 			noerr=0;
 			return noerr;
@@ -225,13 +206,13 @@
 		pindx[ipiv]++;
 
-//		_printf_(true,"pivot for i=%d: irow=%d, icol=%d, pindx[%d]=%d\n",
-//				 i,irow,icol,ipiv,pindx[ipiv]);
-
-/*  switch rows to put pivot element on diagonal, noting that the
-	column stays the same and the determinant changes sign  */
+		//		_printf_(true,"pivot for i=%d: irow=%d, icol=%d, pindx[%d]=%d\n",
+		//				 i,irow,icol,ipiv,pindx[ipiv]);
+
+		/*  switch rows to put pivot element on diagonal, noting that the
+			 column stays the same and the determinant changes sign  */
 
 		if (irow != icol) {
-//			_printf_(true,"row switch for i=%d: irow=%d, icol=%d\n",
-//					 i,irow,icol);
+			//			_printf_(true,"row switch for i=%d: irow=%d, icol=%d\n",
+			//					 i,irow,icol);
 
 			ipt=irow*ndim;
@@ -254,8 +235,8 @@
 		}
 
-/*  divide pivot row by pivot element, noting that the original
-	matrix will have 1 on the diagonal, which will be discarded,
-	and the augmented matrix will start with 1 from the identity
-	matrix and then have 1/pivot, which is part of the inverse.  */
+		/*  divide pivot row by pivot element, noting that the original
+			 matrix will have 1 on the diagonal, which will be discarded,
+			 and the augmented matrix will start with 1 from the identity
+			 matrix and then have 1/pivot, which is part of the inverse.  */
 
 		a[ipiv*ndim+ipiv]=1.;
@@ -263,17 +244,17 @@
 		ipt=ipiv*ndim;
 		for (k=0; k<ncol; k++)
-			a[ipt+k]/=pivot;
+		 a[ipt+k]/=pivot;
 
 		ipt=ipiv*nvec;
 		for (k=0; k<nvec; k++)
-			b[ipt+k]/=pivot;
-
-/*  reduce non-pivot rows such that they will have 0 in the pivot
-	column, which will be discarded, and the augmented matrix will
-	start with 0 from the identity matrix and then have non-zero
-	in the corresponding column, which is part of the inverse.
-	only one column of the augmented matrix is populated at a time,
-	which corresponds to the only column of the original matrix
-	being zeroed, so that the inverse may be done in place.  */
+		 b[ipt+k]/=pivot;
+
+		/*  reduce non-pivot rows such that they will have 0 in the pivot
+			 column, which will be discarded, and the augmented matrix will
+			 start with 0 from the identity matrix and then have non-zero
+			 in the corresponding column, which is part of the inverse.
+			 only one column of the augmented matrix is populated at a time,
+			 which corresponds to the only column of the original matrix
+			 being zeroed, so that the inverse may be done in place.  */
 
 		for (j=0; j<nrow; j++) {
@@ -287,23 +268,23 @@
 				jpt=ipiv*ndim;
 				for (k=0; k<ncol; k++)
-					a[ipt+k]-=dtemp*a[jpt+k];
+				 a[ipt+k]-=dtemp*a[jpt+k];
 
 				ipt=j   *nvec;
 				jpt=ipiv*nvec;
 				for (k=0; k<nvec; k++)
-					b[ipt+k]-=dtemp*b[jpt+k];
-			}
-		}
-
-/*  for a diagonal matrix, the determinant is the product of the
-	diagonal terms, and so it may be accumulated from the pivots,
-	noting that switching rows changes the sign as above  */
+				 b[ipt+k]-=dtemp*b[jpt+k];
+			}
+		}
+
+		/*  for a diagonal matrix, the determinant is the product of the
+			 diagonal terms, and so it may be accumulated from the pivots,
+			 noting that switching rows changes the sign as above  */
 
 		det*=pivot;
 	}
 
-/*  switch columns back in reverse order, noting that a row switch
-	in the original matrix corresponds to a column switch in the
-	inverse matrix  */
+	/*  switch columns back in reverse order, noting that a row switch
+		 in the original matrix corresponds to a column switch in the
+		 inverse matrix  */
 
 	for (i=0; i<nrow; i++) {
@@ -314,6 +295,6 @@
 			icol=pivrc2[j];
 
-//			_printf_(true,"column switch back for j=%d: irow=%d, icol=%d\n",
-//					 j,irow,icol);
+			//			_printf_(true,"column switch back for j=%d: irow=%d, icol=%d\n",
+			//					 j,irow,icol);
 
 			ipt=0;
@@ -349,5 +330,5 @@
 	/*Compute determinant*/
 	Matrix2x2Determinant(&det,A);
-	if (fabs(det) < DBL_EPSILON) _error2_("Determinant smaller that machine epsilon");
+	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller that machine epsilon");
 
 	/*Compute invert*/
@@ -363,5 +344,5 @@
 
 	/*det = a*(e*i-f*h)-b*(d*i-f*g)+c*(d*h-e*g)*/
-   *Adet= A[0]*A[4]*A[8]-A[0]*A[5]*A[7]-A[3]*A[1]*A[8]+A[3]*A[2]*A[7]+A[6]*A[1]*A[5]-A[6]*A[2]*A[4];
+	*Adet= A[0]*A[4]*A[8]-A[0]*A[5]*A[7]-A[3]*A[1]*A[8]+A[3]*A[2]*A[7]+A[6]*A[1]*A[5]-A[6]*A[2]*A[4];
 }
 /*}}}*/
@@ -374,5 +355,5 @@
 	/*Compute determinant*/
 	Matrix3x3Determinant(&det,A);
-	if (fabs(det) < DBL_EPSILON) _error2_("Determinant smaller that machine epsilon");
+	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller that machine epsilon");
 
 	/*Compute invert*/
Index: /issm/trunk/src/c/shared/Numerics/BrentSearch.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/BrentSearch.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Numerics/BrentSearch.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 
 #include "./numerics.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../include/include.h"
 #include "../../io/io.h"
@@ -44,5 +44,5 @@
 	iter=0;
 	fxmin = (*f)(xmin,optargs);
-	if (xIsNan<IssmDouble>(fxmin)) _error2_("Function evaluation returned NaN");
+	if (xIsNan<IssmDouble>(fxmin)) _error_("Function evaluation returned NaN");
 	cout<<setprecision(5);
 	if(VerboseControl()) _pprintLine_("");
@@ -51,5 +51,5 @@
 	if(VerboseControl()) _pprintLine_("           N/A    "<<setw(12)<<xmin<<"  "<<setw(12)<<fxmin<<"           N/A         boundary");
 	fxmax = (*f)(xmax,optargs);
-	if (xIsNan<IssmDouble>(fxmax)) _error2_("Function evaluation returned NaN");
+	if (xIsNan<IssmDouble>(fxmax)) _error_("Function evaluation returned NaN");
 	if(VerboseControl()) _pprintLine_("           N/A    "<<setw(12)<<xmax<<"  "<<setw(12)<<fxmax<<"           N/A         boundary");
 
@@ -75,5 +75,5 @@
 	/*2: call the function to be evaluated*/
 	fxbest = (*f)(x,optargs);
-	if(xIsNan<IssmDouble>(fxbest)) _error2_("Function evaluation returned NaN");
+	if(xIsNan<IssmDouble>(fxbest)) _error_("Function evaluation returned NaN");
 	iter=iter+1;
 
@@ -159,5 +159,5 @@
 		//evaluate function on x
 		fx = (*f)(x,optargs);
-		if(xIsNan<IssmDouble>(fx)) _error2_("Function evaluation returned NaN");
+		if(xIsNan<IssmDouble>(fx)) _error_("Function evaluation returned NaN");
 		iter=iter+1;
 
Index: /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp	(revision 13395)
@@ -4,5 +4,4 @@
 #include "./GaussPoints.h"
 #include "../Alloc/alloc.h"
-#include "../../io/io.h"
 #include "../Exceptions/exceptions.h"
 #include <math.h>
@@ -1670,5 +1669,5 @@
 		if (iter >= MAX_GAUS_ITER) {
 			xDelete<IssmPDouble>(work);
-			_error2_("Max iterations exceeded for l=" << MAX_GAUS_ITER);
+			_error_("Max iterations exceeded for l=" << MAX_GAUS_ITER);
 		}
 	}
Index: /issm/trunk/src/c/shared/Numerics/IsInputConverged.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/IsInputConverged.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Numerics/IsInputConverged.cpp	(revision 13395)
@@ -12,5 +12,5 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 void IsInputConverged(IssmDouble* peps, Input** new_inputs,Input** old_inputs,int num_inputs,int criterion_enum){
@@ -53,5 +53,5 @@
 		else eps=0;
 	}
-	else _error2_("convergence criterion " << EnumToStringx(criterion_enum) << " not supported yet!");
+	else _error_("convergence criterion " << EnumToStringx(criterion_enum) << " not supported yet!");
 
 	/*Assign output pointers:*/
Index: /issm/trunk/src/c/shared/Numerics/OptimalSearch.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/OptimalSearch.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Numerics/OptimalSearch.cpp	(revision 13395)
@@ -10,5 +10,5 @@
 
 #include "./numerics.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../io/io.h"
 #include "../../include/include.h"
@@ -41,5 +41,5 @@
 	//get the value of the function at the first boundary
 	fx1= (*f)(x1,optargs);
-	if (xIsNan<IssmDouble>(fx1)) _error2_("Function evaluation returned NaN");
+	if (xIsNan<IssmDouble>(fx1)) _error_("Function evaluation returned NaN");
 	cout<<setprecision(5);
 	if(VerboseControl()) _pprintLine_("");
@@ -57,5 +57,5 @@
 		iter++;
 		fx2 = (*f)(x2,optargs);
-		if (xIsNan<IssmDouble>(fx2)) _error2_("Function evaluation returned NaN");
+		if (xIsNan<IssmDouble>(fx2)) _error_("Function evaluation returned NaN");
 		if(VerboseControl())
 		 _pprintLine_("         "<<setw(5)<<iter<<"    "<<setw(12)<<x2<<"  "<<setw(12)<<fx2<<"  "<<(fabs(x2-x1)>fabs(fx2-fx1)?fabs(fx2-fx1):fabs(x2-x1)));
Index: /issm/trunk/src/c/shared/Numerics/OptionsFromAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/OptionsFromAnalysis.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Numerics/OptionsFromAnalysis.cpp	(revision 13395)
@@ -11,5 +11,5 @@
 #include <cstring>
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Parameters.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
@@ -57,5 +57,5 @@
 	if (found==-1){
 		/*ok, we did not find anything, this is not good! error out: */
-		_error2_("could find neither a default analysis  nor analysis " << EnumToStringx(analysis_type));
+		_error_("could find neither a default analysis  nor analysis " << EnumToStringx(analysis_type));
 	}
 
Index: /issm/trunk/src/c/shared/Numerics/PetscOptionsFromAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/PetscOptionsFromAnalysis.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Numerics/PetscOptionsFromAnalysis.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../Container/Parameters.h"
 #include "../../toolkits/toolkits.h"
Index: /issm/trunk/src/c/shared/Numerics/UnitConversion.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/UnitConversion.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Numerics/UnitConversion.cpp	(revision 13395)
@@ -11,5 +11,5 @@
 
 #include "../../Container/Container.h"
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
 #include "../../shared/shared.h"
@@ -29,5 +29,5 @@
 	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 _error2_("wrong direction for unit conversion, either IuToExtEnum or ExtToIuEnum. ");
+	else _error_("wrong direction for unit conversion, either IuToExtEnum or ExtToIuEnum. ");
 
 }
@@ -51,27 +51,28 @@
 		case TimesteppingTimeStepEnum:               scale=1.0/yts;break; //yr
 		case TimeEnum:                               scale=1.0/yts;break; //yr
-		case HydrologyWaterVxEnum:                   scale=yts;break; //m/yr
-		case HydrologyWaterVyEnum:                   scale=yts;break; //m/yr
-		case VxEnum:                                 scale=yts;break; //m/yr
-		case InversionVxObsEnum:                     scale=yts;break; //m/yr
-		case VyEnum:                                 scale=yts;break; //m/yr
-		case InversionVyObsEnum:                     scale=yts;break; //m/yr
-		case VzEnum:                                 scale=yts;break; //m/yr
-		case InversionVzObsEnum:                     scale=yts;break; //m/yr
-		case VelEnum:                                scale=yts;break; //m/yr
-		case InversionVelObsEnum:                    scale=yts;break; //m/yr
-		case BalancethicknessThickeningRateEnum:     scale=yts;break; //m/yr
-		case BasalforcingsMeltingRateEnum:           scale=yts;break; //m/yr
-		case BasalforcingsMeltingRateCorrectionEnum: scale=yts;break; //m/yr
-		case SurfaceforcingsPrecipitationEnum:       scale=yts;break; //m/yr
-		case SurfaceforcingsMassBalanceEnum:         scale=yts;break; //m/yr
-		case 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 HydrologyWaterVxEnum:                   scale=yts;break;     //m/yr
+		case HydrologyWaterVyEnum:                   scale=yts;break;     //m/yr
+		case VxEnum:                                 scale=yts;break;     //m/yr
+		case InversionVxObsEnum:                     scale=yts;break;     //m/yr
+		case VyEnum:                                 scale=yts;break;     //m/yr
+		case InversionVyObsEnum:                     scale=yts;break;     //m/yr
+		case VzEnum:                                 scale=yts;break;     //m/yr
+		case InversionVzObsEnum:                     scale=yts;break;     //m/yr
+		case VelEnum:                                scale=yts;break;     //m/yr
+		case InversionVelObsEnum:                    scale=yts;break;     //m/yr
+		case BalancethicknessThickeningRateEnum:     scale=yts;break;     //m/yr
+		case BasalforcingsMeltingRateEnum:           scale=yts;break;     //m/yr
+		case BasalforcingsMeltingRateCorrectionEnum: scale=yts;break;     //m/yr
+		case SurfaceforcingsPrecipitationEnum:       scale=yts;break;     //m/yr
+		case SurfaceforcingsMassBalanceEnum:         scale=yts;break;     //m/yr
+		case 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((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/trunk/src/c/shared/Numerics/Verbosity.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/Verbosity.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Numerics/Verbosity.cpp	(revision 13395)
@@ -34,5 +34,5 @@
 void SetVerbosityLevel(int level){
 
-	if(level<0) _error2_("vebosity level should be a positive integer (user provided " << level << ")");
+	if(level<0) _error_("vebosity level should be a positive integer (user provided " << level << ")");
 
 	verbositylevel = level;
Index: /issm/trunk/src/c/shared/Numerics/adolc_edf.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/adolc_edf.h	(revision 13395)
+++ /issm/trunk/src/c/shared/Numerics/adolc_edf.h	(revision 13395)
@@ -0,0 +1,28 @@
+/*
+ * adolc_edf.h
+ *
+ *  Created on: Jun 26, 2012
+ *      Author: utke
+ */
+
+#ifndef _ADOLC_EDF_H_
+#define _ADOLC_EDF_H_
+
+#include "../../include/include.h"
+
+#ifdef _HAVE_ADOLC_
+
+struct Adolc_edf {
+    ext_diff_fct *myEDF_for_solverx_p;
+    Adolc_edf() : myEDF_for_solverx_p(0) {}
+    inline friend std::ostream& operator << ( ostream&, const Adolc_edf& );
+};
+
+std::ostream& operator << ( std::ostream& out, const Adolc_edf& a) {
+    out << a.myEDF_for_solverx_p;
+    return out;
+}
+
+#endif
+
+#endif
Index: /issm/trunk/src/c/shared/Numerics/cubic.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/cubic.cpp	(revision 13395)
+++ /issm/trunk/src/c/shared/Numerics/cubic.cpp	(revision 13395)
@@ -0,0 +1,91 @@
+#include <math.h>
+#include "./numerics.h"
+
+IssmDouble CBRT(IssmDouble Z){
+
+	IssmDouble ret;
+
+	if (Z> 0.0){
+		ret = fabs(pow(fabs(Z),1./3.));
+	}
+	else if(Z< 0.0){
+		ret = - fabs(pow(fabs(Z),1./3.));
+	}
+	else{
+		ret = 0.;
+	}
+	return ret;
+}
+
+int cubic(IssmDouble a,IssmDouble b,IssmDouble c,IssmDouble d, IssmDouble x[3], int* num){
+	/* Find the real roots of linear/quadratic and cubic equations:
+	 *
+	 *   a x^3 + bx^2 + cx + d = 0
+	 *
+	 *   returns the roots in x
+	 *   num is the number of roots */
+
+	/*Some useful constants*/
+	const IssmDouble pi    = 3.1415926535897932;
+	const IssmDouble third = 1./3.;
+
+	/*Intermediaries*/
+	IssmDouble U[3],W,P,Q,delta,phi;
+
+	/* determine the degree of the polynomial */
+	if (a != 0.0){
+		//cubic problem
+		W     = b/a *third;
+		P     = pow((c/a *third - pow(W,2)),3);
+		Q     = -.5 *(2.0*pow(W,3)-(c*W-d)/a );
+		delta = pow(Q,2)+P;
+		if ( delta < 0.0 ){
+			//three real solutions!
+			//Confine the argument of coeffCOS to the interval [-1;1]!
+			phi = acos(min(1.0,max(-1.0,Q/sqrt(-P))));
+			P   = 2.0*pow((-P),(5.e-1*third));
+			for(int i=0;i<3;i++)	U[i] = P*cos((phi+2*((IssmDouble)i)*pi)*third)-W;
+			x[0] = min(U[0], min(U[1], U[2]));
+			x[1] = max(min(U[0], U[1]),max( min(U[0], U[2]), min(U[1], U[2])));
+			x[2] = max(U[0], max(U[1], U[2]));
+			*num = 3;
+		}
+		else{
+			// only one real solution!
+			delta = sqrt(delta);
+			x[0] = CBRT(Q+delta)+CBRT(Q-delta)-W;
+			*num=1;
+		}
+	}
+	else if (b != 0.0){
+		// quadratic problem
+		P     = 0.5*c/b;
+		delta = pow(P,2)-d/b;
+		if (delta > 0.0){
+			// 2 real solutions
+			x[0] = -P - sqrt(delta);
+			x[1] = -P + sqrt(delta);
+			*num = 2;
+		}
+		else{
+			// no real solution
+			*num = 0;
+		}
+	}
+	else if (c != 0.0){
+		//linear equation
+		x[0] = d/c;
+		*num = 1;
+	}
+	else{
+		//no equation
+		*num = 0;
+	}
+
+	/* perform one step of a newton iteration in order to minimize round-off errors */
+	for(int i=0;i<*num;i++){
+		x[i] = x[i] - (d+x[i]*(c+x[i]*(b+x[i]*a)))/(c+x[i]*(2.0*b+x[i]*3.0*a));
+	}
+
+	return 0;
+}
Index: /issm/trunk/src/c/shared/Numerics/numerics.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/numerics.h	(revision 13394)
+++ /issm/trunk/src/c/shared/Numerics/numerics.h	(revision 13395)
@@ -17,17 +17,18 @@
 struct OptPars;
 
-IssmDouble min(IssmDouble a,IssmDouble b);
-IssmDouble max(IssmDouble a,IssmDouble b);
-int    min(int a,int b);
-int    max(int a,int b);
-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(IssmDouble* T,IssmDouble* xzvectors);
+IssmDouble  min(IssmDouble a,IssmDouble b);
+IssmDouble  max(IssmDouble a,IssmDouble b);
+int         min(int a,int b);
+int         max(int a,int b);
+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(IssmDouble *T,IssmDouble*xzvectors);
+int         cubic(IssmDouble a, IssmDouble b, IssmDouble c, IssmDouble d, double X[3], int *num);
 #ifdef _HAVE_PETSC_
 void   PetscOptionsFromAnalysis(Parameters* parameters,int analysis_type);
Index: /issm/trunk/src/c/shared/String/DescriptorIndex.cpp
===================================================================
--- /issm/trunk/src/c/shared/String/DescriptorIndex.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/String/DescriptorIndex.cpp	(revision 13395)
@@ -23,10 +23,10 @@
 	/*retrieve first token, separated by underscore: */
 	pch = strtok (descriptor,"_");
-	if(!pch)_error2_("descriptor " << descriptor << " is not correctly formatted!");
+	if(!pch)_error_("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)_error2_("scaled descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("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)_error2_("indexed descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("indexed descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 		/*now recover  the index: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("indexed descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("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)_error2_("nodal descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("nodal descriptor " << descriptor << " is not correctly formatted!");
 		memcpy(root,pch,(strlen(pch)+1)*sizeof(char));
 		/*now recover  the index: */
 		pch = strtok (NULL, "_");
-		if(!pch)_error2_("nodal descriptor " << descriptor << " is not correctly formatted!");
+		if(!pch)_error_("nodal descriptor " << descriptor << " is not correctly formatted!");
 		sscanf(pch,"%i",pindex);
 		return NodalEnum;
Index: /issm/trunk/src/c/shared/Sys/ProfilingStart.cpp
===================================================================
--- /issm/trunk/src/c/shared/Sys/ProfilingStart.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Sys/ProfilingStart.cpp	(revision 13395)
@@ -12,4 +12,5 @@
 #include "../../include/macros.h"
 #include "../shared.h"
+#include "../../io/io.h"
 /*}}}*/
 
Index: /issm/trunk/src/c/shared/Threads/LaunchThread.cpp
===================================================================
--- /issm/trunk/src/c/shared/Threads/LaunchThread.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Threads/LaunchThread.cpp	(revision 13395)
@@ -44,10 +44,10 @@
 
 		if(pthread_create(threads+i,NULL,function,(void*)(handles+i))){
-			_error2_("pthread_create error");
+			_error_("pthread_create error");
 		}
 	}
 	for(i=0;i<num_threads;i++){
 		if(pthread_join(threads[i],(void**)&status)){
-			_error2_("pthread_join error");
+			_error_("pthread_join error");
 		}
 	}
Index: /issm/trunk/src/c/shared/TriMesh/GridInsideHole.cpp
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/GridInsideHole.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/TriMesh/GridInsideHole.cpp	(revision 13395)
@@ -14,5 +14,5 @@
 int GridInsideHole(double* px0,double* py0,int n,double* x,double* y){
 
-	double flag;
+	double flag=0.0;
 	double xA,xB,xC,xD,xE;
 	double yA,yB,yC,yD,yE;
@@ -30,9 +30,6 @@
 	/*D and E are on each side of segment [A B], on the median line between segment [A  B], 
 	 *at an angle of 10 degree (less than the minimum 30 enforced by the quality of the mesh: */
-
-
 	xD=xC+tan(10./180.*M_PI)*(yC-yA);
 	yD=yC+tan(10./180.*M_PI)*(xA-xC);
-
 	xE=xC-tan(10./180.*M_PI)*(yC-yA);
 	yE=yC-tan(10./180.*M_PI)*(xA-xC);
@@ -40,5 +37,6 @@
 	/*Either E or D is inside profile (x,y): */
 	IsInPolySerial(&flag,&xD,&yD,1,x,y,n,2);
-	if (flag){
+	/*FIXME: used to be 'flag' and not '!flag', check*/
+	if(!flag){
 		/*D is inside the poly: */
 		*px0=xD;
Index: /issm/trunk/src/c/shared/TriMesh/SplitMeshForRifts.cpp
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/SplitMeshForRifts.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/TriMesh/SplitMeshForRifts.cpp	(revision 13395)
@@ -76,12 +76,13 @@
 				 instances of node in the triangulation *for those elements, to the
 				 new node.*/
-				
+
+				//create new node
+				x=xReNew<double>(x,nods,nods+1);
+				y=xReNew<double>(y,nods,nods+1);
+				x[nods]=x[node-1]; //matlab indexing
+				y[nods]=y[node-1]; //matlab indexing
+
 				//augment number of nodes 
-				nods=nods+1;
-				//create new node
-				x=(double*)xrealloc(x,nods*sizeof(double));
-				y=(double*)xrealloc(y,nods*sizeof(double));
-				x[nods-1]=x[node-1]; //matlab indexing
-				y[nods-1]=y[node-1]; //matlab indexing
+				nods++;
 
 				//change elements owning this node
Index: /issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 13395)
@@ -255,16 +255,16 @@
 	int el1,el2;
 
-	double* segments=NULL;
-	double*    segmentmarkerlist=NULL;
+	double *segments          = NULL;
+	double *segmentmarkerlist = NULL;
 	int     nsegs;
 
 	/*Recover input: */
-	segments=*psegments;
-	segmentmarkerlist=*psegmentmarkerlist;
-	nsegs=*pnsegs;
+	segments          = *psegments;
+	segmentmarkerlist = *psegmentmarkerlist;
+	nsegs             = *pnsegs;
 
 	/*Reallocate segments: */
-	segments=(double*)xrealloc(segments,(nsegs+nriftsegs)*3*sizeof(double));
-	segmentmarkerlist=(double*)xrealloc(segmentmarkerlist,(nsegs+nriftsegs)*sizeof(double));
+	segments         =xReNew<double>(segments,         nsegs*3,(nsegs+nriftsegs)*3);
+	segmentmarkerlist=xReNew<double>(segmentmarkerlist,nsegs*3,(nsegs+nriftsegs)*3);
 
 	/*First, update the existing segments to the new nodes :*/
@@ -662,6 +662,6 @@
 
 	/*Reallocate x and y: */
-	xreal=(double*)xrealloc(x,newnods*sizeof(double));
-	yreal=(double*)xrealloc(y,newnods*sizeof(double));
+	xreal=xReNew<double>(x,nods,newnods);
+	yreal=xReNew<double>(y,nods,newnods);
 	counter1=0;
 	counter2=0;
@@ -1093,10 +1093,9 @@
 				if(triple==1){
 					/*el is a corner element: we need to split it in 3 triangles: */
-					x=(double*)xrealloc(x,(nods+1)*sizeof(double));
-					y=(double*)xrealloc(y,(nods+1)*sizeof(double));
+					x=xReNew<double>(x,nods,nods+1);
+					y=xReNew<double>(y,nods,nods+1);
 					x[nods]=(x[(int)node1-1]+x[(int)node2-1]+x[(int)node3-1])/3;
 					y[nods]=(y[(int)node1-1]+y[(int)node2-1]+y[(int)node3-1])/3;
-
-					index=(double*)xrealloc(index,(nel+2)*3*sizeof(double));
+					index=xReNew<double>(index,nel*3,(nel+2*3));
 					/*First, reassign element el: */
 					*(index+3*el+0)=node1;
Index: /issm/trunk/src/c/shared/Wrapper/ModuleBoot.cpp
===================================================================
--- /issm/trunk/src/c/shared/Wrapper/ModuleBoot.cpp	(revision 13394)
+++ /issm/trunk/src/c/shared/Wrapper/ModuleBoot.cpp	(revision 13395)
@@ -11,5 +11,4 @@
 #error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif
-
 
 int ModuleBoot(void){
Index: /issm/trunk/src/c/shared/Wrapper/wrappershared.h
===================================================================
--- /issm/trunk/src/c/shared/Wrapper/wrappershared.h	(revision 13394)
+++ /issm/trunk/src/c/shared/Wrapper/wrappershared.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define _WRAPPER_SHARED_H_
 
-#include "../../objects/objects.h"
+#include "../../classes/objects/objects.h"
 
 int ModuleBoot(void);
Index: /issm/trunk/src/c/shared/shared.h
===================================================================
--- /issm/trunk/src/c/shared/shared.h	(revision 13394)
+++ /issm/trunk/src/c/shared/shared.h	(revision 13395)
@@ -7,5 +7,4 @@
 
 #include "Alloc/alloc.h"
-#include "Alloc/alloc_module.h"
 #include "Alloc/xNewDelete.h"
 #include "Bamg/shared.h"
Index: /issm/trunk/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp	(revision 13395)
@@ -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:
-			_error2_("No adjoint has been implemented for solution " << EnumToStringx(solutiontype) << " yet");
+			_error_("No adjoint has been implemented for solution " << EnumToStringx(solutiontype) << " yet");
 			break;
 	}
Index: /issm/trunk/src/c/solutions/AnalysisConfiguration.cpp
===================================================================
--- /issm/trunk/src/c/solutions/AnalysisConfiguration.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/AnalysisConfiguration.cpp	(revision 13395)
@@ -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"
@@ -110,5 +110,5 @@
 		
 		default:
-			_error2_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
+			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
 			break;
 	}
Index: /issm/trunk/src/c/solutions/CorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/solutions/CorePointerFromSolutionEnum.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/CorePointerFromSolutionEnum.cpp	(revision 13395)
@@ -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
-			_error2_("ISSM was not compiled with diagnostic capabilities. Exiting");
+			_error_("ISSM was not compiled with diagnostic capabilities. Exiting");
 			#endif
 			break;
@@ -36,5 +36,5 @@
 			solutioncore=&steadystate_core;
 			#else
-			_error2_("ISSM was not compiled with steady state capabilities. Exiting");
+			_error_("ISSM was not compiled with steady state capabilities. Exiting");
 			#endif
 			break;
@@ -43,5 +43,5 @@
 			solutioncore=&thermal_core;
 			#else
-			_error2_("ISSM was not compiled with thermal capabilities. Exiting");
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
 			#endif
 			break;
@@ -50,5 +50,5 @@
 			solutioncore=&enthalpy_core;
 			#else
-			_error2_("ISSM was not compiled with thermal capabilities. Exiting");
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
 			#endif
 			break;
@@ -57,5 +57,5 @@
 			solutioncore=&balancethickness_core;
 			#else
-			_error2_("ISSM was not compiled with balanced capabilities. Exiting");
+			_error_("ISSM was not compiled with balanced capabilities. Exiting");
 			#endif
 			break;
@@ -64,5 +64,5 @@
 			solutioncore=&hydrology_core;
 			#else
-			_error2_("ISSM was not compiled with hydrology capabilities. Exiting");
+			_error_("ISSM was not compiled with hydrology capabilities. Exiting");
 			#endif
 			break;
@@ -71,5 +71,5 @@
 			solutioncore=&surfaceslope_core;
 			#else
-			_error2_("ISSM was not compiled with slope capabilities. Exiting");
+			_error_("ISSM was not compiled with slope capabilities. Exiting");
 			#endif
 			break;
@@ -78,5 +78,5 @@
 			solutioncore=&bedslope_core;
 			#else
-			_error2_("ISSM was not compiled with slope capabilities. Exiting");
+			_error_("ISSM was not compiled with slope capabilities. Exiting");
 			#endif
 			break;
@@ -85,5 +85,5 @@
 			solutioncore=&transient_core;
 			#else
-			_error2_("ISSM was not compiled with transient capabilities. Exiting");
+			_error_("ISSM was not compiled with transient capabilities. Exiting");
 			#endif
 			break;
@@ -92,9 +92,9 @@
 			solutioncore=&prognostic_core;
 			#else
-			_error2_("ISSM was not compiled with prognostic capabilities. Exiting");
+			_error_("ISSM was not compiled with prognostic capabilities. Exiting");
 			#endif
 			break;
 		default:
-			_error2_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
+			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
 			break;
 	}
Index: /issm/trunk/src/c/solutions/ProcessArguments.cpp
===================================================================
--- /issm/trunk/src/c/solutions/ProcessArguments.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/ProcessArguments.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #include "../include/include.h"
 
-void ProcessArguments(int* solution_type,char** pbinfilename,char** poutbinfilename,char** ppetscfilename,char** plockfilename,int argc,char **argv){
+void ProcessArguments(int* solution_type,char** pbinfilename,char** poutbinfilename,char** ppetscfilename,char** plockfilename,char** prootpath, int argc,char **argv){
 
 	char *modelname      = NULL;
@@ -16,13 +16,33 @@
 	char *petscfilename  = NULL;
 	char *lockfilename   = NULL;
+	char *rootpath       = NULL;
+	char *rootpatharg    = NULL;
 
-	if(argc<2)_error2_("Usage error: no solution requested");
 	*solution_type=StringToEnumx(argv[1]);
-	if(argc<3)_error2_("Usage error: missing model name");
+	if(argc<2)_error_("Usage error: no solution requested");
+	if(argc<3)_error_("Usage error: missing execution directory");
+	if(argc<4)_error_("Usage error: missing model name");
+
+	rootpatharg=argv[2];
+	if(strcmp(strstr(rootpatharg,"/"),"/")!=0){ 
+		rootpath       = xNew<char>(strlen(rootpatharg)+2); sprintf(rootpath,"%s/",rootpatharg);
+	}
+	else{
+		rootpath       = xNew<char>(strlen(rootpatharg)+1); sprintf(rootpath,"%s",rootpatharg);
+	}
+
 	modelname=argv[3];
-	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");
+	if(strstr(modelname,rootpath)==NULL){
+		binfilename    = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s%s",rootpath,modelname,".bin");
+		outbinfilename = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s%s",rootpath,modelname,".outbin");
+		petscfilename  = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".petsc") +1); sprintf(petscfilename, "%s%s%s",rootpath,modelname,".petsc");
+		lockfilename   = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s%s",rootpath,modelname,".lock");
+	}
+	else{
+		binfilename    = xNew<char>(strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s",modelname,".bin");
+		outbinfilename = xNew<char>(strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s",modelname,".outbin");
+		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*/
@@ -31,3 +51,5 @@
 	*ppetscfilename=petscfilename;
 	*plockfilename=lockfilename;
+	*prootpath=rootpath;
+
 }
Index: /issm/trunk/src/c/solutions/ResetBoundaryConditions.cpp
===================================================================
--- /issm/trunk/src/c/solutions/ResetBoundaryConditions.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/ResetBoundaryConditions.cpp	(revision 13395)
@@ -3,5 +3,5 @@
  */ 
 
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../modules/modules.h"
 #include "../io/io.h"
@@ -11,5 +11,5 @@
 	
 	/*variables: */
-	Vector*    yg    = NULL;
+	Vector<IssmDouble>*    yg    = NULL;
 	Nodes *nodes = NULL;
 	int    i;
Index: /issm/trunk/src/c/solutions/WriteLockFile.cpp
===================================================================
--- /issm/trunk/src/c/solutions/WriteLockFile.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/WriteLockFile.cpp	(revision 13395)
@@ -17,8 +17,8 @@
 	if(my_rank==0){
 		fid=fopen(filename,"w");
-		if(fid==NULL) _error2_("error message: could not open lock file " << filename);
+		if(fid==NULL) _error_("error message: could not open lock file " << filename);
 
 		/*Close file: */
-		if(fclose(fid)!=0) _error2_("could not close lock file " << filename);
+		if(fclose(fid)!=0) _error_("could not close lock file " << filename);
 	}
 
Index: /issm/trunk/src/c/solutions/adjointbalancethickness_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/adjointbalancethickness_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/adjointbalancethickness_core.cpp	(revision 13395)
@@ -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"
Index: /issm/trunk/src/c/solutions/adjointdiagnostic_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/adjointdiagnostic_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/adjointdiagnostic_core.cpp	(revision 13395)
@@ -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"
Index: /issm/trunk/src/c/solutions/balancethickness_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/balancethickness_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/balancethickness_core.cpp	(revision 13395)
@@ -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"
Index: /issm/trunk/src/c/solutions/bedslope_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/bedslope_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/bedslope_core.cpp	(revision 13395)
@@ -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"
Index: /issm/trunk/src/c/solutions/control_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/control_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/control_core.cpp	(revision 13395)
@@ -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"
@@ -82,5 +82,5 @@
 		/*Display info*/
 		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];
+		for(i=0;i<num_responses;i++) step_responses[i]=reCast<int,IssmDouble>(responses[n*num_responses+i]);
 		femmodel->parameters->SetParam(step_responses,1,num_responses,StepResponsesEnum);
 		
@@ -99,5 +99,5 @@
 
 		if(VerboseControl()) _pprintLine_("   optimizing along gradient direction");
-		optpars.maxiter=(int)maxiter[n]; optpars.cm_jump=cm_jump[n];
+		optpars.maxiter=reCast<int,IssmDouble>(maxiter[n]); optpars.cm_jump=cm_jump[n];
 		BrentSearch(&search_scalar,J+n,&optpars,&objectivefunction,&optargs);
 
@@ -115,5 +115,13 @@
 	if(!dakota_analysis){ //do not save this if we are running the control core from a qmu run!
 		for(i=0;i<num_controls;i++) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,control_type[i]);
-		femmodel->results->AddObject(new DoubleVecExternalResult(femmodel->results->Size()+1,JEnum,J,nsteps,1,0));
+
+		#ifdef _HAVE_ADOLC_
+		IssmPDouble* J_passive=xNew<IssmPDouble>(nsteps);
+		for(int i=0;i<nsteps;i++)J_passive[i]=reCast<IssmPDouble>(J[i]);
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J_passive,nsteps,1,1,0));
+		xDelete<IssmPDouble>(J_passive);
+		#else
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J,nsteps,1,1,0));
+		#endif
 	}
 
Index: /issm/trunk/src/c/solutions/controlconvergence.cpp
===================================================================
--- /issm/trunk/src/c/solutions/controlconvergence.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/controlconvergence.cpp	(revision 13395)
@@ -8,5 +8,5 @@
 #endif
 
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../io/io.h"
Index: /issm/trunk/src/c/solutions/controlrestart.cpp
===================================================================
--- /issm/trunk/src/c/solutions/controlrestart.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/controlrestart.cpp	(revision 13395)
@@ -25,6 +25,13 @@
 		/*we essentially want J and the parameter: */
 		for(int i=0;i<num_controls;i++) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,control_type[i]);
-		femmodel->results->AddObject(new DoubleVecExternalResult(femmodel->results->Size()+1,JEnum,J,nsteps,1,0));
-		//femmodel->results->AddObject(new StringExternalResult(femmodel->results->Size()+1,InversionControlParametersEnum,EnumToStringx(control_type),1,0));
+		#ifdef _HAVE_ADOLC_
+		IssmPDouble* J_passive=xNew<IssmPDouble>(nsteps);
+		for(int i=0;i<nsteps;i++)J_passive[i]=reCast<IssmPDouble>(J[i]);
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J_passive,nsteps,1,1,0));
+		xDelete<IssmPDouble>(J_passive);
+		#else
+		femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,J,nsteps,1,1,0));
+		#endif
+		//femmodel->results->AddObject(new GenericExternalResult<char*>(femmodel->results->Size()+1,InversionControlParametersEnum,EnumToStringx(control_type),1,0));
 
 		/*write to disk: */
Index: /issm/trunk/src/c/solutions/controltao_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/controltao_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/controltao_core.cpp	(revision 13395)
@@ -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"
@@ -13,5 +13,5 @@
 #include "../solvers/solvers.h"
 
-#if defined (_HAVE_TAO_) && defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ == 2)
+#if defined (_HAVE_TAO_) && defined (_HAVE_PETSC_) && (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 1)
 #include <tao.h>
 
@@ -21,4 +21,5 @@
 typedef struct {
 	FemModel* femmodel;
+	double*   J;
 } AppCtx;
 
@@ -26,14 +27,14 @@
 
 	/*TAO*/
-	int        ierr;
-	int        num_controls,solution_type;
-	int        nsteps,maxiter;
-	AppCtx     user;
-	TaoSolver  tao = 0;
-	IssmDouble    *dummy          = NULL;
-	int       *control_list   = NULL;
-	Vector    *X              = NULL;
-	Vector    *XL             = NULL;
-	Vector    *XU             = NULL;
+	int                 ierr;
+	int                 num_controls,solution_type;
+	int                 nsteps,maxiter;
+	AppCtx              user;
+	TaoSolver           tao = 0;
+	IssmDouble         *dummy        = NULL;
+	int                *control_list = NULL;
+	Vector<IssmDouble> *X            = NULL;
+	Vector<IssmDouble> *XL           = NULL;
+	Vector<IssmDouble> *XU           = NULL;
 
 	/*Initialize TAO*/
@@ -41,5 +42,5 @@
 	PetscGetArgs(&argc,&args);
 	ierr = TaoInitialize(&argc,&args,(char*)0,"");
-	if(ierr) _error2_("Could not initialize Tao");
+	if(ierr) _error_("Could not initialize Tao");
 
 	/*Recover some parameters*/
@@ -69,9 +70,10 @@
 	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
 	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
-	TaoSetInitialVector(tao,X->vector);
-	TaoSetVariableBounds(tao,XL->vector,XU->vector);
+	TaoSetInitialVector(tao,X->pvector->vector);
+	TaoSetVariableBounds(tao,XL->pvector->vector,XU->pvector->vector);
 	xdelete(&XL);
 	xdelete(&XU);
 
+	user.J=xNewZeroInit<double>(maxiter+5);
 	user.femmodel=femmodel;
 	TaoSetObjectiveAndGradientRoutine(tao,FormFunctionGradient,(void*)&user); 
@@ -81,9 +83,10 @@
 	TaoSolve(tao);
 	TaoView(tao,PETSC_VIEWER_STDOUT_WORLD);
-	TaoGetSolutionVector(tao,&X->vector);
+	TaoGetSolutionVector(tao,&X->pvector->vector);
 	SetControlInputsFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X);
 	for(int i=0;i<num_controls;i++){
 		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,control_list[i]);
 	}
+	femmodel->results->AddObject(new GenericExternalResult<double*>(femmodel->results->Size()+1,JEnum,user.J,maxiter+3,1,1,0));
 
 	/*Finalize*/
@@ -103,14 +106,14 @@
 
 	/*Retreive arguments*/
-	int       solution_type,num_cost_functions;
-	AppCtx   *user           = (AppCtx *)userCtx;
-	FemModel *femmodel       = user->femmodel;
-	int      *cost_functions = NULL;
-	IssmDouble   *cost_functionsd= NULL;
-	Vector   *gradient       = NULL;
-	Vector   *X              = NULL;
+	int                  solution_type,num_cost_functions;
+	AppCtx              *user            = (AppCtx *)userCtx;
+	FemModel            *femmodel        = user->femmodel;
+	int                 *cost_functions  = NULL;
+	IssmDouble          *cost_functionsd = NULL;
+	Vector<IssmDouble>  *gradient        = NULL;
+	Vector<IssmDouble>  *X               = NULL;
 
 	/*Convert input to Vec*/
-	X=new Vector(Xpetsc);
+	X=new Vector<IssmDouble>(Xpetsc);
 
 	/*Set new variable*/
@@ -142,5 +145,5 @@
 	/*Compute gradient*/
 	Gradjx(&gradient,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-	VecCopy(gradient->vector,G); xdelete(&gradient);
+	VecCopy(gradient->pvector->vector,G); xdelete(&gradient);
 	VecScale(G,-1.);
 
@@ -166,4 +169,5 @@
 	if(its==0) _pprintLine_("-----------------------------------+-----------------------");
 	_pprintString_(setw(4)<<its<<"   "<<setw(12)<<setprecision(7)<<f<<"  "<<setw(12)<<setprecision(7)<<gnorm<<"  | ");
+	user->J[its]=f;
 
 	/*Retrieve objective functions independently*/
@@ -181,5 +185,5 @@
 #else
 void controltao_core(FemModel* femmodel){
-	_error2_("TAO not installed or PETSc version not supported");
+	_error_("TAO not installed or PETSc version not supported");
 }
 #endif //_HAVE_TAO_ 
Index: /issm/trunk/src/c/solutions/convergence.cpp
===================================================================
--- /issm/trunk/src/c/solutions/convergence.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/convergence.cpp	(revision 13395)
@@ -3,10 +3,10 @@
  */ 
 
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../modules/modules.h"
 #include "../io/io.h"
 #include "../EnumDefinitions/EnumDefinitions.h"
 
-void convergence(bool* pconverged, Matrix* Kff,Vector* pf,Vector* uf,Vector* old_uf,Parameters* parameters){
+void convergence(bool* pconverged, Matrix<IssmDouble>* Kff,Vector<IssmDouble>* pf,Vector<IssmDouble>* uf,Vector<IssmDouble>* old_uf,Parameters* parameters){
 
 	/*output*/
@@ -14,9 +14,9 @@
 
 	/*intermediary*/
-	Vector* KU=NULL;
-	Vector* KUF=NULL;
-	Vector* KUold=NULL;
-	Vector* KUoldF=NULL;
-	Vector* duf=NULL;
+	Vector<IssmDouble>* KU=NULL;
+	Vector<IssmDouble>* KUF=NULL;
+	Vector<IssmDouble>* KUold=NULL;
+	Vector<IssmDouble>* KUoldF=NULL;
+	Vector<IssmDouble>* duf=NULL;
 	IssmDouble ndu,nduinf,nu;
 	IssmDouble nKUF;
@@ -72,5 +72,5 @@
 	if (xIsNan<IssmDouble>(res)){
 		_pprintLine_("norm nf = " << nF << "f and norm kuold = " << nKUoldF << "f");
-		_error2_("mechanical equilibrium convergence criterion is NaN!");
+		_error_("mechanical equilibrium convergence criterion is NaN!");
 	}
 
@@ -81,9 +81,9 @@
 	//print
 	if(res<eps_res){
-		if(VerboseConvergence()) _pprintLine_(setw(50) << left << "   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{ 
-		if(VerboseConvergence()) _pprintLine_(setw(50) << left << "   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;
 	}
@@ -96,5 +96,5 @@
 		ndu=duf->Norm(NORM_TWO); nu=old_uf->Norm(NORM_TWO);
 
-		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error2_("convergence criterion is NaN!");
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
 
 		//clean up
@@ -121,5 +121,5 @@
 		duf=old_uf->Duplicate(); old_uf->Copy(duf); duf->AYPX(uf,-1.0);
 		ndu=duf->Norm(NORM_TWO); nduinf=duf->Norm(NORM_INF);
-		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error2_("convergence criterion is NaN!");
+		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
 
 		//clean up
Index: /issm/trunk/src/c/solutions/diagnostic_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/diagnostic_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/diagnostic_core.cpp	(revision 13395)
@@ -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,4 +20,5 @@
 	bool  ishutter          = false;
 	bool  ismacayealpattyn  = false;
+	bool  isl1l2            = false;
 	bool  isstokes          = false;
 	bool  isnewton          = false;
@@ -33,4 +34,5 @@
 	femmodel->parameters->FindParam(&ishutter,FlowequationIshutterEnum);
 	femmodel->parameters->FindParam(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
+	femmodel->parameters->FindParam(&isl1l2,FlowequationIsl1l2Enum);
 	femmodel->parameters->FindParam(&isstokes,FlowequationIsstokesEnum);
 	femmodel->parameters->FindParam(&isnewton,DiagnosticIsnewtonEnum);
@@ -70,5 +72,5 @@
 	}
 
-	if (ismacayealpattyn ^ isstokes){ // ^ = xor
+	if ((ismacayealpattyn || isl1l2) ^ isstokes){ // ^ = xor
 		
 		if(VerboseSolution()) _pprintLine_("   computing velocities");
Index: /issm/trunk/src/c/solutions/enthalpy_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/enthalpy_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/enthalpy_core.cpp	(revision 13395)
@@ -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"
Index: /issm/trunk/src/c/solutions/gradient_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/gradient_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/gradient_core.cpp	(revision 13395)
@@ -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"
@@ -18,7 +18,7 @@
 	IssmDouble  norm_inf;
 	IssmDouble *norm_list    = NULL;
-	Vector*     new_gradient = NULL;
-	Vector*     gradient     = NULL;
-	Vector*     old_gradient = NULL;
+	Vector<IssmDouble>*     new_gradient = NULL;
+	Vector<IssmDouble>*     gradient     = NULL;
+	Vector<IssmDouble>*     old_gradient = NULL;
 
 	/*Compute gradient*/
@@ -37,6 +37,6 @@
 	/*Check that gradient is clean*/
 	norm_inf=new_gradient->Norm(NORM_INF);
-	if(norm_inf<=0)    _error2_("||∂J/∂α||∞ = 0    gradient norm is zero");
-	if(xIsNan<IssmDouble>(norm_inf))_error2_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
+	if(norm_inf<=0)    _error_("||∂J/∂α||∞ = 0    gradient norm is zero");
+	if(xIsNan<IssmDouble>(norm_inf))_error_("||∂J/∂α||∞ = NaN  gradient norm is NaN");
 
 	/*plug back into inputs: */
Index: /issm/trunk/src/c/solutions/hydrology_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/hydrology_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/hydrology_core.cpp	(revision 13395)
@@ -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"
@@ -39,5 +39,5 @@
 		nsteps=1;
 	}
-	else nsteps=(int)((final_time-starttime)/dt);
+	else nsteps=reCast<int,IssmDouble>((final_time-starttime)/dt);
 	time=starttime;
 
Index: /issm/trunk/src/c/solutions/hydrology_core_step.cpp
===================================================================
--- /issm/trunk/src/c/solutions/hydrology_core_step.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/hydrology_core_step.cpp	(revision 13395)
@@ -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"
Index: /issm/trunk/src/c/solutions/issm.cpp
===================================================================
--- /issm/trunk/src/c/solutions/issm.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/issm.cpp	(revision 13395)
@@ -5,4 +5,5 @@
 #include "../issm.h"
 #include "../include/globals.h"
+#include "../shared/Numerics/adolc_edf.h"
 
 int main(int argc,char **argv){
@@ -14,4 +15,8 @@
 	bool  dakota_analysis,control_analysis,tao_analysis;
 
+	/*AD: */
+	bool autodiff=false;
+	size_t   tape_stats[11];
+
 	/*FemModel: */
 	FemModel *femmodel = NULL;
@@ -28,4 +33,5 @@
 	char *outbinfilename = NULL;
 	char *petscfilename  = NULL;
+	char *rootpath       = NULL;
 
 	/*time*/
@@ -42,8 +48,9 @@
 	ISSMBOOT();
 
+	
 	/*Initialize environments: Petsc, MPI, etc...: */
 	#ifdef _HAVE_PETSC_
 	ierr=PetscInitialize(&argc,&argv,(char*)0,"");  
-	if(ierr) _error2_("Could not initialize Petsc");
+	if(ierr) _error_("Could not initialize Petsc");
 	#else
 	#ifdef _HAVE_MPI_
@@ -69,9 +76,14 @@
 	_pprintLine_("(website: " << PACKAGE_URL << " contact: " << PACKAGE_BUGREPORT << ")");
 	_pprintLine_("");
-	ProcessArguments(&solution_type,&binfilename,&outbinfilename,&petscfilename,&lockfilename,argc,argv);
+	ProcessArguments(&solution_type,&binfilename,&outbinfilename,&petscfilename,&lockfilename,&rootpath,argc,argv);
 
 	/*out of solution_type, figure out types of analyses needed in the femmodel: */
 	AnalysisConfiguration(&analyses,&numanalyses,solution_type);
-	
+
+	/*before we create the model, start the trace on for AD mode: */
+	#ifdef _HAVE_ADOLC_
+	trace_on(1);
+	#endif
+
 	/*Create femmodel, using input file: */
 	#ifdef _HAVE_MPI_
@@ -80,5 +92,5 @@
 	start_init=(IssmPDouble)clock();
 	#endif
-	femmodel=new FemModel(binfilename,outbinfilename,solution_type,analyses,numanalyses);
+	femmodel=new FemModel(rootpath,binfilename,outbinfilename,solution_type,analyses,numanalyses);
 	
 	/*get type of solution we are going to run: */
@@ -100,4 +112,5 @@
 	femmodel->parameters->FindParam(&tao_analysis,InversionTaoEnum);
 	femmodel->parameters->FindParam(&profiling,DebugProfilingEnum); 
+	femmodel->parameters->FindParam(&autodiff,AutodiffIsautodiffEnum);
 
 	#ifdef _HAVE_MPI_
@@ -105,4 +118,13 @@
 	#else
 	finish_init=(IssmPDouble)clock();
+	#endif
+	
+	/*If running AD, then initialize the tape: */
+	#ifdef _HAVE_ADOLC_
+	GenericParam<Adolc_edf> *theAdolcEDF_p=new GenericParam<Adolc_edf>(AdolcParamEnum);
+	theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p=reg_ext_fct(EDF_for_solverx);
+	femmodel->parameters->AddObject(theAdolcEDF_p);
+	#else
+	if(autodiff) _error_("ISSM was not compiled with ADOLC support, cannot carry out autodiff analysis!");
 	#endif
 
@@ -120,5 +142,5 @@
 		Dakotax(femmodel);
 		#else
-		_error2_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
+		_error_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
 		#endif
 	}
@@ -130,5 +152,5 @@
 		 control_core(femmodel);
 		#else
-		_error2_("ISSM was not compiled with control support, cannot carry out dakota analysis!");
+		_error_("ISSM was not compiled with control support, cannot carry out dakota analysis!");
 		#endif
 	}
@@ -139,8 +161,15 @@
 	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));
-	}
+		femmodel->results->AddObject(new GenericExternalResult<double>(femmodel->results->Size()+1, ProfilingSolutionTimeEnum, Solution_time, 1, 0));
+		femmodel->results->AddObject(new GenericExternalResult<double>(femmodel->results->Size()+1, ProfilingCurrentMemEnum, Memory_use, 1, 0));
+		femmodel->results->AddObject(new GenericExternalResult<double>(femmodel->results->Size()+1, ProfilingCurrentFlopsEnum, Current_flops, 1, 0));
+	}
+
+	#ifdef _HAVE_ADOLC_
+	if(autodiff){
+		trace_off();
+		AutodiffDriversx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
+	}
+	#endif
 
 
@@ -150,7 +179,21 @@
 	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);
+	
+	/*If running AD, close our tape, print statistics: {{{*/
+	#ifdef _HAVE_ADOLC_
+	if(autodiff){
+		tapestats(1,tape_stats); //reading of tape statistics
+		_pprintLine_("   ADOLC statistics: ");
+		_pprintLine_("   "<<setw(45)<<left<<"Number of independents: " <<tape_stats[0]);
+		_pprintLine_("   "<<setw(45)<<left<<"Number of dependents: " <<tape_stats[1]);
+		_pprintLine_("   "<<setw(45)<<left<<"Maximal number of live active variables: " <<tape_stats[2]);
+		_pprintLine_("   "<<setw(45)<<left<<"Size of value stack (number of overwrites): " <<tape_stats[3]);
+		_pprintLine_("   "<<setw(45)<<left<<"Buffer size (a multiple of eight): " <<tape_stats[4]);
+		_pprintLine_("   "<<setw(45)<<left<<"Total number of operations recorded: " <<tape_stats[5]);
+	}
+	#endif  /*}}}*/
 
 	/*Close output and petsc options file and write lock file if requested*/
@@ -167,4 +210,5 @@
 	xDelete<char>(outbinfilename);
 	xDelete<char>(petscfilename);
+	xDelete<char>(rootpath);
 	delete femmodel;
 
@@ -200,4 +244,5 @@
 	#endif
 	#endif
+
 	
 	/*end module: */
Index: /issm/trunk/src/c/solutions/kriging.cpp
===================================================================
--- /issm/trunk/src/c/solutions/kriging.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/kriging.cpp	(revision 13395)
@@ -7,5 +7,5 @@
 
 /*Local prototypes*/
-void ProcessArguments2(char** pbinfilename,char** poutbinfilename,char** plockfilename,int argc,char **argv);
+void ProcessArguments2(char** pbinfilename,char** poutbinfilename,char** plockfilename,char** prootpath,int argc,char **argv);
 void ProcessInputfile(IssmDouble **px,IssmDouble **py,IssmDouble **pdata,int *pnobs,IssmDouble **px_interp,IssmDouble **py_interp,int *pninterp,Options **poptions,FILE* fid);
 
@@ -21,13 +21,14 @@
 	char *binfilename    = NULL;
 	char *outbinfilename = NULL;
+	char *rootpath       = 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;
+	int         ninterp,nobs;
+	IssmDouble *x        = NULL;
+	IssmDouble *y        = NULL;
+	IssmDouble *data     = NULL;
+	IssmDouble *x_interp = NULL;
+	IssmDouble *y_interp = NULL;
+	Options    *options  = NULL;
 
 	/*Output*/
@@ -40,5 +41,5 @@
 #ifdef _HAVE_PETSC_
 	int ierr=PetscInitialize(&argc,&argv,(char*)0,"");  
-	if(ierr) _error2_("Could not initialize Petsc");
+	if(ierr) _error_("Could not initialize Petsc");
 #else
 #ifdef _HAVE_MPI_
@@ -58,5 +59,5 @@
 	_pprintLine_("(website: " << PACKAGE_URL << " contact: " << PACKAGE_BUGREPORT << ")");
 	_pprintLine_("");
-	ProcessArguments2(&binfilename,&outbinfilename,&lockfilename,argc,argv);
+	ProcessArguments2(&binfilename,&outbinfilename,&lockfilename,&rootpath,argc,argv);
 
 	/*Process input files*/
@@ -72,6 +73,6 @@
 	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));
+		results->AddObject(new GenericExternalResult<double*>(results->Size()+1,0,predictions,ninterp,1,1,0));
+		results->AddObject(new GenericExternalResult<double*>(results->Size()+1,1,error,ninterp,1,1,0));
 		for(int i=0;i<results->Size();i++){
 			ExternalResult* result=(ExternalResult*)results->GetObjectByOffset(i);
@@ -89,4 +90,5 @@
 	xDelete<char>(binfilename);
 	xDelete<char>(outbinfilename);
+	xDelete<char>(rootpath);
 	xDelete<IssmDouble>(x);
 	xDelete<IssmDouble>(y);
@@ -115,16 +117,34 @@
 }
 
-void ProcessArguments2(char** pbinfilename,char** poutbinfilename,char** plockfilename,int argc,char **argv){
-
+void ProcessArguments2(char** pbinfilename,char** poutbinfilename,char** plockfilename,char** prootpath,int argc,char **argv){
 	char *modelname      = NULL;
 	char *binfilename    = NULL;
 	char *outbinfilename = NULL;
 	char *lockfilename   = NULL;
+	char *rootpatharg    = NULL;
+	char *rootpath       = NULL;
 
-	if(argc<2)_error2_("Usage error: missing model name");
+	if(argc<1)_error_("Usage error: no execution path provided");
+	if(argc<2)_error_("Usage error: missing model name");
+
+	rootpatharg=argv[1];
+	if(strcmp(strstr(rootpatharg,"/"),"/")!=0){ 
+		rootpath       = xNew<char>(strlen(rootpatharg)+2); sprintf(rootpath,"%s/",rootpatharg);
+	}  
+	else{
+		rootpath       = xNew<char>(strlen(rootpatharg)+1); sprintf(rootpath,"%s",rootpatharg);
+	} 
+
 	modelname=argv[2];
-	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");
+	if(strstr(modelname,rootpath)==NULL){
+		binfilename    = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s%s",rootpath,modelname,".bin");
+		outbinfilename = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s%s",rootpath,modelname,".outbin");
+		lockfilename   = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s%s",rootpath,modelname,".lock");
+	}
+	else{
+		binfilename    = xNew<char>(strlen(modelname)+strlen(".bin")   +1); sprintf(binfilename,   "%s%s",modelname,".bin");
+		outbinfilename = xNew<char>(strlen(modelname)+strlen(".outbin")+1); sprintf(outbinfilename,"%s%s",modelname,".outbin");
+		lockfilename   = xNew<char>(strlen(modelname)+strlen(".lock")  +1); sprintf(lockfilename,  "%s%s",modelname,".lock");
+	}
 
 	/*Clean up and assign output pointer*/
@@ -132,4 +152,5 @@
 	*poutbinfilename=outbinfilename;
 	*plockfilename=lockfilename;
+	*prootpath=rootpath;
 }
 
@@ -149,4 +170,5 @@
 	iomodel->fid=fid;
 	iomodel->CheckEnumSync();
+	iomodel->independents=xNew<bool>(MaximumNumberOfEnums); for(int i=0;i<MaximumNumberOfEnums;i++) iomodel->independents[i]=false;
 	iomodel->FetchData(&x,&M,&N,0);        nobs=M*N;
 	iomodel->FetchData(&y,&M,&N,1);        _assert_(M*N==nobs);
Index: /issm/trunk/src/c/solutions/objectivefunction.cpp
===================================================================
--- /issm/trunk/src/c/solutions/objectivefunction.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/objectivefunction.cpp	(revision 13395)
@@ -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"
@@ -49,5 +49,5 @@
 	}
 	else{
-		_error2_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
+		_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
 	}
 
@@ -66,5 +66,5 @@
 	}
 	else{
-		_error2_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
+		_error_("Solution " << EnumToStringx(solution_type) << " not implemented yet");
 	}
 
Index: /issm/trunk/src/c/solutions/prognostic_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/prognostic_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/prognostic_core.cpp	(revision 13395)
@@ -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,5 @@
 	/*parameters: */
 	bool save_results;
-	bool ispdd;
-	bool issmbgradients;
+	bool issmbgradients,ispdd,isdelta18o;
 
 	/*activate formulation: */
@@ -24,11 +23,7 @@
 	/*recover parameters: */
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&issmbgradients,SurfaceforcingsIssmbgradientsEnum);
 	femmodel->parameters->FindParam(&ispdd,SurfaceforcingsIspddEnum);
-	femmodel->parameters->FindParam(&issmbgradients,SurfaceforcingsIssmbgradientsEnum);
-
-	if(ispdd){
-	  if(VerboseSolution()) _pprintLine_("   call positive degree day module");
-	  PositiveDegreeDayx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-	}
+	femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
 
 	if(issmbgradients){
@@ -36,5 +31,12 @@
 	  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);
Index: /issm/trunk/src/c/solutions/solutions.h
===================================================================
--- /issm/trunk/src/c/solutions/solutions.h	(revision 13394)
+++ /issm/trunk/src/c/solutions/solutions.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define SOLUTIONS_H_
 
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../io/io.h"
 
@@ -33,5 +33,5 @@
 
 //convergence:
-void convergence(bool* pconverged, Matrix* K_ff,Vector* p_f,Vector* u_f,Vector* u_f_old,Parameters* parameters);
+void convergence(bool* pconverged, Matrix<IssmDouble>* K_ff,Vector<IssmDouble>* p_f,Vector<IssmDouble>* u_f,Vector<IssmDouble>* u_f_old,Parameters* parameters);
 bool controlconvergence(IssmDouble J,IssmDouble tol_cm);
 bool steadystateconvergence(FemModel* femmodel);
@@ -41,5 +41,5 @@
 
 //diverse
-void ProcessArguments(int* solution,char** pbinname,char** poutbinname,char** ppetscname,char** plockname,int argc,char **argv);
+void ProcessArguments(int* solution,char** pbinname,char** poutbinname,char** ppetscname,char** plockname,char** prootpath,int argc,char **argv);
 void WriteLockFile(char* filename);
 void controlrestart(FemModel* femmodel,IssmDouble* J);
Index: /issm/trunk/src/c/solutions/steadystate_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/steadystate_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/steadystate_core.cpp	(revision 13395)
@@ -11,5 +11,5 @@
 #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"
@@ -52,5 +52,5 @@
 		}
 		#else
-		_error2_("ISSM was not compiled with thermal capabilities. Exiting");
+		_error_("ISSM was not compiled with thermal capabilities. Exiting");
 		#endif
 
Index: /issm/trunk/src/c/solutions/steadystateconvergence.cpp
===================================================================
--- /issm/trunk/src/c/solutions/steadystateconvergence.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/steadystateconvergence.cpp	(revision 13395)
@@ -9,5 +9,5 @@
 #endif
 
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../shared/shared.h"
 #include "../Container/Container.h"
Index: /issm/trunk/src/c/solutions/surfaceslope_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/surfaceslope_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/surfaceslope_core.cpp	(revision 13395)
@@ -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"
Index: /issm/trunk/src/c/solutions/thermal_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/thermal_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/thermal_core.cpp	(revision 13395)
@@ -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"
Index: /issm/trunk/src/c/solutions/transient_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/transient_core.cpp	(revision 13394)
+++ /issm/trunk/src/c/solutions/transient_core.cpp	(revision 13395)
@@ -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"
@@ -24,5 +24,5 @@
 	/*parameters: */
 	IssmDouble starttime,finaltime,dt,yts;
-	bool   isdiagnostic,isprognostic,isthermal,isgroundingline,isenthalpy;
+	bool   isdiagnostic,isprognostic,isthermal,isgroundingline,isenthalpy,isdelta18o;
 	bool   save_results,dakota_analysis;
 	bool   time_adapt=false;
@@ -53,4 +53,5 @@
 	femmodel->parameters->FindParam(&numoutputs,TransientNumRequestedOutputsEnum);
 	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,TransientRequestedOutputsEnum);
+	femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
 
 	/*initialize: */
@@ -103,8 +104,8 @@
 			}
 			#else
-			_error2_("ISSM was not compiled with thermal capabilities. Exiting");
+			_error_("ISSM was not compiled with thermal capabilities. Exiting");
 			#endif
 		}
-
+		
 		if(isdiagnostic){
 			if(VerboseSolution()) _pprintLine_("   computing new velocity");
@@ -112,5 +113,5 @@
 			diagnostic_core(femmodel);
 			#else
-			_error2_("ISSM was not compiled with diagnostic capabilities. Exiting");
+			_error_("ISSM was not compiled with diagnostic capabilities. Exiting");
 			#endif
 		}
@@ -128,5 +129,5 @@
 			GroundinglineMigrationx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
 			#else
-			_error2_("ISSM was not compiled with grounding line migration capabilities. Exiting");
+			_error_("ISSM was not compiled with grounding line migration capabilities. Exiting");
 			#endif
 		}
@@ -141,4 +142,9 @@
 			RequestedOutputsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,requested_outputs,numoutputs);
 
+			if(isdelta18o){
+			        InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceforcingsMonthlytemperaturesEnum);
+			        InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceforcingsPrecipitationEnum);
+			}
+
 			if(VerboseSolution()) _pprintLine_("   saving temporary results");
 			OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
@@ -146,4 +152,6 @@
 	}
 
+	RequestedDependentsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	
 	/*Free ressources:*/
 	xDelete<int>(requested_outputs);
Index: /issm/trunk/src/c/solvers/solver_adjoint_linear.cpp
===================================================================
--- /issm/trunk/src/c/solvers/solver_adjoint_linear.cpp	(revision 13394)
+++ /issm/trunk/src/c/solvers/solver_adjoint_linear.cpp	(revision 13395)
@@ -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"
@@ -13,11 +13,11 @@
 
 	/*intermediary: */
-	Matrix*  Kff = NULL;
-	Matrix*  Kfs = NULL;
-	Vector*  ug  = NULL;
-	Vector*  uf  = NULL;
-	Vector*  pf  = NULL;
-	Vector*  df  = NULL;
-	Vector*  ys  = NULL;
+	Matrix<IssmDouble>*  Kff = NULL;
+	Matrix<IssmDouble>*  Kfs = NULL;
+	Vector<IssmDouble>*  ug  = NULL;
+	Vector<IssmDouble>*  uf  = NULL;
+	Vector<IssmDouble>*  pf  = NULL;
+	Vector<IssmDouble>*  df  = NULL;
+	Vector<IssmDouble>*  ys  = NULL;
 	int  configuration_type;
 
Index: /issm/trunk/src/c/solvers/solver_linear.cpp
===================================================================
--- /issm/trunk/src/c/solvers/solver_linear.cpp	(revision 13394)
+++ /issm/trunk/src/c/solvers/solver_linear.cpp	(revision 13395)
@@ -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"
@@ -11,11 +11,11 @@
 
 	/*intermediary: */
-	Matrix*  Kff = NULL;
-	Matrix*  Kfs = NULL;
-	Vector*  ug  = NULL;
-	Vector*  uf  = NULL;
-	Vector*  pf  = NULL;
-	Vector*  df  = NULL;
-	Vector*  ys  = NULL;
+	Matrix<IssmDouble>*  Kff = NULL;
+	Matrix<IssmDouble>*  Kfs = NULL;
+	Vector<IssmDouble>*  ug  = NULL;
+	Vector<IssmDouble>*  uf  = NULL;
+	Vector<IssmDouble>*  pf  = NULL;
+	Vector<IssmDouble>*  df  = NULL;
+	Vector<IssmDouble>*  ys  = NULL;
 	int  configuration_type;
 
@@ -29,4 +29,9 @@
 	Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
 	xdelete(&Kff); xdelete(&pf); xdelete(&df);
+//#ifdef  _HAVE_ADOLC_
+//        for (int i =0; i<uf->svector->M; ++i) {
+//          ADOLC_DUMP_MACRO(uf->svector->vector[i]);
+//        }
+//#endif
 	Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);xdelete(&uf); xdelete(&ys);
 	InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug); 
Index: /issm/trunk/src/c/solvers/solver_newton.cpp
===================================================================
--- /issm/trunk/src/c/solvers/solver_newton.cpp	(revision 13394)
+++ /issm/trunk/src/c/solvers/solver_newton.cpp	(revision 13395)
@@ -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"
@@ -18,16 +18,16 @@
 	int    count;
 	IssmDouble kmax;
-	Matrix* Kff = NULL;
-	Matrix* Kfs    = NULL;
-	Matrix* Jff = NULL;
-	Vector* ug  = NULL;
-	Vector* old_ug = NULL;
-	Vector* uf  = NULL;
-	Vector* old_uf = NULL;
-	Vector* duf = NULL;
-	Vector* pf  = NULL;
-	Vector* pJf    = NULL;
-	Vector* df  = NULL;
-	Vector* ys  = NULL;
+	Matrix<IssmDouble>* Kff = NULL;
+	Matrix<IssmDouble>* Kfs    = NULL;
+	Matrix<IssmDouble>* Jff = NULL;
+	Vector<IssmDouble>* ug  = NULL;
+	Vector<IssmDouble>* old_ug = NULL;
+	Vector<IssmDouble>* uf  = NULL;
+	Vector<IssmDouble>* old_uf = NULL;
+	Vector<IssmDouble>* duf = NULL;
+	Vector<IssmDouble>* pf  = NULL;
+	Vector<IssmDouble>* pJf    = NULL;
+	Vector<IssmDouble>* df  = NULL;
+	Vector<IssmDouble>* ys  = NULL;
 
 	/*parameters:*/
@@ -71,5 +71,5 @@
 			int tempStep=1;
 			IssmDouble tempTime=1.0;
-			femmodel->results->AddObject(new BoolExternalResult(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
+			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
 			break;
 		}
@@ -79,5 +79,5 @@
 			int tempStep=1;
 			IssmDouble tempTime=1.0;
-			femmodel->results->AddObject(new BoolExternalResult(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
+			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
 			break;
 		}
Index: /issm/trunk/src/c/solvers/solver_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solvers/solver_nonlinear.cpp	(revision 13394)
+++ /issm/trunk/src/c/solvers/solver_nonlinear.cpp	(revision 13395)
@@ -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"
@@ -14,13 +14,13 @@
 
 	/*intermediary: */
-	Matrix* Kff = NULL;
-	Matrix* Kfs = NULL;
-	Vector* ug  = NULL;
-	Vector* old_ug = NULL;
-	Vector* uf  = NULL;
-	Vector* old_uf = NULL;
-	Vector* pf  = NULL;
-	Vector* df  = NULL;
-	Vector* ys  = NULL;
+	Matrix<IssmDouble>* Kff = NULL;
+	Matrix<IssmDouble>* Kfs = NULL;
+	Vector<IssmDouble>* ug  = NULL;
+	Vector<IssmDouble>* old_ug = NULL;
+	Vector<IssmDouble>* uf  = NULL;
+	Vector<IssmDouble>* old_uf = NULL;
+	Vector<IssmDouble>* pf  = NULL;
+	Vector<IssmDouble>* df  = NULL;
+	Vector<IssmDouble>* ys  = NULL;
 	
 	Loads* loads=NULL;
@@ -89,5 +89,5 @@
 			int tempStep=1;
 			IssmDouble tempTime=1.0;
-			femmodel->results->AddObject(new BoolExternalResult(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
+			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
 			break;
 		}
@@ -100,5 +100,5 @@
 			int tempStep=1;
 			IssmDouble tempTime=1.0;
-			femmodel->results->AddObject(new BoolExternalResult(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
+			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
 			break;
 		}
Index: /issm/trunk/src/c/solvers/solver_stokescoupling_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solvers/solver_stokescoupling_nonlinear.cpp	(revision 13394)
+++ /issm/trunk/src/c/solvers/solver_stokescoupling_nonlinear.cpp	(revision 13395)
@@ -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"
@@ -14,18 +14,18 @@
 
 	/*intermediary: */
-	Matrix*  Kff_horiz = NULL;
-	Matrix* Kfs_horiz   = NULL;
-	Vector*  ug_horiz  = NULL;
-	Vector*  uf_horiz  = NULL;
-	Vector*  old_uf_horiz = NULL;
-	Vector*  pf_horiz  = NULL;
-	Vector*  df_horiz  = NULL;
-	Matrix*  Kff_vert  = NULL;
-	Matrix*  Kfs_vert  = NULL;
-	Vector*  ug_vert   = NULL;
-	Vector*  uf_vert   = NULL;
-	Vector*  pf_vert   = NULL;
-	Vector*  df_vert   = NULL;
-	Vector*  ys   = NULL;
+	Matrix<IssmDouble>*  Kff_horiz = NULL;
+	Matrix<IssmDouble>* Kfs_horiz   = NULL;
+	Vector<IssmDouble>*  ug_horiz  = NULL;
+	Vector<IssmDouble>*  uf_horiz  = NULL;
+	Vector<IssmDouble>*  old_uf_horiz = NULL;
+	Vector<IssmDouble>*  pf_horiz  = NULL;
+	Vector<IssmDouble>*  df_horiz  = NULL;
+	Matrix<IssmDouble>*  Kff_vert  = NULL;
+	Matrix<IssmDouble>*  Kfs_vert  = NULL;
+	Vector<IssmDouble>*  ug_vert   = NULL;
+	Vector<IssmDouble>*  uf_vert   = NULL;
+	Vector<IssmDouble>*  pf_vert   = NULL;
+	Vector<IssmDouble>*  df_vert   = NULL;
+	Vector<IssmDouble>*  ys   = NULL;
 	bool converged;
 	int  constraints_converged;
Index: /issm/trunk/src/c/solvers/solver_thermal_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solvers/solver_thermal_nonlinear.cpp	(revision 13394)
+++ /issm/trunk/src/c/solvers/solver_thermal_nonlinear.cpp	(revision 13395)
@@ -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"
@@ -12,15 +12,15 @@
 
 	/*solution : */
-	Vector* tg=NULL; 
-	Vector* tf=NULL; 
-	Vector* tf_old=NULL; 
-	Vector* ys=NULL; 
+	Vector<IssmDouble>* tg=NULL; 
+	Vector<IssmDouble>* tf=NULL; 
+	Vector<IssmDouble>* tf_old=NULL; 
+	Vector<IssmDouble>* ys=NULL; 
 	IssmDouble melting_offset;
 
 	/*intermediary: */
-	Matrix* Kff=NULL;
-	Matrix* Kfs=NULL;
-	Vector* pf=NULL;
-	Vector* df=NULL;
+	Matrix<IssmDouble>* Kff=NULL;
+	Matrix<IssmDouble>* Kfs=NULL;
+	Vector<IssmDouble>* pf=NULL;
+	Vector<IssmDouble>* df=NULL;
 
 	bool converged;
Index: /issm/trunk/src/c/solvers/solvers.h
===================================================================
--- /issm/trunk/src/c/solvers/solvers.h	(revision 13394)
+++ /issm/trunk/src/c/solvers/solvers.h	(revision 13395)
@@ -6,5 +6,5 @@
 #define SOLVERS_H_
 
-#include "../objects/objects.h"
+#include "../classes/objects/objects.h"
 #include "../io/io.h"
 
Index: sm/trunk/src/c/toolkits/issm/SeqMat.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/issm/SeqMat.cpp	(revision 13394)
+++ 	(revision )
@@ -1,211 +1,0 @@
-/*!\file SeqMat.cpp
- * \brief: implementation of the SeqMat 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 "../toolkits.h"
-#include "../../shared/shared.h"
-
-/*}}}*/
-
-/*SeqMat constructors and destructor*/
-/*FUNCTION SeqMat::SeqMat(){{{*/
-SeqMat::SeqMat(){
-
-	this->M=0;
-	this->N=0;
-	this->matrix=NULL;
-}
-/*}}}*/
-/*FUNCTION SeqMat::SeqMat(int M,int N){{{*/
-SeqMat::SeqMat(int pM,int pN){
-
-	this->M=pM;
-	this->N=pN;
-	this->matrix=NULL;
-	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(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){{{*/
-SeqMat::SeqMat(IssmDouble* serial_mat,int pM,int pN,IssmDouble sparsity){
-
-	int i,j;
-
-	this->M=pM;
-	this->N=pN;
-	this->matrix=NULL;
-	if(M*N){
-		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){
-
-	this->M=pM;
-	this->N=pN;
-	this->matrix=NULL;
-	if(M*N) this->matrix=xNewZeroInit<IssmDouble>(pM*pN);
-}
-/*}}}*/
-/*FUNCTION SeqMat::~SeqMat(){{{*/
-SeqMat::~SeqMat(){
-
-	xDelete<IssmDouble>(this->matrix);
-	M=0;
-	N=0;
-}
-/*}}}*/
-
-/*SeqMat specific routines: */
-/*FUNCTION SeqMat::Echo{{{*/
-void SeqMat::Echo(void){
-
-	int i,j;
-	_printLine_("SeqMat size " << this->M << "-" << this->N);
-	for(i=0;i<M;i++){
-		for(j=0;j<N;j++){
-			_printString_(this->matrix[N*i+j] << " ");
-		}
-		_printLine_("");
-	}
-}
-/*}}}*/
-/*FUNCTION SeqMat::Assemble{{{*/
-void SeqMat::Assemble(void){
-		
-	/*do nothing*/
-
-}
-/*}}}*/
-/*FUNCTION SeqMat::Norm{{{*/
-IssmDouble SeqMat::Norm(NormMode mode){
-
-	IssmDouble norm;
-	IssmDouble absolute;
-	int i,j;
-
-	switch(mode){
-		case NORM_INF:
-			norm=0;
-			for(i=0;i<this->M;i++){
-				absolute=0;
-				for(j=0;j<this->N;j++){
-					absolute+=fabs(this->matrix[N*i+j]);
-				}
-				norm=max(norm,absolute);
-			}
-			return norm;
-			break;
-		default:
-			_error2_("unknown norm !");
-			break;
-	}
-}
-/*}}}*/
-/*FUNCTION SeqMat::GetSize{{{*/
-void SeqMat::GetSize(int* pM,int* pN){
-
-	*pM=this->M;
-	*pN=this->N;
-
-}
-/*}}}*/
-/*FUNCTION SeqMat::GetLocalSize{{{*/
-void SeqMat::GetLocalSize(int* pM,int* pN){
-	
-	*pM=this->M;
-	*pN=this->N;
-
-}
-/*}}}*/
-/*FUNCTION SeqMat::MatMult{{{*/
-void SeqMat::MatMult(SeqVec* X,SeqVec* AX){
-
-	int i,j;
-	int XM,AXM;
-	IssmDouble dummy;
-
-	X->GetSize(&XM);
-	AX->GetSize(&AXM);
-
-	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++){
-		dummy=0;
-		for(j=0;j<N;j++){
-			dummy+= this->matrix[N*i+j]*X->vector[j];
-		}
-		AX->vector[i]=dummy;
-	}
-
-}
-/*}}}*/
-/*FUNCTION SeqMat::Duplicate{{{*/
-SeqMat* SeqMat::Duplicate(void){
-
-	IssmDouble dummy=0;
-
-	return new SeqMat(this->matrix,this->M,this->N,dummy);
-
-}
-/*}}}*/
-/*FUNCTION SeqMat::ToSerial{{{*/
-IssmDouble* SeqMat::ToSerial(void){
-
-	IssmDouble* buffer=NULL;
-
-	if(this->M*this->N){
-		buffer=xNew<IssmDouble>(this->M*this->N);
-		xMemCpy<IssmDouble>(buffer,this->matrix,this->M*this->N);
-	}
-	return buffer;
-
-}
-/*}}}*/
-/*FUNCTION SeqMat::SetValues{{{*/
-void SeqMat::SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode){
-	
-	int i,j;
-	switch(mode){
-		case ADD_VAL:
-			for(i=0;i<m;i++) for(j=0;j<n;j++) this->matrix[N*idxm[i]+idxn[j]]+=values[n*i+j];
-			break;
-		case INS_VAL:
-			for(i=0;i<m;i++) for(j=0;j<n;j++) this->matrix[N*idxm[i]+idxn[j]]=values[n*i+j];
-			break;
-		default:
-			_error2_("unknown insert mode!");
-			break;
-	}
-
-}
-/*}}}*/
-/*FUNCTION SeqMat::Convert{{{*/
-void SeqMat::Convert(MatrixType type){
-
-	/*do nothing*/
-
-}
-/*}}}*/
Index: /issm/trunk/src/c/toolkits/issm/SeqMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/SeqMat.h	(revision 13394)
+++ /issm/trunk/src/c/toolkits/issm/SeqMat.h	(revision 13395)
@@ -1,4 +1,4 @@
 /*!\file:  SeqMat.h
- * \brief wrapper to SeqMat objects, which are just wrappers to a simple IssmDouble* buffer.
+ * \brief wrapper to SeqMat objects, which are just wrappers to a simple IssmDouble or IssmPDouble* buffer.
  */ 
 
@@ -14,9 +14,17 @@
 #endif
 
-#include "../toolkitsenums.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/MemOps/xMemCpy.h"
+#include "../../shared/Alloc/alloc.h"
+#include "../../include/macros.h"
+#include "./SeqVec.h"
 
 /*}}}*/
-class SeqVec;
-
+
+/*We need to template this class, in case we want to create Matrices that hold IssmDouble* matrix or IssmPDouble* matrix. 
+  Such matrices would be useful for use without or with the matlab or python interface (which do not care for IssmDouble types, 
+  but only rely on IssmPDouble types)*/
+
+template <class doubletype> 
 class SeqMat{
 
@@ -24,28 +32,200 @@
 	
 		int M,N; 
-		IssmDouble* matrix; 
-
-		/*SeqMat constructors, destructors {{{*/
-		SeqMat();
-		SeqMat(int M,int N);
-		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 {{{*/
-		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(SeqVec* X,SeqVec* AX);
-		SeqMat* Duplicate(void);
-		IssmDouble* ToSerial(void);
-		void SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode);
-		void Convert(MatrixType type);
-		/*}}}*/
+		doubletype* matrix;  /*here, doubletype is either IssmDouble or IssmPDouble*/
+
+		/*SeqMat constructors, destructors*/
+		/*FUNCTION SeqMat(){{{*/
+		SeqMat(){
+
+			this->M=0;
+			this->N=0;
+			this->matrix=NULL;
+		}
+		/*}}}*/
+		/*FUNCTION SeqMat(int M,int N){{{*/
+		SeqMat(int pM,int pN){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(M*N) this->matrix=xNewZeroInit<doubletype>(pM*pN);
+		}
+		/*}}}*/
+		/*FUNCTION SeqMat(int M,int N, doubletype sparsity){{{*/
+		SeqMat(int pM,int pN, doubletype sparsity){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(M*N) this->matrix=xNewZeroInit<doubletype>(pM*pN);
+		}
+		/*}}}*/
+		/*FUNCTION SeqMat(doubletype* serial_mat,int M,int N,doubletype sparsity){{{*/
+		SeqMat(doubletype* serial_mat,int pM,int pN,doubletype sparsity){
+
+			int i,j;
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(M*N){
+				this->matrix=xNewZeroInit<doubletype>(pM*pN);
+				xMemCpy<doubletype>(this->matrix,serial_mat,pM*pN);
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION SeqMat(int M,int N, int connectivity, int numberofdofspernode){{{*/
+		SeqMat(int pM,int pN, int connectivity,int numberofdofspernode){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(M*N) this->matrix=xNewZeroInit<doubletype>(pM*pN);
+		}
+		/*}}}*/
+		/*FUNCTION ~SeqMat(){{{*/
+		~SeqMat(){
+
+			xDelete<doubletype>(this->matrix);
+			M=0;
+			N=0;
+		}
+		/*}}}*/
+
+		/*SeqMat specific routines */
+		/*FUNCTION Echo{{{*/
+		void Echo(void){
+
+			int i,j;
+			_printLine_("SeqMat size " << this->M << "-" << this->N);
+			for(i=0;i<M;i++){
+				for(j=0;j<N;j++){
+					_printString_(this->matrix[N*i+j] << " ");
+				}
+				_printLine_("");
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Assemble{{{*/
+		void Assemble(void){
+
+			/*do nothing*/
+
+		}
+		/*}}}*/
+		/*FUNCTION Norm{{{*/
+		doubletype Norm(NormMode mode){
+
+			doubletype norm;
+			doubletype absolute;
+			int i,j;
+
+			switch(mode){
+				case NORM_INF:
+					norm=0;
+					for(i=0;i<this->M;i++){
+						absolute=0;
+						for(j=0;j<this->N;j++){
+							absolute+=fabs(this->matrix[N*i+j]);
+						}
+						norm=max(norm,absolute);
+					}
+					return norm;
+					break; 
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		/*FUNCTION GetSize{{{*/
+		void GetSize(int* pM,int* pN){
+
+			*pM=this->M;
+			*pN=this->N;
+
+		}
+		/*}}}*/
+		/*FUNCTION GetLocalSize{{{*/
+		void GetLocalSize(int* pM,int* pN){
+
+			*pM=this->M;
+			*pN=this->N;
+
+		}
+		/*}}}*/
+		/*FUNCTION MatMult{{{*/
+		void MatMult(SeqVec<doubletype>* X,SeqVec<doubletype>* AX){
+
+			int i,j;
+			int XM,AXM;
+			doubletype dummy;
+
+			X->GetSize(&XM);
+			AX->GetSize(&AXM);
+
+			if(M!=AXM)_error_("A and AX should have the same number of rows!");
+			if(N!=XM)_error_("A and X should have the same number of columns!");
+
+			for(i=0;i<M;i++){
+				dummy=0;
+				for(j=0;j<N;j++){
+					dummy+= this->matrix[N*i+j]*X->vector[j];
+				}
+				AX->vector[i]=dummy;
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION Duplicate{{{*/
+		SeqMat* Duplicate(void){
+
+			doubletype dummy=0;
+
+			return new SeqMat(this->matrix,this->M,this->N,dummy);
+
+		}
+		/*}}}*/
+		/*FUNCTION ToSerial{{{*/
+		doubletype* ToSerial(void){
+
+			doubletype* buffer=NULL;
+
+			if(this->M*this->N){
+				buffer=xNew<doubletype>(this->M*this->N);
+				xMemCpy<doubletype>(buffer,this->matrix,this->M*this->N);
+			}
+			return buffer;
+
+		}
+		/*}}}*/
+		/*FUNCTION SetValues{{{*/
+		void SetValues(int m,int* idxm,int n,int* idxn,doubletype* values,InsMode mode){
+
+			int i,j;
+			switch(mode){
+				case ADD_VAL:
+					for(i=0;i<m;i++) for(j=0;j<n;j++) this->matrix[N*idxm[i]+idxn[j]]+=values[n*i+j];
+					break;
+				case INS_VAL:
+					for(i=0;i<m;i++) for(j=0;j<n;j++) this->matrix[N*idxm[i]+idxn[j]]=values[n*i+j];
+					break;
+				default:
+					_error_("unknown insert mode!");
+					break;
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION Convert{{{*/
+		void Convert(MatrixType type){
+
+			/*do nothing*/
+
+		}
+		/*}}}*/		
 
 };
-		
+
 #endif //#ifndef _SEQMAT_H_
Index: sm/trunk/src/c/toolkits/issm/SeqVec.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/issm/SeqVec.cpp	(revision 13394)
+++ 	(revision )
@@ -1,237 +1,0 @@
-/*!\file SeqVec.cpp
- * \brief: implementation of the SeqVec 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 "../toolkits.h"
-#include "../../shared/shared.h"
-
-/*}}}*/
-
-/*SeqVec constructors and destructor*/
-/*FUNCTION SeqVec::SeqVec(){{{*/
-SeqVec::SeqVec(){
-
-	this->M=0;
-	this->vector=NULL;
-}
-/*}}}*/
-/*FUNCTION SeqVec::SeqVec(int M,bool fromlocalsize){{{*/
-SeqVec::SeqVec(int pM,bool fromlocalsize){
-
-	this->M=pM;
-	this->vector=NULL;
-	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;
-
-	this->M=pM;
-	this->vector=NULL;
-	if(this->M){
-		this->vector=xNewZeroInit<IssmDouble>(pM);
-		xMemCpy<IssmDouble>(this->vector,buffer,pM);
-	}
-}
-/*}}}*/
-		/*FUNCTION SeqVec::~SeqVec(){{{*/
-SeqVec::~SeqVec(){
-	xDelete<IssmDouble>(this->vector);
-	M=0;
-}
-/*}}}*/
-
-/*SeqVec specific routines: */
-/*FUNCTION SeqVec::Echo{{{*/
-void SeqVec::Echo(void){
-
-	int i;
-	_printLine_("SeqVec size " << this->M);
-	for(i=0;i<M;i++){
-		_printString_(vector[i] << "\n ");
-	}
-}
-/*}}}*/
-
-/*FUNCTION SeqVec::Assemble{{{*/
-void SeqVec::Assemble(void){
-		
-	/*do nothing*/
-
-}
-/*}}}*/
-/*FUNCTION SeqVec::SetValues{{{*/
-void SeqVec::SetValues(int ssize, int* list, IssmDouble* values, InsMode mode){
-	
-	int i;
-	switch(mode){
-		case ADD_VAL:
-			for(i=0;i<ssize;i++) this->vector[list[i]]+=values[i];
-			break;
-		case INS_VAL:
-			for(i=0;i<ssize;i++) this->vector[list[i]]=values[i];
-			break;
-		default:
-			_error2_("unknown insert mode!");
-			break;
-	}
-
-}
-/*}}}*/
-/*FUNCTION SeqVec::SetValue{{{*/
-void SeqVec::SetValue(int dof, IssmDouble value, InsMode mode){
-
-	switch(mode){
-		case ADD_VAL:
-			this->vector[dof]+=value;
-			break;
-		case INS_VAL:
-			this->vector[dof]=value;
-			break;
-		default:
-			_error2_("unknown insert mode!");
-			break;
-	}
-}
-/*}}}*/
-/*FUNCTION SeqVec::GetValue{{{*/
-void SeqVec::GetValue(IssmDouble* pvalue,int dof){
-
-	*pvalue=this->vector[dof];
-
-}
-/*}}}*/
-		
-/*FUNCTION SeqVec::GetSize{{{*/
-void SeqVec::GetSize(int* pM){
-
-	*pM=this->M;
-
-}
-/*}}}*/
-/*FUNCTION SeqVec::GetLocalSize{{{*/
-void SeqVec::GetLocalSize(int* pM){
-	
-	*pM=this->M;
-
-}
-/*}}}*/
-/*FUNCTION SeqVec::Duplicate{{{*/
-SeqVec* SeqVec::Duplicate(void){
-	
-	return new SeqVec(this->vector,this->M);
-
-}
-/*}}}*/
-/*FUNCTION SeqVec::Set{{{*/
-void SeqVec::Set(IssmDouble value){
-
-	int i;
-	for(i=0;i<this->M;i++)this->vector[i]=value;
-
-}
-/*}}}*/
-/*FUNCTION SeqVec::AXPY{{{*/
-void SeqVec::AXPY(SeqVec* X, IssmDouble a){
-
-	int i;
-
-	/*y=a*x+y where this->vector is y*/
-	for(i=0;i<this->M;i++)this->vector[i]=a*X->vector[i]+this->vector[i];
-	
-}
-/*}}}*/
-/*FUNCTION SeqVec::AYPX{{{*/
-void SeqVec::AYPX(SeqVec* X, IssmDouble a){
-	
-	int i;
-
-	/*y=x+a*y where this->vector is y*/
-	for(i=0;i<this->M;i++)this->vector[i]=X->vector[i]+a*this->vector[i];
-
-}
-/*}}}*/
-/*FUNCTION SeqVec::ToMPISerial{{{*/
-IssmDouble* SeqVec::ToMPISerial(void){
-
-	IssmDouble* buffer=NULL;
-
-	if(this->M){
-		buffer=xNew<IssmDouble>(this->M);
-		xMemCpy<IssmDouble>(buffer,this->vector,this->M);
-	}
-	return buffer;
-
-}
-/*}}}*/
-/*FUNCTION SeqVec::Copy{{{*/
-void SeqVec::Copy(SeqVec* to){
-
-	int i;
-
-	to->M=this->M;
-	for(i=0;i<this->M;i++)to->vector[i]=this->vector[i];
-
-}
-/*}}}*/
-/*FUNCTION SeqVec::Norm{{{*/
-IssmDouble SeqVec::Norm(NormMode mode){
-
-	IssmDouble norm;
-	int i;
-
-	switch(mode){
-		case NORM_INF:
-			norm=0; for(i=0;i<this->M;i++)norm=max(norm,fabs(this->vector[i]));
-			return norm;
-			break;
-		case NORM_TWO:
-			norm=0; 
-			for(i=0;i<this->M;i++)norm+=pow(this->vector[i],2);
-			return sqrt(norm);
-			break;
-		default:
-			_error2_("unknown norm !");
-			break;
-	}
-}
-/*}}}*/
-/*FUNCTION SeqVec::Scale{{{*/
-void SeqVec::Scale(IssmDouble scale_factor){
-
-	int i;
-	for(i=0;i<this->M;i++)this->vector[i]=scale_factor*this->vector[i];
-	
-}
-/*}}}*/
-/*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;
-
-}
-/*}}}*/
-/*FUNCTION SeqVec::PointwiseDivide{{{*/
-void SeqVec::PointwiseDivide(SeqVec* x,SeqVec* y){
-
-	int i;
-	/*pointwise w=x/y where this->vector is w: */
-	for(i=0;i<this->M;i++)this->vector[i]=x->vector[i]/y->vector[i];
-}
-/*}}}*/
Index: /issm/trunk/src/c/toolkits/issm/SeqVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/SeqVec.h	(revision 13394)
+++ /issm/trunk/src/c/toolkits/issm/SeqVec.h	(revision 13395)
@@ -14,41 +14,247 @@
 #endif
 
-#include "../toolkitsenums.h"
+#include "../../shared/Exceptions/exceptions.h"
+#include "../../shared/MemOps/xMemCpy.h"
+#include "../../shared/Alloc/alloc.h"
+#include "../../include/macros.h"
 
 /*}}}*/
 
+/*We need to template this class, in case we want to create vectors that hold IssmDouble* matrix or IssmPDouble* matrix. 
+  Such vectors would be useful for use without or with the matlab or python interface (which do not care for IssmDouble types, 
+  but only rely on IssmPDouble types)*/
+
+template <class doubletype> 
 class SeqVec{
 
 	public:
 	
-		IssmDouble* vector;
+		doubletype* vector;
 		int M;
 
-		/*SeqVec constructors, destructors {{{*/
-		SeqVec();
-		SeqVec(int M,bool fromlocalsize=false);
-		SeqVec(IssmDouble* buffer, int M);
-		~SeqVec();
-		/*}}}*/
-		/*SeqVec 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);
-		SeqVec* Duplicate(void);
-		void Set(IssmDouble value);
-		void AXPY(SeqVec* X, IssmDouble a);
-		void AYPX(SeqVec* X, IssmDouble a);
-		IssmDouble* ToMPISerial(void);
-		void Copy(SeqVec* to);
-		IssmDouble Norm(NormMode norm_type);
-		void Scale(IssmDouble scale_factor);
-		void PointwiseDivide(SeqVec* x,SeqVec* y);
-		IssmDouble Dot(SeqVec* vector);
+		/*SeqVec constructors, destructors*/
+		/*FUNCTION SeqVec(){{{*/
+		SeqVec(){
+
+			this->M=0;
+			this->vector=NULL;
+		}
+		/*}}}*/
+		/*FUNCTION SeqVec(int M){{{*/
+		SeqVec(int pM){
+
+			this->M=pM;
+			this->vector=NULL;
+			if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
+		}
+		/*}}}*/
+		/*FUNCTION SeqVec(int M,bool fromlocalsize){{{*/
+		SeqVec(int pM,bool fromlocalsize){
+
+			this->M=pM;
+			this->vector=NULL;
+			if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
+		}
+		/*}}}*/
+		/*FUNCTION SeqVec(doubletype* serial_vec,int M){{{*/
+		SeqVec(doubletype* buffer,int pM){
+
+			int i,j;
+
+			this->M=pM;
+			this->vector=NULL;
+			if(this->M){
+				this->vector=xNew<doubletype>(pM);
+				xMemCpy<doubletype>(this->vector,buffer,pM);
+			}
+		}
+		/*}}}*/
+		/*FUNCTION ~SeqVec(){{{*/
+		~SeqVec(){
+			xDelete<doubletype>(this->vector);
+			M=0;
+		}
+		/*}}}*/
+
+		/*SeqVec specific routines*/
+		/*FUNCTION Echo{{{*/
+		void Echo(void){
+
+			int i;
+			_printLine_("SeqVec size " << this->M);
+			for(i=0;i<M;i++){
+				_printString_(vector[i] << "\n ");
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Assemble{{{*/
+		void Assemble(void){
+
+			/*do nothing*/
+
+		}
+		/*}}}*/
+		/*FUNCTION SetValues{{{*/
+		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){
+
+			int i;
+			switch(mode){
+				case ADD_VAL:
+					for(i=0;i<ssize;i++) this->vector[list[i]]+=values[i];
+					break;
+				case INS_VAL:
+					for(i=0;i<ssize;i++) this->vector[list[i]]=values[i];
+					break;
+				default:
+					_error_("unknown insert mode!");
+					break;
+			}
+
+		}
+		/*}}}*/
+		/*FUNCTION SetValue{{{*/
+		void SetValue(int dof, doubletype value, InsMode mode){
+
+			switch(mode){
+				case ADD_VAL:
+					this->vector[dof]+=value;
+					break;
+				case INS_VAL:
+					this->vector[dof]=value;
+					break;
+				default:
+					_error_("unknown insert mode!");
+					break;
+			}
+		}
+		/*}}}*/
+		/*FUNCTION GetValue{{{*/
+		void GetValue(doubletype* pvalue,int dof){
+
+			*pvalue=this->vector[dof];
+
+		}
+		/*}}}*/
+		/*FUNCTION GetSize{{{*/
+		void GetSize(int* pM){
+
+			*pM=this->M;
+
+		}
+		/*}}}*/
+		/*FUNCTION GetLocalSize{{{*/
+		void GetLocalSize(int* pM){
+
+			*pM=this->M;
+
+		}
+		/*}}}*/
+		/*FUNCTION Duplicate{{{*/
+		SeqVec* Duplicate(void){
+
+			return new SeqVec(this->vector,this->M);
+
+		}
+		/*}}}*/
+		/*FUNCTION Set{{{*/
+		void Set(doubletype value){
+
+			int i;
+			for(i=0;i<this->M;i++)this->vector[i]=value;
+
+		}
+		/*}}}*/
+		/*FUNCTION AXPY{{{*/
+		void AXPY(SeqVec* X, doubletype a){
+
+			int i;
+
+			/*y=a*x+y where this->vector is y*/
+			for(i=0;i<this->M;i++)this->vector[i]=a*X->vector[i]+this->vector[i];
+
+		}
+		/*}}}*/
+		/*FUNCTION AYPX{{{*/
+		void AYPX(SeqVec* X, doubletype a){
+
+			int i;
+
+			/*y=x+a*y where this->vector is y*/
+			for(i=0;i<this->M;i++)this->vector[i]=X->vector[i]+a*this->vector[i];
+
+		}
+		/*}}}*/
+		/*FUNCTION ToMPISerial{{{*/
+		doubletype* ToMPISerial(void){
+
+			doubletype* buffer=NULL;
+
+			if(this->M){
+				buffer=xNew<doubletype>(this->M);
+				xMemCpy<doubletype>(buffer,this->vector,this->M);
+			}
+			return buffer;
+
+		}
+		/*}}}*/
+		/*FUNCTION Copy{{{*/
+		void Copy(SeqVec* to){
+
+			int i;
+
+			to->M=this->M;
+			for(i=0;i<this->M;i++)to->vector[i]=this->vector[i];
+
+		}
+		/*}}}*/
+		/*FUNCTION Norm{{{*/
+		doubletype Norm(NormMode mode){
+
+			doubletype norm;
+			int i;
+
+			switch(mode){
+				case NORM_INF:
+					norm=0; for(i=0;i<this->M;i++)norm=max(norm,fabs(this->vector[i]));
+					return norm;
+					break;
+				case NORM_TWO:
+					norm=0; 
+					for(i=0;i<this->M;i++)norm+=pow(this->vector[i],2);
+					return sqrt(norm);
+					break;
+				default:
+					_error_("unknown norm !");
+					break;
+			}
+		}
+		/*}}}*/
+		/*FUNCTION Scale{{{*/
+		void Scale(doubletype scale_factor){
+
+			int i;
+			for(i=0;i<this->M;i++)this->vector[i]=scale_factor*this->vector[i];
+
+		}
+		/*}}}*/
+		/*FUNCTION Dot{{{*/
+		doubletype Dot(SeqVec* input){
+
+			int i;
+
+			doubletype dot=0;
+			for(i=0;i<this->M;i++)dot+=this->vector[i]*input->vector[i];
+			return dot;
+
+		}
+		/*}}}*/
+		/*FUNCTION PointwiseDivide{{{*/
+		void PointwiseDivide(SeqVec* x,SeqVec* y){
+
+			int i;
+			/*pointwise w=x/y where this->vector is w: */
+			for(i=0;i<this->M;i++)this->vector[i]=x->vector[i]/y->vector[i];
+		}
 		/*}}}*/
 };
-
 #endif //#ifndef _SEQVEC_H_
Index: /issm/trunk/src/c/toolkits/issm/issmtoolkit.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/issmtoolkit.h	(revision 13394)
+++ /issm/trunk/src/c/toolkits/issm/issmtoolkit.h	(revision 13395)
@@ -6,6 +6,4 @@
 #define _ISSM_TOOLKIT_H_
 
-#include "../../include/include.h"
-
 #include "./SeqMat.h"
 #include "./SeqVec.h"
Index: /issm/trunk/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp	(revision 13394)
+++ /issm/trunk/src/c/toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp	(revision 13395)
@@ -55,6 +55,10 @@
 			NULL, NULL, pnum_procs, tpwgts, options, &objval,epart, npart);
 
+	/*clean-up*/
+	xDelete<idx_t>(eptr);
+	xDelete<real_t>(tpwgts);
+
 	#else
-	_error2_("METIS version not supported yet");
+	_error_("METIS version not supported yet");
 	#endif
 }
Index: /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp	(revision 13395)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp	(revision 13395)
@@ -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/trunk/src/c/toolkits/petsc/objects/PetscMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.h	(revision 13395)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.h	(revision 13395)
@@ -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/trunk/src/c/toolkits/petsc/objects/PetscVec.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscVec.cpp	(revision 13395)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscVec.cpp	(revision 13395)
@@ -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/trunk/src/c/toolkits/petsc/objects/PetscVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscVec.h	(revision 13395)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscVec.h	(revision 13395)
@@ -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/trunk/src/c/toolkits/petsc/objects/petscobjects.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/petscobjects.h	(revision 13395)
+++ /issm/trunk/src/c/toolkits/petsc/objects/petscobjects.h	(revision 13395)
@@ -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/trunk/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp	(revision 13394)
+++ /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp	(revision 13395)
@@ -30,5 +30,5 @@
 			break;
 		default: 
-			_error2_("unknown insert mode!");
+			_error_("unknown insert mode!");
 			break;
 	}
Index: /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 13394)
+++ /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 13395)
@@ -30,5 +30,5 @@
 			break;
 		default: 
-			_error2_("unknown matrix type !");
+			_error_("unknown matrix type !");
 			break;
 	}
Index: /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp	(revision 13394)
+++ /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp	(revision 13395)
@@ -30,5 +30,5 @@
 			break;
 		default: 
-			_error2_("unknown norm !");
+			_error_("unknown norm !");
 			break;
 	}
Index: /issm/trunk/src/c/toolkits/petsc/patches/MatInvert.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/MatInvert.cpp	(revision 13394)
+++ /issm/trunk/src/c/toolkits/petsc/patches/MatInvert.cpp	(revision 13395)
@@ -29,5 +29,5 @@
 	/*Some checks: */
 	MatGetSize(matrix,&M,&N);
-	if(M!=N) _error2_("trying to invert a non square matrix!");
+	if(M!=N) _error_("trying to invert a non square matrix!");
 
 	/*Create identitiy matrix: */
Index: /issm/trunk/src/c/toolkits/petsc/patches/MatPartition.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/MatPartition.cpp	(revision 13394)
+++ /issm/trunk/src/c/toolkits/petsc/patches/MatPartition.cpp	(revision 13395)
@@ -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{
-			_error2_("MatType " << type << " not supported yet");
+			_error_("MatType " << type << " not supported yet");
 		}
 		/*Assemble*/
Index: /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 13394)
+++ /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 13395)
@@ -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
@@ -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); 
Index: /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 13394)
+++ /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 13395)
@@ -55,5 +55,5 @@
 			if(first[0]!='-'){
 				/*This is not good, the option does not have '-'! Get out*/
-				_error2_("Option " << first << " should be preceded by '-'!");
+				_error_("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/trunk/src/c/toolkits/petsc/patches/VecMerge.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 13394)
+++ /issm/trunk/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 13395)
@@ -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) ){
-		_error2_("Dimensions of partitioning vector incompatible with dimensions of input vector\n");
+		_error_("Dimensions of partitioning vector incompatible with dimensions of input vector\n");
 	}
 
Index: /issm/trunk/src/c/toolkits/petsc/petscincludes.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/petscincludes.h	(revision 13394)
+++ /issm/trunk/src/c/toolkits/petsc/petscincludes.h	(revision 13395)
@@ -16,4 +16,5 @@
 /*our own patches: */
 #include "patches/petscpatches.h"
+#include "objects/petscobjects.h"
 
 #endif
Index: /issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 13394)
+++ /issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 13395)
@@ -51,5 +51,5 @@
 
 	/*Some dimensions checks: */
-	if (mA!=nA) _error2_("trying to take the invert of a non-square matrix!");
+	if (mA!=nA) _error_("trying to take the invert of a non-square matrix!");
 
 	/* Set default Plapack parameters */
Index: /issm/trunk/src/m/Makefile.am
===================================================================
--- /issm/trunk/src/m/Makefile.am	(revision 13394)
+++ /issm/trunk/src/m/Makefile.am	(revision 13395)
@@ -1,41 +1,50 @@
-bin_SCRIPTS=./classes/*.m \
-				./classes/model/*.m \
-				./classes/clusters/*.m \
-				./enum/*.m \
-				./kml/*.m \
-				./model/*.m \
-				./model/plot/*.m \
-				./model/mesh/*.m \
-				./model/display/*.m \
-				./model/parameterization/*.m \
-				./model/partition/*.m \
-				./model/solvers/*.m \
-				./planet/*.m \
-				./qmu/*.m \
-				./utils/*.m \
-				./utils/Array/*.m \
-				./utils/BC/*.m \
-				./utils/Basins/*.m \
-				./utils/Cluster/*.m \
-				./utils/DataProcessing/*.m \
-				./utils/Ecco3/*.m \
-				./utils/Exp/*.m \
-				./utils/Exp/manipulation/*.m \
-				./utils/Exp/readwrite/*.m \
-				./utils/Geometry/*.m \
-				./utils/ImageProcessing/*.m \
-				./utils/Interp/*.m \
-				./utils/Kml/*.m \
-				./utils/LatLong/*.m \
-				./utils/Math/*.m \
-				./utils/Meca/*.m \
-				./utils/Mesh/*.m \
-				./utils/Miscellaneous/*.m \
-				./utils/Model/*.m \
-				./utils/Numerics/*.m \
-				./utils/OS/*.m \
-				./utils/Plot/*.m \
-				./utils/Shell/*.m \
-				./utils/String/*.m \
-				./utils/consistency/*.m \
-				./utils/qmu/*.m 
+#To generate list of directories
+#
+#find . -type d -exec ls -d {} \;
+
+bin_SCRIPTS= ./qmu/*.m \
+				 ./qmu/setupdesign/*.m \
+				 ./qmu/plot/*.m \
+				 ./qmu/examples/*.m \
+				 ./kml/*.m \
+				 ./enum/*.m \
+				 ./classes/*.m \
+				 ./classes/qmu/*.m \
+				 ./classes/qmu/@dakota_method/*.m \
+				 ./classes/clusters/*.m \
+				 ./classes/model/*.m \
+				 ./consistency/*.m \
+				 ./array/*.m \
+				 ./boundaryconditions/*.m \
+				 ./exp/*.m \
+				 ./exp/manipulation/*.m \
+				 ./geometry/*.m \
+				 ./interp/*.m \
+				 ./latlong/*.m \
+				 ./mech/*.m \
+				 ./mesh/*.m \
+				 ./mesh/planet/*.m \
+				 ./mesh/rifts/*.m \
+				 ./miscellaneous/*.m \
+				 ./os/*.m \
+				 ./plot/*.m \
+				 ./plot/colormaps/*.m \
+				 ./string/*.m \
+				 ./contrib/massbalance/*.m \
+				 ./contrib/ecco/*.m \
+				 ./contrib/hydrology/*.m \
+				 ./contrib/hack/*.m \
+				 ./contrib/gslib/*.m \
+				 ./contrib/uci/*.m \
+				 ./contrib/oasis/*.m \
+				 ./contrib/bamg/*.m \
+				 ./extrusion/*.m \
+				 ./inversions/*.m \
+				 ./io/*.m \
+				 ./parameterization/*.m \
+				 ./partition/*.m \
+				 ./print/*.m \
+				 ./regional/*.m \
+				 ./solve/*.m \
+				 ./solvers/*.m \
+				 ./materials/*.m
Index: /issm/trunk/src/m/array/allempty.m
===================================================================
--- /issm/trunk/src/m/array/allempty.m	(revision 13395)
+++ /issm/trunk/src/m/array/allempty.m	(revision 13395)
@@ -0,0 +1,22 @@
+%
+%  function to return an empty cell array if all array elements are empty
+%
+%  function [cout]=allempty(cin)
+%
+function [cout]=allempty(cin)
+
+if ~nargin
+    help allempty
+    return
+end
+
+for j=1:numel(cin)
+    if ~isempty(cin{j})
+        cout=cin;
+        return
+    end
+end
+cout={};
+
+end
+
Index: /issm/trunk/src/m/array/allequal.m
===================================================================
--- /issm/trunk/src/m/array/allequal.m	(revision 13395)
+++ /issm/trunk/src/m/array/allequal.m	(revision 13395)
@@ -0,0 +1,70 @@
+%
+%  function to return an empty array if all array elements are
+%  equal to the given value, which may also be empty but not nan.
+%
+%  (note that by definition, nan is not equal to nan.  this could
+%  be changed by using isequalwithequalnans.)
+%
+%  function [aout]=allequal(ain,aval)
+%
+function [aout]=allequal(ain,aval)
+
+if ~nargin
+    help allequal
+    return
+end
+
+aout=ain;
+
+if     islogical(ain) && islogical(aval)
+    for i=1:numel(ain)
+        if ~isequal(ain(i),aval)
+            return
+        end
+    end
+    aout=logical([]);
+
+elseif isnumeric(ain) && isnumeric(aval)
+    for i=1:numel(ain)
+        if ~isequal(ain(i),aval)
+            return
+        end
+    end
+    aout=[];
+
+elseif ischar(ain) && ischar(aval)
+    for i=1:size(ain,1)
+        if ~strcmp(ain(i,:),aval)
+            return
+        end
+    end
+    aout='';
+
+elseif iscell(ain)
+    if     islogical(aval)
+        for i=1:numel(ain)
+            if ~islogical(ain{i}) || ~isequal(ain{i},aval)
+                return
+            end
+        end
+        aout={};
+
+    elseif isnumeric(aval)
+        for i=1:numel(ain)
+            if ~isnumeric(ain{i}) || ~isequal(ain{i},aval)
+                return
+            end
+        end
+        aout={};
+
+    elseif ischar(aval)
+        for i=1:size(ain,1)
+            if ~ischar(ain{i}) || ~strcmp(ain{i},aval)
+                return
+            end
+        end
+        aout={};
+    end
+end
+
+end
Index: /issm/trunk/src/m/array/allnan.m
===================================================================
--- /issm/trunk/src/m/array/allnan.m	(revision 13395)
+++ /issm/trunk/src/m/array/allnan.m	(revision 13395)
@@ -0,0 +1,22 @@
+%
+%  function to return an empty double array if all array elements are NaN
+%
+%  function [dout]=allnan(din)
+%
+function [dout]=allnan(din)
+
+if ~nargin
+    help allnan
+    return
+end
+
+for i=1:numel(din)
+    if ~isnan(din(i))
+        dout=din;
+        return
+    end
+end
+dout=[];
+
+end
+
Index: /issm/trunk/src/m/array/any2str.m
===================================================================
--- /issm/trunk/src/m/array/any2str.m	(revision 13395)
+++ /issm/trunk/src/m/array/any2str.m	(revision 13395)
@@ -0,0 +1,22 @@
+%
+%  function to convert anything to a string
+%
+%  function [svec]=any2str(a,alim)
+%
+function [svec]=any2str(a,alim)
+
+if ~exist('alim','var') || (numel(a) <= alim)
+    if iscell(a)
+        svec=string_cell(a);
+    else
+        if (numel(a) > 1) && ~ischar(a)
+            svec=string_vec(a);
+        else
+            svec=item2str(a);
+        end
+    end
+else
+	svec=[string_size(a) ' ''' class(a) ''''];
+end
+
+end
Index: /issm/trunk/src/m/array/array_numel.m
===================================================================
--- /issm/trunk/src/m/array/array_numel.m	(revision 13395)
+++ /issm/trunk/src/m/array/array_numel.m	(revision 13395)
@@ -0,0 +1,35 @@
+%
+%  function to find a number of elements from a list of arrays.
+%  
+%  [asize]=array_numel(varargin)
+%
+%  see array_size to check the number and shape of elements, if
+%  multiple indices will be used.
+%
+function [anum]=array_numel(varargin)
+
+anum=1;
+
+for iarg=1:nargin
+    if ischar(varargin{iarg})
+        inum=numel(cellstr(varargin{iarg}));
+    else
+        inum=numel(varargin{iarg});
+    end
+    
+    if ~isequal(inum,1)
+        if isequal(anum,1)
+            anum=inum;
+        else
+            if ~isequal(inum,anum)
+                if ~isempty(inputname(iarg))
+                    error('Array ''%s'' has inconsistent number of elements.',inputname(iarg));
+                else
+                    error('Array %d has inconsistent number of elements.',iarg);
+                end
+            end
+        end
+    end
+end
+
+end
Index: /issm/trunk/src/m/array/array_size.m
===================================================================
--- /issm/trunk/src/m/array/array_size.m	(revision 13395)
+++ /issm/trunk/src/m/array/array_size.m	(revision 13395)
@@ -0,0 +1,35 @@
+%
+%  function to find an array size from a list of arrays.
+%  
+%  [asize]=array_size(varargin)
+%
+%  see array_numel to check only the number of elements, if
+%  single indices will be used.
+%
+function [asize]=array_size(varargin)
+
+asize=[1 1];
+
+for iarg=1:nargin
+    if ischar(varargin{iarg})
+        isize=size(cellstr(varargin{iarg}));
+    else
+        isize=size(varargin{iarg});
+    end
+    
+    if ~isequal(isize,[1 1])
+        if isequal(asize,[1 1])
+            asize=isize;
+        else
+            if ~isequal(isize,asize)
+                if ~isempty(inputname(iarg))
+                    error('Array ''%s'' has inconsistent size.',inputname(iarg));
+                else
+                    error('Array %d has inconsistent size.',iarg);
+                end
+            end
+        end
+    end
+end
+
+end
Index: /issm/trunk/src/m/array/find_string.m
===================================================================
--- /issm/trunk/src/m/array/find_string.m	(revision 13395)
+++ /issm/trunk/src/m/array/find_string.m	(revision 13395)
@@ -0,0 +1,18 @@
+%
+%  function to find a string in a cell array
+%  (could probably be replaced by matlab strmatch)
+%  
+%  [ifound]=find_string(cells,str)
+%
+function [ifound]=find_string(cells,str)
+
+ifound=false;
+
+for i=1:numel(cells)
+    if ischar(cells{i}) && strcmp(cells{i},str)
+        ifound=i;
+        return
+    end
+end
+
+end
Index: /issm/trunk/src/m/array/item2str.m
===================================================================
--- /issm/trunk/src/m/array/item2str.m	(revision 13395)
+++ /issm/trunk/src/m/array/item2str.m	(revision 13395)
@@ -0,0 +1,31 @@
+%
+%  function to convert an item to a string
+%
+%  function [svec]=item2str(a)
+%
+function [svec]=item2str(a)
+
+if     islogical(a)
+    if a
+        svec='true';
+    else
+        svec='false';
+    end
+elseif ischar(a)
+    svec=['''' a ''''];
+elseif isnumeric(a)
+    svec=num2str(a);
+else
+    if ~isempty(inputname(1))
+        warning('item2str:item_unrecog',...
+            'Item ''%s'' is of unrecognized type ''%s''.',...
+            inputname(1),class(a));
+    else
+        warning('item2str:item_unrecog',...
+            'Item %d is of unrecognized type ''%s''.',...
+            1,class(a));
+    end
+    return
+end
+
+end
Index: /issm/trunk/src/m/array/rotateticklabel.m
===================================================================
--- /issm/trunk/src/m/array/rotateticklabel.m	(revision 13395)
+++ /issm/trunk/src/m/array/rotateticklabel.m	(revision 13395)
@@ -0,0 +1,69 @@
+function th=rotateticklabel(h,rot,demo)
+%ROTATETICKLABEL rotates tick labels
+%   TH=ROTATETICKLABEL(H,ROT) is the calling form where H is a handle to
+%   the axis that contains the XTickLabels that are to be rotated. ROT is
+%   an optional parameter that specifies the angle of rotation. The default
+%   angle is 90. TH is a handle to the text objects created. For long
+%   strings such as those produced by datetick, you may have to adjust the
+%   position of the axes so the labels don't get cut off.
+%
+%   Of course, GCA can be substituted for H if desired.
+%
+%   TH=ROTATETICKLABEL([],[],'demo') shows a demo figure.
+%
+%   Known deficiencies: if tick labels are raised to a power, the power
+%   will be lost after rotation.
+%
+%   See also datetick.
+
+%   Written Oct 14, 2005 by Andy Bliss
+%   Copyright 2005 by Andy Bliss
+
+%DEMO:
+if nargin==3
+    x=[now-.7 now-.3 now];
+    y=[20 35 15];
+    figure
+    plot(x,y,'.-')
+    datetick('x',0,'keepticks')
+    h=gca;
+    set(h,'position',[0.13 0.35 0.775 0.55])
+    rot=90;
+end
+
+%set the default rotation if user doesn't specify
+if nargin==1
+    rot=90;
+end
+%make sure the rotation is in the range 0:360 (brute force method)
+while rot>360
+    rot=rot-360;
+end
+while rot<0
+    rot=rot+360;
+end
+%get current tick labels
+a=get(h,'XTickLabel');
+%erase current tick labels from figure
+set(h,'XTickLabel',[]);
+%get tick label positions
+b=get(h,'XTick');
+c=get(h,'YTick');
+%make new tick labels
+%  must consider yscale (jes, 9/14/10)
+switch lower(get(h,'YScale'))
+    case 'linear'
+        if rot<180
+            th=text(b,repmat(c(1)-.1*(c(2)-c(1)),length(b),1),a,'HorizontalAlignment','right','rotation',rot,'Interpreter','none');
+        else
+            th=text(b,repmat(c(1)-.1*(c(2)-c(1)),length(b),1),a,'HorizontalAlignment','left','rotation',rot,'Interpreter','none');
+        end
+    case 'log'
+        if rot<180
+            th=text(b,repmat(10^(log10(c(1))-.1*(log10(c(2))-log10(c(1)))),length(b),1),a,'HorizontalAlignment','right','rotation',rot,'Interpreter','none');
+        else
+            th=text(b,repmat(10^(log10(c(1))-.1*(log10(c(2))-log10(c(1)))),length(b),1),a,'HorizontalAlignment','left','rotation',rot,'Interpreter','none');
+        end
+    otherwise
+        set(h,'XTickLabel',a);
+end
Index: /issm/trunk/src/m/array/str2int.m
===================================================================
--- /issm/trunk/src/m/array/str2int.m	(revision 13395)
+++ /issm/trunk/src/m/array/str2int.m	(revision 13395)
@@ -0,0 +1,46 @@
+%
+%  function to find and read the first or last positive integer
+%  in a character string.
+%
+%  function [aint]=str2int(astr,cfl)
+%
+function [aint]=str2int(astr,cfl);
+
+aint=[];
+
+if     ~exist('cfl','var') || strncmpi(cfl,'f',1)
+    i=1;
+
+    while (i <= length(astr))
+        if (astr(i) >= '0' && astr(i) <= '9')
+            aint=sscanf(astr(i:length(astr)),'%d',[1,1]);
+            return
+        else
+            i=i+1;
+        end
+	end
+
+elseif strncmpi(cfl,'l',1)
+    i=length(astr);
+    ifound=false;
+
+    while (i >= 1)
+        if     (astr(i) >= '0' && astr(i) <= '9')
+            ifound=true;
+            i=i-1;
+        elseif ~ifound
+            i=i-1;
+        else
+            aint=sscanf(astr(i+1:length(astr)),'%d',[1,1]);
+            return
+        end
+	end
+
+    if ifound
+        aint=sscanf(astr,'%d',[1,1]);
+        return
+    end
+end
+
+end
+
Index: /issm/trunk/src/m/array/string_cell.m
===================================================================
--- /issm/trunk/src/m/array/string_cell.m	(revision 13395)
+++ /issm/trunk/src/m/array/string_cell.m	(revision 13395)
@@ -0,0 +1,26 @@
+%
+%  function to return the string of a cell array
+%
+%  function [svec]=string_cell(a)
+%
+function [svec]=string_cell(a)
+
+if ~nargin
+    help string_cell
+    return
+end
+
+if (numel(a) == 0)
+    svec='{}';
+    return
+end
+
+%  assemble string for output
+
+svec ='{';
+for i=1:numel(a)-1;
+    svec=[svec item2str(a{i}) ' '];
+end
+svec=[svec item2str(a{end}) '}'];
+
+end
Index: /issm/trunk/src/m/array/string_dim.m
===================================================================
--- /issm/trunk/src/m/array/string_dim.m	(revision 13395)
+++ /issm/trunk/src/m/array/string_dim.m	(revision 13395)
@@ -0,0 +1,72 @@
+%
+%  function to return the string dimension of an array element
+%
+%  function [sdim]=string_dim(a,idim,varargin)
+%
+function [sdim]=string_dim(a,idim,varargin)
+
+if ~nargin
+    help string_dim
+    return
+end
+
+%  check for scalar
+
+if (numel(a) == 1) && (idim == 1)
+    sdim='';
+    return
+end
+
+%  check for overflow
+
+if (idim > numel(a))
+    if ~isempty(inputname(1))
+        error('Index %d exceeds number of elements in array ''%s''.',...
+            idim,inputname(1));
+    else
+        error('Index %d exceeds number of elements in array %d.',...
+            idim,1);
+    end
+end
+
+%  check for column or row vector (Matlab uses a minimum of two
+%  dimensions, so this won't match Matlab standard output)
+
+for iarg=1:nargin-2
+    if strcmpi(varargin{iarg},'vector')
+        if (ndims(a) == 2) && ((size(a,1) == 1) || (size(a,2) == 1))
+            sdim =['(' num2str(idim) ')'];
+            return
+        end
+    end
+end
+
+%  do the general case
+
+asize=size(a);
+index=zeros(size(asize));
+aprod=prod(asize);
+idim =idim-1;
+
+%  calculate indices base 0 and convert to base 1
+
+%  note that ind2sub might be useful, except that it requires a list
+%  of scalars rather than a vector for output.
+
+for i=length(asize):-1:1
+    aprod=aprod/asize(i);
+    index(i)=floor(idim/aprod);
+    idim=idim-index(i)*aprod;
+end
+index=index+1;
+
+%  assemble string for output
+
+sdim ='(';
+for i=1:length(asize)-1;
+    sdim =[sdim num2str(index(i)) ','];
+end
+sdim =[sdim num2str(index(end)) ')'];
+
+end
+
Index: /issm/trunk/src/m/array/string_size.m
===================================================================
--- /issm/trunk/src/m/array/string_size.m	(revision 13395)
+++ /issm/trunk/src/m/array/string_size.m	(revision 13395)
@@ -0,0 +1,38 @@
+%
+%  function to return the string size of an array
+%
+%  function [ssize]=string_size(a,varargin)
+%
+function [ssize]=string_size(a,varargin)
+
+if ~nargin
+    help string_size
+    return
+end
+
+%  check for column or row vector (Matlab uses a minimum of two
+%  dimensions, so this won't match Matlab standard output)
+
+for iarg=1:nargin-1
+    if strcmpi(varargin{iarg},'vector')
+        if (ndims(a) == 2) && ((size(a,1) == 1) || (size(a,2) == 1))
+            ssize =['(' num2str(numel(a)) ')'];
+            return
+        end
+    end
+end
+
+%  do the general case
+
+asize=size(a);
+
+%  assemble string for output
+
+ssize ='(';
+for i=1:length(asize)-1;
+    ssize =[ssize num2str(asize(i)) 'x'];
+end
+ssize =[ssize num2str(asize(end)) ')'];
+
+end
+
Index: /issm/trunk/src/m/array/string_vec.m
===================================================================
--- /issm/trunk/src/m/array/string_vec.m	(revision 13395)
+++ /issm/trunk/src/m/array/string_vec.m	(revision 13395)
@@ -0,0 +1,26 @@
+%
+%  function to return the string of an vector
+%
+%  function [svec]=string_vec(a)
+%
+function [svec]=string_vec(a)
+
+if ~nargin
+    help string_vec
+    return
+end
+
+if (numel(a) == 0)
+    svec='[]';
+    return
+end
+
+%  assemble string for output
+
+svec ='[';
+for i=1:numel(a)-1;
+    svec=[svec item2str(a(i)) ' '];
+end
+svec=[svec item2str(a(end)) ']'];
+
+end
Index: /issm/trunk/src/m/array/struc_class.m
===================================================================
--- /issm/trunk/src/m/array/struc_class.m	(revision 13395)
+++ /issm/trunk/src/m/array/struc_class.m	(revision 13395)
@@ -0,0 +1,30 @@
+%
+%  function to find the structural fields of a specified class
+%  
+%  [sclasso]=struc_class(sclass,cstr)
+%
+function [sclasso]=struc_class(sclass,cstr)
+
+%  collect only the objects of the appropriate class
+
+if     isa(sclass,cstr)
+    if ~isempty(inputname(1))
+        sclasso.(inputname(1))=sclass;
+    else
+        sclasso.(cstr)        =sclass;
+    end
+
+elseif isstruct(sclass)
+    fnames=fieldnames(sclass);
+    for i=1:numel(fnames)
+        if isa(sclass.(fnames{i}),cstr)
+            sclasso.(fnames{i})=sclass.(fnames{i});
+        end
+    end
+end
+
+if ~exist('sclasso','var')
+    sclasso=struct([]);
+end
+
+end
Index: /issm/trunk/src/m/array/struc_desc.m
===================================================================
--- /issm/trunk/src/m/array/struc_desc.m	(revision 13395)
+++ /issm/trunk/src/m/array/struc_desc.m	(revision 13395)
@@ -0,0 +1,61 @@
+%
+%  function to find the structures with the specified descriptors
+%  
+%  [sarrayo]=struc_desc(sarray,varargin)
+%
+function [sarrayo]=struc_desc(sarray,varargin)
+
+if ~isfield(sarray,'descriptor')
+    if ~isempty(inputname(1))
+        error('Field ''descriptor'' not found in array ''%s''.',inputname(1));
+    else
+        error('Field ''descriptor'' not found in array %d.',1);
+    end
+end
+
+sarrayo=struct([]);
+
+for iarg=1:nargin-1
+    if     iscell(varargin{iarg})
+        desc=        varargin{iarg};
+    elseif ischar(varargin{iarg})
+        desc=cellstr(varargin{iarg});
+    end
+    
+    for i=1:length(desc)
+        sarrayoi=struc_desci(sarray,desc{i});
+        if ~isempty(sarrayoi)
+            if isempty(sarrayo)
+                sarrayo       =sarrayoi;
+            else
+                sarrayo(end+1)=sarrayoi;
+            end
+        end
+    end
+end
+
+%  if nothing found, return whole array
+
+if isempty(sarrayo)
+    sarrayo=sarray;
+end
+
+end
+
+%
+%  function to find the structure with the specified descriptor
+%  
+function [sarrayo]=struc_desci(sarray,str)
+
+sarrayo=struct([]);
+
+for i=1:numel(sarray)
+    if strcmp(sarray(i).descriptor,str)
+        sarrayo=sarray(i);
+        return
+    end
+end
+
+warning(['String ''' str ''' not found in array ''' inputname(1) '''.']);
+
+end
Index: /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m	(revision 13395)
+++ /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m	(revision 13395)
@@ -0,0 +1,64 @@
+function md=SetIceSheetBC(md)
+%SETICESHEETBC - Create the boundary conditions for diagnostic and thermal models for an IceSheet with no Ice Front
+%
+%   Usage:
+%      md=SetIceSheetBC(md)
+%
+%   See also: SETICESHELFBC, SETMARINEICESHEETBC
+
+%node on Dirichlet
+pos=find(md.mesh.vertexonboundary);
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
+md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+
+%Dirichlet Values
+if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
+	disp('      boundary conditions for diagnostic model: spc set as observed velocities');
+	md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos);
+else
+	disp('      boundary conditions for diagnostic model: spc set as zero');
+end
+
+%segment on neumann (Ice Front) -> none
+if (md.mesh.dimension==2)
+	md.diagnostic.icefront=zeros(0,4);
+else
+	md.diagnostic.icefront=zeros(0,6);
+end
+
+%Create zeros basal melting rate and surface mass balance if not specified
+if (isnan(md.surfaceforcings.precipitation) & (md.surfaceforcings.ispdd==1)),
+	md.surfaceforcings.precipitation=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.precipitation specified: values set as zero');
+end
+if (isnan(md.surfaceforcings.mass_balance) & (md.surfaceforcings.ispdd==0)),
+	md.surfaceforcings.mass_balance=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.mass_balance specified: values set as zero');
+end
+if isnan(md.basalforcings.melting_rate),
+	md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no basalforcings.melting_rate specified: values set as zero');
+end
+if isnan(md.balancethickness.thickening_rate),
+	md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no balancethickness.thickening_rate specified: values set as zero');
+end
+
+md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+
+if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
+		md.basalforcings.geothermalflux=50*10^-3*ones(md.mesh.numberofvertices,1); %50 mW/m^2
+	end
+else
+	disp('      no thermal boundary conditions created: no observed temperature found');
+end
Index: /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.m	(revision 13395)
+++ /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.m	(revision 13395)
@@ -0,0 +1,95 @@
+function md=SetIceShelfBC(md,varargin)
+%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 nargin==2,
+	icefrontfile=varargin{1};
+	if ~exist(icefrontfile), error(['SetIceShelfBC error message: ice front file ' icefrontfile ' not found']); end
+	nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2);
+	nodeonicefront=double(md.mesh.vertexonboundary & nodeinsideicefront);
+elseif nargin==1,
+	nodeonicefront=zeros(md.mesh.numberofvertices,1);
+else
+	help SetIceShelfBC
+	error('bad usage');
+end
+pos=find(md.mesh.vertexonboundary & ~nodeonicefront);
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
+md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+
+%Dirichlet Values
+if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
+	disp('      boundary conditions for diagnostic model: spc set as observed velocities');
+	md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos);
+else
+	disp('      boundary conditions for diagnostic model: spc set as zero');
+end
+
+%segment on Ice Front
+%segment on Neumann (Ice Front)
+pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2)));
+if (md.mesh.dimension==2)
+	pressureload=md.mesh.segments(pos,:);
+elseif md.mesh.dimension==3
+	pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
+	pressureload=[];
+	for i=1:md.mesh.numberoflayers-1,
+		pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
+	end
+end
+
+%Add water or air enum depending on the element
+pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))];
+
+%plug onto model
+md.diagnostic.icefront=pressureload;
+
+%Create zeros basalforcings and surfaceforcings
+if (isnan(md.surfaceforcings.precipitation) & (md.surfaceforcings.ispdd==1)),
+	md.surfaceforcings.precipitation=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.precipitation specified: values set as zero');
+end
+if (isnan(md.surfaceforcings.mass_balance) & (md.surfaceforcings.ispdd==0)),
+	        md.surfaceforcings.mass_balance=zeros(md.mesh.numberofvertices,1);
+		disp('      no surfaceforcings.mass_balance specified: values set as zero');
+end
+if isnan(md.basalforcings.melting_rate),
+	md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no basalforcings.melting_rate specified: values set as zero');
+end
+if isnan(md.balancethickness.thickening_rate),
+	md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no balancethickness.thickening_rate specified: values set as zero');
+end
+
+md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+
+if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
+		md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
+	end
+else
+	disp('      no thermal boundary conditions created: no observed temperature found');
+end
Index: /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py	(revision 13395)
+++ /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py	(revision 13395)
@@ -0,0 +1,98 @@
+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
+	"""
+
+	#node on Dirichlet (boundary and ~icefront)
+	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:
+		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 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'
+
+	#segment on Ice Front
+	#segment on Neumann (Ice Front)
+#	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_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=numpy.concatenate((pressureload,1*md.mask.elementonfloatingice[pressureload[:,-1].astype('int')-1].reshape((-1,1))),axis=1)
+
+	#plug onto model
+	md.diagnostic.icefront=pressureload
+
+	#Create zeros basalforcings and surfaceforcings
+	if numpy.all(numpy.isnan(md.surfaceforcings.precipitation)) and (md.surfaceforcings.ispdd==1):
+		md.surfaceforcings.precipitation=numpy.zeros(md.mesh.numberofvertices)
+		print '      no surfaceforcings.precipitation specified: values set as zero'
+	if numpy.all(numpy.isnan(md.surfaceforcings.mass_balance)) and (md.surfaceforcings.ispdd==0):
+		md.surfaceforcings.mass_balance=numpy.zeros(md.mesh.numberofvertices)
+		print '      no surfaceforcings.mass_balance specified: values set as zero'
+	if numpy.all(numpy.isnan(md.basalforcings.melting_rate)):
+		md.basalforcings.melting_rate=numpy.zeros(md.mesh.numberofvertices)
+		print '      no basalforcings.melting_rate specified: values set as zero'
+	if numpy.all(numpy.isnan(md.balancethickness.thickening_rate)):
+		md.balancethickness.thickening_rate=numpy.zeros(md.mesh.numberofvertices)
+		print '      no balancethickness.thickening_rate specified: values set as zero'
+
+	md.prognostic.spcthickness=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+	md.balancethickness.spcthickness=float('NaN')*numpy.ones(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/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 13395)
+++ /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 13395)
@@ -0,0 +1,107 @@
+function md=SetMarineIceSheetBC(md,varargin)
+%SETICEMARINESHEETBC - Create the boundary conditions for diagnostic and thermal models for a  Marine Ice Sheet with Ice Front
+%
+%   Neumann BC are used on the ice front (an ARGUS contour around the ice front
+%   can be given in input, or it will be deduced as onfloatingice & onboundary)
+%   Dirichlet BC are used elsewhere for diagnostic
+%
+%   Usage:
+%      md=SetMarineIceSheetBC(md,icefrontfile)
+%      md=SetMarineIceSheetBC(md)
+%
+%   Example:
+%      md=SetMarineIceSheetBC(md,'Front.exp')
+%      md=SetMarineIceSheetBC(md)
+%
+%   See also: SETICESHELFBC, SETMARINEICESHEETBC
+
+%node on Dirichlet (boundary and ~icefront)
+if nargin==2,
+	%User provided Front.exp, use it
+	icefrontfile=varargin{1};
+	if ~exist(icefrontfile)
+		error(['SetMarineIceSheetBC error message: ice front file ' icefrontfile ' not found']);
+	end
+	nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2);
+	vertexonicefront=double(md.mesh.vertexonboundary & nodeinsideicefront);
+else
+	%Guess where the ice front is
+	vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
+	vertexonfloatingice(md.mesh.elements(find(md.mask.elementonfloatingice),:))=1;
+	vertexonicefront=double(md.mesh.vertexonboundary & vertexonfloatingice);
+end
+pos=find(md.mesh.vertexonboundary & ~vertexonicefront);
+if isempty(pos),
+	warning('SetMarineIceSheetBC warning: ice front all around the glacier, no dirichlet found. Dirichlet must be added manually')
+end
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+md.diagnostic.spcvx(pos)=0;
+md.diagnostic.spcvy(pos)=0;
+md.diagnostic.spcvz(pos)=0;
+md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+
+%Dirichlet Values
+if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
+	disp('      boundary conditions for diagnostic model: spc set as observed velocities');
+	md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos);
+else
+	disp('      boundary conditions for diagnostic model: spc set as zero');
+end
+
+md.hydrology.spcwatercolumn=zeros(md.mesh.numberofvertices,2);
+pos=find(md.mesh.vertexonboundary); 
+md.hydrology.spcwatercolumn(pos,1)=1;
+
+%segment on Neumann (Ice Front)
+pos=find(vertexonicefront(md.mesh.segments(:,1)) | vertexonicefront(md.mesh.segments(:,2)));
+if (md.mesh.dimension==2)
+	pressureload=md.mesh.segments(pos,:);
+elseif md.mesh.dimension==3
+	pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
+	pressureload=[];
+	for i=1:md.mesh.numberoflayers-1,
+		pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
+	end
+end
+
+%Add water or air enum depending on the element
+pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))+ 0*md.mask.elementongroundedice(pressureload(:,end))];
+
+%plug onto model
+md.diagnostic.icefront=pressureload;
+
+
+%Create zeros basalforcings and surfaceforcings
+if (isnan(md.surfaceforcings.precipitation) & (md.surfaceforcings.ispdd==1)),
+	md.surfaceforcings.precipitation=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.precipitation specified: values set as zero');
+end
+if (isnan(md.surfaceforcings.mass_balance) & (md.surfaceforcings.ispdd==0)),
+	md.surfaceforcings.mass_balance=zeros(md.mesh.numberofvertices,1);
+	disp('      no surfaceforcings.mass_balance specified: values set as zero');
+end
+if isnan(md.basalforcings.melting_rate),
+	md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no basalforcings.melting_rate specified: values set as zero');
+end
+if isnan(md.balancethickness.thickening_rate),
+	md.balancethickness.thickening_rate=zeros(md.mesh.numberofvertices,1);
+	disp('      no balancethickness.thickening_rate specified: values set as zero');
+end
+
+md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+
+if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+	md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
+		md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
+		md.basalforcings.geothermalflux(find(md.mask.vertexongroundedice))=50*10^-3; %50mW/m2
+	end
+else
+	disp('      no thermal boundary conditions created: no observed temperature found');
+end
Index: /issm/trunk/src/m/classes/autodiff.m
===================================================================
--- /issm/trunk/src/m/classes/autodiff.m	(revision 13394)
+++ /issm/trunk/src/m/classes/autodiff.m	(revision 13395)
@@ -6,7 +6,7 @@
 classdef autodiff
 	properties (SetAccess=public) 
-		isautodiff = false;
-		forward    = true;
-		reverse    = false;
+		isautodiff   = false;
+		dependents   = {};
+		independents = {};
 	end
 	methods
@@ -24,17 +24,45 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
+		%Early return 
+		if ~obj.isautodiff, return; end
+
 		end % }}}
 		function disp(obj) % {{{
 			disp(sprintf('   automatic differentiation parameters:'));
-
 			fielddisplay(obj,'isautodiff','indicates if the automatic differentiation is activated');
-			fielddisplay(obj,'forward','forward differentiation');
-			fielddisplay(obj,'reverse','backward differentiation');
-
+			fielddisplay(obj,'dependents','list of dependent variables ; ex: {''Thickness'',''FrictionCoefficient''}');
+			fielddisplay(obj,'independents','list of independent variables ; ex: {''IceVolume'',''MassFlux''}');
 		end % }}}
 		function marshall(obj,fid) % {{{
+
 			WriteData(fid,'object',obj,'fieldname','isautodiff','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','forward','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','reverse','format','Boolean');
+			
+			%early return
+			if ~obj.isautodiff, return; end
+
+			%process dependent variables
+			num_dependents=numel(obj.dependents);
+			WriteData(fid,'data',num_dependents,'enum',AutodiffNumDependentsEnum(),'format','Integer');
+			
+			if(num_dependents),
+				data=zeros(1,num_dependents);
+				for i=1:num_dependents,
+					data(i)=StringToEnum(obj.dependents{i});
+				end
+				WriteData(fid,'data',data,'enum',AutodiffDependentsEnum(),'format','DoubleMat','mattype',3);
+			end
+			
+			%process independent variables
+			num_independents=numel(obj.independents);
+			WriteData(fid,'data',num_independents,'enum',AutodiffNumIndependentsEnum(),'format','Integer');
+			
+			if(num_independents)
+				data=zeros(1,num_independents);
+				for i=1:num_independents,
+					data(i)=StringToEnum(obj.independents{i});
+				end
+				WriteData(fid,'data',data,'enum',AutodiffIndependentsEnum(),'format','DoubleMat','mattype',3);
+			end
+
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/autodiff.py
===================================================================
--- /issm/trunk/src/m/classes/autodiff.py	(revision 13394)
+++ /issm/trunk/src/m/classes/autodiff.py	(revision 13395)
@@ -1,12 +1,20 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class autodiff:
+class autodiff(object):
+	"""
+	AUTODIFF class definition
+
+	   Usage:
+	      autodiff=autodiff();
+	"""
+
 	#properties
 	def __init__(self):
 		# {{{ Properties
 		self.isautodiff = False
-		self.forward    = True
-		self.reverse    = False
 
 		#set defaults
@@ -14,15 +22,21 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   automatic differentiation parameters:'
-		string="%s\n%s"%(string,fielddisplay(obj,'isautodiff','indicates if the automatic differentiation is activated'))
-		string="%s\n%s"%(string,fielddisplay(obj,'forward','forward differentiation'))
-		string="%s\n%s"%(string,fielddisplay(obj,'reverse','backward differentiation'))
+		string="%s\n%s"%(string,fielddisplay(self,'isautodiff','indicates if the automatic differentiation is activated'))
 		return string
 		#}}}
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','isautodiff','format','Boolean')
+	# }}}
+
Index: /issm/trunk/src/m/classes/balancethickness.m
===================================================================
--- /issm/trunk/src/m/classes/balancethickness.m	(revision 13394)
+++ /issm/trunk/src/m/classes/balancethickness.m	(revision 13395)
@@ -27,5 +27,5 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 			%Early return
-			if solution~=BalancethicknessSolutionEnum, return; end
+			if solution~=BalancethicknessSolutionEnum(), return; end
 
 			md = checkfield(md,'balancethickness.spcthickness','forcing',1);
Index: /issm/trunk/src/m/classes/balancethickness.py
===================================================================
--- /issm/trunk/src/m/classes/balancethickness.py	(revision 13394)
+++ /issm/trunk/src/m/classes/balancethickness.py	(revision 13395)
@@ -1,11 +1,22 @@
 #module imports
 from fielddisplay import fielddisplay
-class balancethickness:
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
+
+class balancethickness(object):
+	"""
+	BALANCETHICKNESS class definition
+
+	   Usage:
+	      balancethickness=balancethickness();
+	"""
+
 	#properties
 	def __init__(self):
 		# {{{ Properties
-		self.spcthickness = float('NaN')
-		self.thickening_rate           = float('NaN')
-		self.stabilization           = 0
+		self.spcthickness      = float('NaN')
+		self.thickening_rate   = float('NaN')
+		self.stabilization     = 0
 
 		#set defaults
@@ -13,21 +24,39 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		
 		string='   balance thickness solution parameters:' 
 		
-		string="%s\n\n%s"%(string,fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'thickening_rate','ice thickening rate used in the mass conservation (dh/dt)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'stabilization','0: None, 1: SU, 2: MacAyeal''s artificial diffusivity, 3:DG'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'thickening_rate','ice thickening rate used in the mass conservation (dh/dt)'))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization',"0: None, 1: SU, 2: MacAyeal's artificial diffusivity, 3:DG"))
 		return string
 		#}}}
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#Type of stabilization used
-		obj.stabilization=1
+		self.stabilization=1
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		#Early return
+		if not solution==BalancethicknessSolutionEnum():
+			return md
+
+		md = checkfield(md,'balancethickness.spcthickness','forcing',1)
+		md = checkfield(md,'balancethickness.thickening_rate','size',[md.mesh.numberofvertices],'NaN',1)
+		md = checkfield(md,'balancethickness.stabilization','size',[1],'values',[0,1,2,3])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','thickening_rate','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
+	# }}}
+
Index: /issm/trunk/src/m/classes/bamggeom.py
===================================================================
--- /issm/trunk/src/m/classes/bamggeom.py	(revision 13395)
+++ /issm/trunk/src/m/classes/bamggeom.py	(revision 13395)
@@ -0,0 +1,45 @@
+class bamggeom(object):
+	"""
+	BAMGGEOM class definition
+
+	   Usage:
+	      bamggeom(varargin)
+	"""
+
+	def __init__(self,*args):    # {{{
+		self.Vertices=[]
+		self.Edges=[]
+		self.TangentAtEdges=[]
+		self.Corners=[]
+		self.RequiredVertices=[]
+		self.RequiredEdges=[]
+		self.CrackedEdges=[]
+		self.SubDomains=[]
+
+		if not len(args):
+			# if no input arguments, create a default object
+			pass
+
+		elif len(args) == 1:
+			object=args[0]
+			for field in object.iterkeys():
+				if field in vars(self):
+					setattr(self,field,object[field])
+
+		else:
+			raise TypeError("bamggeom constructor error message: unknown type of constructor call")
+	# }}}
+
+	def __repr__(self):    # {{{
+		s ="class '%s' object '%s' = \n" % (type(self),'self')
+		s+="    Vertices: %s\n" % str(self.Vertices)
+		s+="    Edges: %s\n" % str(self.Edges)
+		s+="    TangentAtEdges: %s\n" % str(self.TangentAtEdges)
+		s+="    Corners: %s\n" % str(self.Corners)
+		s+="    RequiredVertices: %s\n" % str(self.RequiredVertices)
+		s+="    RequiredEdges: %s\n" % str(self.RequiredEdges)
+		s+="    CrackedEdges: %s\n" % str(self.CrackedEdges)
+		s+="    SubDomains: %s\n" % str(self.SubDomains)
+		return s
+	# }}}
+
Index: /issm/trunk/src/m/classes/bamgmesh.py
===================================================================
--- /issm/trunk/src/m/classes/bamgmesh.py	(revision 13395)
+++ /issm/trunk/src/m/classes/bamgmesh.py	(revision 13395)
@@ -0,0 +1,61 @@
+class bamgmesh(object):
+	"""
+	BAMGMESH class definition
+
+	   Usage:
+	      bamgmesh(varargin)
+	"""
+
+	def __init__(self,*args):    # {{{
+		self.Vertices=[]
+		self.Edges=[]
+		self.Triangles=[]
+		self.Quadrilaterals=[]
+		self.IssmEdges=[]
+		self.IssmSegments=[]
+		self.VerticesOnGeomVertex=[]
+		self.VerticesOnGeomEdge=[]
+		self.EdgesOnGeomEdge=[]
+		self.SubDomains=[]
+		self.SubDomainsFromGeom=[]
+		self.ElementConnectivity=[]
+		self.NodalConnectivity=[]
+		self.NodalElementConnectivity=[]
+		self.CrackedVertices=[]
+		self.CrackedEdges=[]
+
+		if not len(args):
+			# if no input arguments, create a default object
+			pass
+
+		elif len(args) == 1:
+			object=args[0]
+			for field in object.iterkeys():
+				if field in vars(self):
+					setattr(self,field,object[field])
+
+		else:
+			raise TypeError("bamgmesh constructor error message: unknown type of constructor call")
+	# }}}
+
+	def __repr__(self):    # {{{
+		s ="class '%s' object '%s' = \n" % (type(self),'self')
+		s+="    Vertices: %s\n" % str(self.Vertices)
+		s+="    Edges: %s\n" % str(self.Edges)
+		s+="    Triangles: %s\n" % str(self.Triangles)
+		s+="    Quadrilaterals: %s\n" % str(self.Quadrilaterals)
+		s+="    IssmEdges: %s\n" % str(self.IssmEdges)
+		s+="    IssmSegments: %s\n" % str(self.IssmSegments)
+		s+="    VerticesOnGeomVertex: %s\n" % str(self.VerticesOnGeomVertex)
+		s+="    VerticesOnGeomEdge: %s\n" % str(self.VerticesOnGeomEdge)
+		s+="    EdgesOnGeomEdge: %s\n" % str(self.EdgesOnGeomEdge)
+		s+="    SubDomains: %s\n" % str(self.SubDomains)
+		s+="    SubDomainsFromGeom: %s\n" % str(self.SubDomainsFromGeom)
+		s+="    ElementConnectivity: %s\n" % str(self.ElementConnectivity)
+		s+="    NodalConnectivity: %s\n" % str(self.NodalConnectivity)
+		s+="    NodalElementConnectivity: %s\n" % str(self.NodalElementConnectivity)
+		s+="    CrackedVertices: %s\n" % str(self.CrackedVertices)
+		s+="    CrackedEdges: %s\n" % str(self.CrackedEdges)
+		return s
+	# }}}
+
Index: /issm/trunk/src/m/classes/basalforcings.m
===================================================================
--- /issm/trunk/src/m/classes/basalforcings.m	(revision 13394)
+++ /issm/trunk/src/m/classes/basalforcings.m	(revision 13395)
@@ -24,11 +24,11 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			if ismember(PrognosticAnalysisEnum,analyses) & ~(solution==TransientSolutionEnum & md.transient.isprognostic==0),
+			if ismember(PrognosticAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.isprognostic==0),
 				md = checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1);
 			end
-			if ismember(BalancethicknessAnalysisEnum,analyses),
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
 				md = checkfield(md,'basalforcings.melting_rate','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
-			if ismember(ThermalAnalysisEnum,analyses) & ~(solution==TransientSolutionEnum & md.transient.isthermal==0),
+			if ismember(ThermalAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.isthermal==0),
 				md = checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1);
 				md = checkfield(md,'basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0);
Index: /issm/trunk/src/m/classes/basalforcings.py
===================================================================
--- /issm/trunk/src/m/classes/basalforcings.py	(revision 13394)
+++ /issm/trunk/src/m/classes/basalforcings.py	(revision 13395)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class basalforcings:
+class basalforcings(object):
+	"""
+	BASAL FORCINGS class definition
+
+	   Usage:
+	      basalforcings=basalforcings();
+	"""
+
 	#properties
 	def __init__(self):
@@ -14,16 +24,37 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   basal forcings parameters:"
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,"melting_rate","basal melting rate (positive if melting)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"melting_rate_correction","additional melting applied when the grounding line retreats"))
-		string="%s\n%s"%(string,fielddisplay(obj,"geothermalflux","geothermal heat flux [W/m^2]"))
+		string="%s\n\n%s"%(string,fielddisplay(self,"melting_rate","basal melting rate (positive if melting)"))
+		string="%s\n%s"%(string,fielddisplay(self,"melting_rate_correction","additional melting applied when the grounding line retreats"))
+		string="%s\n%s"%(string,fielddisplay(self,"geothermalflux","geothermal heat flux [W/m^2]"))
 		return string
 		#}}}
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if PrognosticAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isprognostic):
+			md = checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'basalforcings.melting_rate','NaN',1,'size',[md.mesh.numberofvertices])
+
+		if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isthermal):
+			md = checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0)
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','melting_rate','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','melting_rate_correction','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1)
+	# }}}
+
Index: /issm/trunk/src/m/classes/clusters/acenet.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/acenet.m	(revision 13394)
+++ /issm/trunk/src/m/classes/clusters/acenet.m	(revision 13395)
@@ -18,5 +18,5 @@
 		 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
+		 codepath='PATH'; % this one is for issm on my acenet directory
 		 executionpath='/home/klemorza/issm/execution';
 		 %}}}
@@ -56,5 +56,5 @@
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
 			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
@@ -74,5 +74,5 @@
           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);
+                   cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
 			 fclose(fid);
 
@@ -85,7 +85,4 @@
 			 for i=1:numel(filelist),
 				 compressstring = [compressstring ' ' filelist{i}];
-			 end
-			 if cluster.interactive,
-				 compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
 			 end
 			 system(compressstring);
Index: /issm/trunk/src/m/classes/clusters/castor.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/castor.m	(revision 13394)
+++ /issm/trunk/src/m/classes/clusters/castor.m	(revision 13395)
@@ -46,5 +46,5 @@
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
 			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
@@ -62,8 +62,8 @@
 			 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,'export PBS_O_WORKDIR=%s\n',[cluster.executionpath '/' dirname]);
 			 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);
+			 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 '/' dirname],modelname);
 			 fclose(fid);
 
Index: /issm/trunk/src/m/classes/clusters/cosmos.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/cosmos.m	(revision 13394)
+++ /issm/trunk/src/m/classes/clusters/cosmos.m	(revision 13395)
@@ -46,5 +46,5 @@
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
 			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
@@ -60,10 +60,10 @@
 			 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,'export PBS_O_WORKDIR=%s\n',[cluster.executionpath '/' dirname]);
 			 fprintf(fid,'cd $PBS_O_WORKDIR\n');
 			 fprintf(fid,'export OMP_NUM_THREADS=1\n');
 			 fprintf(fid,'ulimit -s unlimited\n');
 			 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);
+			 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 '/' dirname],modelname);
 			 fclose(fid);
 
Index: /issm/trunk/src/m/classes/clusters/discover.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/discover.m	(revision 13394)
+++ /issm/trunk/src/m/classes/clusters/discover.m	(revision 13395)
@@ -87,5 +87,5 @@
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
 			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
@@ -107,10 +107,10 @@
 			 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 mpi/impi-4.0.3.008\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);
+			 fprintf(fid,'cd %s/%s/\n\n',cluster.executionpath,dirname);
+			 fprintf(fid,'mpirun -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
 			 if ~io_gather, %concatenate the output files:
 				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
@@ -122,7 +122,7 @@
 				 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);
+					 fprintf(fid,'mpirun -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],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);
+					 fprintf(fid,'mpirun -np %i valgrind --leak-check=full %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
 				 end
 				 if ~io_gather, %concatenate the output files:
Index: /issm/trunk/src/m/classes/clusters/gemini.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/gemini.m	(revision 13394)
+++ /issm/trunk/src/m/classes/clusters/gemini.m	(revision 13395)
@@ -46,5 +46,5 @@
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
 			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
@@ -63,8 +63,8 @@
 			 fprintf(fid,'#PBS -e %s.errlog \n',modelname);
 
-			 fprintf(fid,'export PBS_O_WORKDIR=%s\n',cluster.executionpath);
+			 fprintf(fid,'export PBS_O_WORKDIR=%s\n',[cluster.executionpath '/' dirname]);
 			 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);
+			 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 '/' dirname],modelname);
 			 fclose(fid);
 
Index: /issm/trunk/src/m/classes/clusters/generic.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/generic.m	(revision 13394)
+++ /issm/trunk/src/m/classes/clusters/generic.m	(revision 13395)
@@ -6,172 +6,195 @@
 
 classdef generic
-    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{:});
-
-			 %get name
-			 cluster.name=getfieldvalue(options,'name',oshostname());
-
-			 %initialize cluster using user settings if provided
-			 if (exist([cluster.name '_settings'])==2), eval([cluster.name '_settings']); end
-
-			 %OK get other fields
-			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
-		 end
-		 %}}}
-		 function disp(cluster) % {{{
-			 %  display the object
-			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
-			 disp(sprintf('    name: %s',cluster.name));
-			 disp(sprintf('    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),
-				 checkessage('number of processors should not be NaN!');
-			 end
-		 end
-		 %}}}
-		 function BuildQueueScript(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/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);
-
-			 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 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,dirname,filelist)% {{{
-
-			if ispc,
+	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{:});
+
+			%get name
+			cluster.name=getfieldvalue(options,'name',oshostname());
+
+			%initialize cluster using user settings if provided
+			if (exist([cluster.name '_settings'])==2), eval([cluster.name '_settings']); end
+
+			%OK get other fields
+			cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		end
+		%}}}
+		function disp(cluster) % {{{
+			%  display the object
+			disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			disp(sprintf('    name: %s',cluster.name));
+			disp(sprintf('    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) % {{{
+
+			%write queuing script 
+			if ~ispc(),
+
+				fid=fopen([modelname '.queue'],'w');
+				fprintf(fid,'#!/bin/sh\n');
+				if ~isvalgrind,
+					if cluster.interactive
+						if ismpi,
+							fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+						else
+							fprintf(fid,'%s/issm.exe %s %s %s ',cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+						end
+					else
+						if ismpi,
+							fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+						else
+							fprintf(fid,'%s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+						end
+					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);
+					if ismac, 
+						if ismpi,
+							fprintf(fid,'mpiexec -np %i %s --leak-check=full --dsymutil=yes --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+							cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname], modelname,modelname,modelname);
+						else
+							fprintf(fid,'%s --leak-check=full --dsymutil=yes --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+							cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname], modelname,modelname,modelname);
+						end
+					else
+						if ismpi,
+							fprintf(fid,'mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+							cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+						else
+							fprintf(fid,'%s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
+							cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+						end
+					end
+				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 '/' dirname],modelname);
+				else
+					fprintf(fid,'"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog',...
+						cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+				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 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],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,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,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],modelname);
+				else
+					fprintf(fid,'"%s/issm.exe" %s "%s" %s 2> %s.errlog >%s.outlog',...
+						cluster.codepath,EnumToString(solution),[cluster.executionpath '/' modelname],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=['source ' issmdir '/etc/environment.sh && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && source  ' modelname '.queue '];
+			issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		end %}}}
+		function Download(cluster,dirname,filelist)% {{{
+
+			if ispc(),
 				%do nothing
 				return;
Index: /issm/trunk/src/m/classes/clusters/generic.py
===================================================================
--- /issm/trunk/src/m/classes/clusters/generic.py	(revision 13394)
+++ /issm/trunk/src/m/classes/clusters/generic.py	(revision 13395)
@@ -1,14 +1,26 @@
-#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 subprocess
+from EnumToString import EnumToString
+from issmdir import *
+from pairoptions import *
+from ismpi import *
+from issmssh import *
+from issmscpin import *
+from issmscpout import *
+from MatlabFuncs 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,22 +28,171 @@
 		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'
+
+		#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 ispc():
+
+			fid=open(modelname+'.queue','w')
+			fid.write('#!/bin/sh\n')
+			if not isvalgrind:
+				if self.interactive: 
+					if ismpi():
+						fid.write('mpiexec -np %i %s/issm.exe %s %s/%s %s ' % (self.np,self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname))
+					else:
+						fid.write('%s/issm.exe %s %s/%s %s ' % (self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname))
+				else:
+					if ismpi():
+						fid.write('mpiexec -np %i %s/issm.exe %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
+					else:
+						fid.write('%s/issm.exe %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.codepath,EnumToString(solution)[0],self.executionpath,dirname,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)
+				if ismpi():
+					fid.write('mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s/%s %s 2> %s.errlog >%s.outlog ' % \
+							(self.np,self.valgrind,self.valgrindsup,self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
+				else:	
+					fid.write('%s --leak-check=full --suppressions=%s %s/issm.exe %s %s/%s %s 2> %s.errlog >%s.outlog ' % \
+							(self.valgrind,self.valgrindsup,self.codepath,EnumToString(solution)[0],self.executionpath,dirname,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" %s ' % (self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname))
+			else:
+				fid.write('"%s/issm.exe" %s "%s/%s" %s 2> %s.errlog >%s.outlog' % \
+					(self.codepath,EnumToString(solution)[0],self.executionpath,dirname,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 ispc():
+
+			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 %s ' % (self.np,self.codepath,self.executionpath,modelname,modelname))
+				else:
+					fid.write('mpiexec -np %i %s/kriging.exe %s/%s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,self.executionpath,modelname,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 %s 2> %s.errlog >%s.outlog ' % \
+					(self.np,self.valgrind,self.valgrindsup,self.codepath,self.executionpath,modelname,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" %s ' % (self.codepath,EnumToString(solution)[0],self.executionpath,modelname,modelname))
+			else:
+				fid.write('"%s/issm.exe" %s "%s/%s" %s 2> %s.errlog >%s.outlog' % \
+					(self.codepath,EnumToString(solution)[0],self.executionpath,modelname,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 ispc():
+			#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/trunk/src/m/classes/clusters/greenplanet.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/greenplanet.m	(revision 13394)
+++ /issm/trunk/src/m/classes/clusters/greenplanet.m	(revision 13395)
@@ -63,5 +63,5 @@
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
 			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
@@ -81,6 +81,6 @@
 			 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,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
+			 fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,dirname);
+			 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
 			 if ~io_gather, %concatenate the output files:
 				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
@@ -91,5 +91,5 @@
 			 if cluster.interactive,
 				 fid=fopen([modelname '.run'],'w');
-				 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),cluster.executionpath,modelname);
+				 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
 				 if ~io_gather, %concatenate the output files:
 					 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
Index: /issm/trunk/src/m/classes/clusters/pfe.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/pfe.m	(revision 13394)
+++ /issm/trunk/src/m/classes/clusters/pfe.m	(revision 13395)
@@ -9,18 +9,19 @@
     properties (SetAccess=public)  
 		 % {{{
-		 name='pfe'
-		 login='';
-		 numnodes=20;
-		 cpuspernode=8; 
-		 port=1025;
-		 queue='long';
-		 time=12*60;
-		 processor='neh';
-		 codepath='';
-		 executionpath='';
-		 interactive=0;
-		 bbftp=0;
-		 numstreams=8;
-		 hyperthreading=0;
+		 name           = 'pfe'
+		 login          = '';
+		 numnodes       = 20;
+		 cpuspernode    = 8;
+		 port           = 1025;
+		 queue          = 'long';
+		 time           = 12*60;
+		 processor      = 'neh';
+		 codepath       = '';
+		 executionpath  = '';
+		 grouplist     = 's1010';
+		 interactive    = 0;
+		 bbftp          = 0;
+		 numstreams     = 8;
+		 hyperthreading = 0;
 	 end
 	 properties (SetAccess=private) 
@@ -52,4 +53,5 @@
 			 disp(sprintf('    codepath: %s',cluster.codepath));
 			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+			 disp(sprintf('    grouplist: %s',cluster.grouplist));
 			 disp(sprintf('    interactive: %i',cluster.interactive));
 			 disp(sprintf('    hyperthreading: %i',cluster.hyperthreading));
@@ -93,8 +95,9 @@
 			 if isempty(cluster.codepath), md = checkmessage(md,'codepath empty'); end
 			 if isempty(cluster.executionpath), md = checkmessage(md,'executionpath empty'); end
-
-		 end
-		 %}}}
-		 function BuildQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+			 if isempty(cluster.grouplist), md = checkmessage(md,'grouplist empty'); end
+
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
 			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
@@ -107,4 +110,55 @@
 			 fprintf(fid,'#PBS -S /bin/bash\n');
 %			 fprintf(fid,'#PBS -N %s\n',modelname);
+			 fprintf(fid,'#PBS -l select=%i:ncpus=%i:model=%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=%s\n',cluster.grouplist);
+			 fprintf(fid,'#PBS -m e\n');
+			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
+			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
+			 fprintf(fid,'module load comp-intel/11.1.046\n');
+			 fprintf(fid,'module load mpi/mpt.1.25\n');
+			 fprintf(fid,'module load 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,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
+			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
+			 fprintf(fid,'cd %s/%s/\n\n',cluster.executionpath,dirname);
+			 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			 if ~io_gather, %concatenate the output files:
+				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			 end
+			 fclose(fid);
+
+			 %in interactive mode, create a run file, and errlog and outlog file
+			 if cluster.interactive,
+				 fid=fopen([modelname '.run'],'w');
+				 if ~isvalgrind,
+					 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/Interactive' num2str(cluster.interactive)],modelname);
+				 else
+					 fprintf(fid,'mpiexec -np %i valgrind --leak-check=full %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/Interactive' num2str(cluster.interactive)],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 BuildKrigingQueueScript(cluster,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:model=%s\n',cluster.numnodes,cluster.cpuspernode,cluster.processor);
 			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time*60); %walltime is in seconds.
@@ -118,8 +172,10 @@
 			 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 PATH="$PATH:."\n');
+			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
+			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
 			 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);
+			 fprintf(fid,'cd %s/%s/\n\n',cluster.executionpath,modelname);
+			 fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s\n',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname); %FIXME
 			 if ~io_gather, %concatenate the output files:
 				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
@@ -131,7 +187,7 @@
 				 fid=fopen([modelname '.run'],'w');
 				 if ~isvalgrind,
-					 fprintf(fid,'mpiexec -np %i %s/issm.exe %s $PBS_O_WORKDIR %s\n',cluster.np,cluster.codepath,EnumToString(solution),modelname);
-				 else
-					 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);
+					 fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s\n',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname);
+				 else
+					 fprintf(fid,'mpiexec -np %i valgrind --leak-check=full %s/kriging.exe %s %s\n',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname);
 				 end
 				 if ~io_gather, %concatenate the output files:
Index: /issm/trunk/src/m/classes/clusters/pollux.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/pollux.m	(revision 13394)
+++ /issm/trunk/src/m/classes/clusters/pollux.m	(revision 13395)
@@ -46,5 +46,5 @@
 		 end
 		 %}}}
-		 function BuildQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
 
 			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
@@ -62,8 +62,8 @@
 			 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,'export PBS_O_WORKDIR=%s\n',[cluster.executionpath '/' dirname]);
 			 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);
+			 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 '/' dirname],modelname);
 			 fclose(fid);
 
Index: /issm/trunk/src/m/classes/constants.py
===================================================================
--- /issm/trunk/src/m/classes/constants.py	(revision 13394)
+++ /issm/trunk/src/m/classes/constants.py	(revision 13395)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class constants:
+class constants(object):
+	"""
+	CONSTANTS class definition
+
+	   Usage:
+	      constants=constants();
+	"""
+
 	#properties
 	def __init__(self):
@@ -14,10 +24,10 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   constants parameters:"
-		string="%s\n\n%s"%(string,fielddisplay(obj,"g","gravitational acceleration"))
-		string="%s\n%s"%(string,fielddisplay(obj,"yts","number of seconds in a year"))
-		string="%s\n%s"%(string,fielddisplay(obj,"referencetemperature","reference temperature used in the enthalpy model"))
+		string="%s\n\n%s"%(string,fielddisplay(self,"g","gravitational acceleration"))
+		string="%s\n%s"%(string,fielddisplay(self,"yts","number of seconds in a year"))
+		string="%s\n%s"%(string,fielddisplay(self,"referencetemperature","reference temperature used in the enthalpy model"))
 
 
@@ -25,17 +35,32 @@
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#acceleration due to gravity (m/s^2)
-		obj.g=9.81
+		self.g=9.81
 
 		#converstion from year to seconds
-		obj.yts=365*24*3600
+		self.yts=365*24*3600
 
 		#the reference temperature for enthalpy model (cf Aschwanden)
-		obj.referencetemperature=223.15
+		self.referencetemperature=223.15
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'constants.g','>',0,'size',[1])
+		md = checkfield(md,'constants.yts','>',0,'size',[1])
+		md = checkfield(md,'constants.referencetemperature','size',[1])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','g','format','Double')
+		WriteData(fid,'object',self,'fieldname','yts','format','Double')
+		WriteData(fid,'object',self,'fieldname','referencetemperature','format','Double')
+	# }}}
+
Index: /issm/trunk/src/m/classes/debug.py
===================================================================
--- /issm/trunk/src/m/classes/debug.py	(revision 13394)
+++ /issm/trunk/src/m/classes/debug.py	(revision 13395)
@@ -1,11 +1,20 @@
 #module imports
 from fielddisplay import fielddisplay
+from WriteData import *
 
-class debug:
+class debug(object):
+	"""
+	DEBUG class definition
+
+	   Usage:
+	      debug=debug();
+	"""
+
 	#properties
 	def __init__(self):
 		# {{{ Properties
-		self.valgrind=False
-		self.gprof   = False
+		self.valgrind  = False
+		self.gprof     = False
+		self.profiling = False
 		
 		#set defaults
@@ -13,16 +22,21 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   debug parameters:"
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,"valgrind","use Valgrind to debug (0 or 1)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"gprof","use gnu-profiler to find out where the time is spent"))
+		string="%s\n\n%s"%(string,fielddisplay(self,"valgrind","use Valgrind to debug (0 or 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"gprof","use gnu-profiler to find out where the time is spent"))
+		string="%s\n%s"%(string,fielddisplay(self,'profiling','enables profiling (memory, flops, time)'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','profiling','format','Boolean')
+	# }}}
+
Index: /issm/trunk/src/m/classes/diagnostic.m
===================================================================
--- /issm/trunk/src/m/classes/diagnostic.m	(revision 13394)
+++ /issm/trunk/src/m/classes/diagnostic.m	(revision 13395)
@@ -67,14 +67,14 @@
 
 			%Early return
-			if ~ismember(DiagnosticHorizAnalysisEnum,analyses), return; end
-			%if ~ismember(DiagnosticHorizAnalysisEnum,analyses) |  (solution==TransientSolutionEnum & md.transient.isdiagnostic==0), return; end
+			if ~ismember(DiagnosticHorizAnalysisEnum(),analyses), return; end
+			%if ~ismember(DiagnosticHorizAnalysisEnum(),analyses) |  (solution==TransientSolutionEnum() & md.transient.isdiagnostic==0), return; end
 
 			md = checkfield(md,'diagnostic.spcvx','forcing',1);
 			md = checkfield(md,'diagnostic.spcvy','forcing',1);
 			if md.mesh.dimension==3, md = checkfield(md,'diagnostic.spcvz','forcing',1); end
-			md = checkfield(md,'diagnostic.restol','size',[1 1],'>',0);
+			md = checkfield(md,'diagnostic.restol','size',[1 1],'>',0,'NaN',1);
 			md = checkfield(md,'diagnostic.reltol','size',[1 1]);
 			md = checkfield(md,'diagnostic.abstol','size',[1 1]);
-			md = checkfield(md,'diagnostic.isnewton','numel',1,'values',[0 1]);
+			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);
@@ -102,6 +102,6 @@
 			if any(sum(isnan(md.diagnostic.referential),2)==0),
 				pos=find(sum(isnan(md.diagnostic.referential),2)==0);
-				if any(abs(dot(md.diagnostic.referential(pos,1:3)',md.diagnostic.referential(pos,4:6)'))>eps),
-					md = checkmessage(md,['Vectors in diagnostic.referential (colums 1 to 3 and 4 to 6) must be orthogonal']);
+				if any(abs(dot(md.diagnostic.referential(pos,1:3),md.diagnostic.referential(pos,4:6),2))>eps),
+					md = checkmessage(md,['Vectors in diagnostic.referential (columns 1 to 3 and 4 to 6) must be orthogonal']);
 				end
 			end
@@ -168,8 +168,8 @@
 			%marshall ice front
 			data=obj.icefront;
-			pos=find(data(:,end)==0); data(pos,end)=AirEnum;
-			pos=find(data(:,end)==1); data(pos,end)=WaterEnum;
-			pos=find(data(:,end)==2); data(pos,end)=IceEnum;
-			WriteData(fid,'data',data,'enum',DiagnosticIcefrontEnum,'format','DoubleMat','mattype',3);
+			pos=find(data(:,end)==0); data(pos,end)=AirEnum();
+			pos=find(data(:,end)==1); data(pos,end)=WaterEnum();
+			pos=find(data(:,end)==2); data(pos,end)=IceEnum();
+			WriteData(fid,'data',data,'enum',DiagnosticIcefrontEnum(),'format','DoubleMat','mattype',3);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/diagnostic.py
===================================================================
--- /issm/trunk/src/m/classes/diagnostic.py	(revision 13394)
+++ /issm/trunk/src/m/classes/diagnostic.py	(revision 13395)
@@ -1,6 +1,18 @@
 #module imports
+import numpy
+import sys
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class diagnostic:
+class diagnostic(object):
+	"""
+	DIAGNOSTIC class definition
+
+	   Usage:
+	      diagnostic=diagnostic();
+	"""
+
 	#properties
 	def __init__(self):
@@ -29,71 +41,154 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
-		
 		
 		string='\n   Diagnostic solution parameters:'
 		string="%s\n\n%s"%(string,'      Convergence criteria:')
 			
-		string="%s\n%s"%(string,fielddisplay(obj,'restol','mechanical equilibrium residual convergence criterion'))
-		string="%s\n%s"%(string,fielddisplay(obj,'reltol','velocity relative convergence criterion, NaN -> not applied'))
-		string="%s\n%s"%(string,fielddisplay(obj,'abstol','velocity absolute convergence criterion, NaN -> not applied'))
-		string="%s\n%s"%(string,fielddisplay(obj,'isnewton','Apply Newton''s method instead of a Picard fixed point method'))
-		string="%s\n%s"%(string,fielddisplay(obj,'maxiter','maximum number of nonlinear iterations'))
-		string="%s\n%s"%(string,fielddisplay(obj,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)'))
+		string="%s\n%s"%(string,fielddisplay(self,'restol','mechanical equilibrium residual convergence criterion'))
+		string="%s\n%s"%(string,fielddisplay(self,'reltol','velocity relative convergence criterion, NaN -> not applied'))
+		string="%s\n%s"%(string,fielddisplay(self,'abstol','velocity absolute convergence criterion, NaN -> not applied'))
+		string="%s\n%s"%(string,fielddisplay(self,'isnewton',"Apply Newton's method instead of a Picard fixed point method"))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of nonlinear iterations'))
+		string="%s\n%s"%(string,fielddisplay(self,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)'))
 
 		string="%s\n%s"%(string,'      boundary conditions:')
 
-		string="%s\n%s"%(string,fielddisplay(obj,'spcvx','x-axis velocity constraint (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'spcvy','y-axis velocity constraint (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'spcvz','z-axis velocity constraint (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'icefront','segments on ice front list (last column 0-> Air, 1-> Water, 2->Ice'))
+		string="%s\n%s"%(string,fielddisplay(self,'spcvx','x-axis velocity constraint (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'spcvy','y-axis velocity constraint (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'spcvz','z-axis velocity constraint (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'icefront','segments on ice front list (last column 0-> Air, 1-> Water, 2->Ice'))
 
 		string="%s\n%s"%(string,'      Rift options:')
-		string="%s\n%s"%(string,fielddisplay(obj,'rift_penalty_threshold','threshold for instability of mechanical constraints'))
-		string="%s\n%s"%(string,fielddisplay(obj,'rift_penalty_lock','number of iterations before rift penalties are locked'))
+		string="%s\n%s"%(string,fielddisplay(self,'rift_penalty_threshold','threshold for instability of mechanical constraints'))
+		string="%s\n%s"%(string,fielddisplay(self,'rift_penalty_lock','number of iterations before rift penalties are locked'))
 
 		string="%s\n%s"%(string,'      Penalty options:')
-		string="%s\n%s"%(string,fielddisplay(obj,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vertex_pairing','pairs of vertices that are penalized'))
+		string="%s\n%s"%(string,fielddisplay(self,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset'))
+		string="%s\n%s"%(string,fielddisplay(self,'vertex_pairing','pairs of vertices that are penalized'))
 
 		string="%s\n%s"%(string,'      Other:')
-		string="%s\n%s"%(string,fielddisplay(obj,'shelf_dampening','use dampening for floating ice ? Only for Stokes model'))
-		string="%s\n%s"%(string,fielddisplay(obj,'stokesreconditioning','multiplier for incompressibility equation. Only for Stokes model'))
-		string="%s\n%s"%(string,fielddisplay(obj,'referential','local referential'))
-		string="%s\n%s"%(string,fielddisplay(obj,'requested_outputs','additional outputs requested'))
+		string="%s\n%s"%(string,fielddisplay(self,'shelf_dampening','use dampening for floating ice ? Only for Stokes model'))
+		string="%s\n%s"%(string,fielddisplay(self,'stokesreconditioning','multiplier for incompressibility equation. Only for Stokes model'))
+		string="%s\n%s"%(string,fielddisplay(self,'referential','local referential'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
 
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		#maximum of non-linear iterations.
-		obj.maxiter=100
+		self.maxiter=100
 
 		#Convergence criterion: absolute, relative and residual
-		obj.restol=10**-4;
-		obj.reltol=0.01
-		obj.abstol=10
+		self.restol=10**-4
+		self.reltol=0.01
+		self.abstol=10
 
-		obj.stokesreconditioning=10**13
-		obj.shelf_dampening=0
+		self.stokesreconditioning=10**13
+		self.shelf_dampening=0
 
 		#Penalty factor applied kappa=max(stiffness matrix)*10^penalty_factor
-		obj.penalty_factor=3
+		self.penalty_factor=3
 
 		#coefficient to update the viscosity between each iteration of
 		#a diagnostic according to the following formula
 		#viscosity(n)=viscosity(n)+viscosity_overshoot(viscosity(n)-viscosity(n-1))
-		obj.viscosity_overshoot=0
+		self.viscosity_overshoot=0
 
 		#Stop the iterations of rift if below a threshold
-		obj.rift_penalty_threshold=0
+		self.rift_penalty_threshold=0
 
 		#in some solutions, it might be needed to stop a run when only
 		#a few constraints remain unstable. For thermal computation, this
 		#parameter is often used.
-		obj.rift_penalty_lock=10
+		self.rift_penalty_lock=10
 
-		return obj
+		return self
 	#}}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if DiagnosticHorizAnalysisEnum() not in analyses:
+			return md
+		#if (DiagnosticHorizAnalysisEnum() not in analyses) | (solution==TransientSolutionEnum() and not md.transient.isdiagnostic):
+		#	return md
+
+		md = checkfield(md,'diagnostic.spcvx','forcing',1)
+		md = checkfield(md,'diagnostic.spcvy','forcing',1)
+		if md.mesh.dimension==3:
+			md = checkfield(md,'diagnostic.spcvz','forcing',1)
+		md = checkfield(md,'diagnostic.restol','size',[1],'>',0)
+		md = checkfield(md,'diagnostic.reltol','size',[1])
+		md = checkfield(md,'diagnostic.abstol','size',[1])
+		md = checkfield(md,'diagnostic.isnewton','numel',[1],'values',[0,1])
+		md = checkfield(md,'diagnostic.stokesreconditioning','size',[1],'NaN',1)
+		md = checkfield(md,'diagnostic.viscosity_overshoot','size',[1],'NaN',1)
+		if md.mesh.dimension==2:
+			md = checkfield(md,'diagnostic.icefront','size',[float('NaN'),4],'NaN',1)
+		else:
+			md = checkfield(md,'diagnostic.icefront','size',[float('NaN'),6],'NaN',1)
+		md = checkfield(md,'diagnostic.icefront[:,-1]','values',[0,1,2])
+		md = checkfield(md,'diagnostic.maxiter','size',[1],'>=',1)
+		md = checkfield(md,'diagnostic.referential','size',[md.mesh.numberofvertices,6])
+		if not md.diagnostic.requested_outputs:
+			md = checkfield(md,'diagnostic.requested_outputs','size',[float('NaN'),1])
+
+		#singular solution
+#		if ~any((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy))==2),
+		if not numpy.any(numpy.logical_and(numpy.logical_not(numpy.isnan(md.diagnostic.spcvx)),numpy.logical_not(numpy.isnan(md.diagnostic.spcvy)))):
+			md.checkmessage("model is not well posed (singular). You need at least one node with fixed velocity!")
+		#CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES
+#		if any(sum(isnan(md.diagnostic.referential),2)~=0 & sum(isnan(md.diagnostic.referential),2)~=6),
+		if numpy.any(numpy.logical_and(numpy.sum(numpy.isnan(md.diagnostic.referential),axis=1)!=0,numpy.sum(numpy.isnan(md.diagnostic.referential),axis=1)!=6)):
+			md.checkmessage("Each line of diagnostic.referential should contain either only NaN values or no NaN values")
+		#CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL
+#		if any(sum(isnan(md.diagnostic.referential),2)==0),
+		if numpy.any(numpy.sum(numpy.isnan(md.diagnostic.referential),axis=1)==0):
+			pos=[i for i,item in enumerate(numpy.sum(numpy.isnan(md.diagnostic.referential),axis=1)) if item==0]
+#			numpy.inner (and numpy.dot) calculate all the dot product permutations, resulting in a full matrix multiply
+#			if numpy.any(numpy.abs(numpy.inner(md.diagnostic.referential[pos,0:2],md.diagnostic.referential[pos,3:5]).diagonal())>sys.float_info.epsilon):
+#				md.checkmessage("Vectors in diagnostic.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
+			for item in md.diagnostic.referential[pos,:]:
+				if numpy.abs(numpy.inner(item[0:2],item[3:5]))>sys.float_info.epsilon:
+					md.checkmessage("Vectors in diagnostic.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
+		#CHECK THAT NO rotation specified for FS Grounded ice at base
+#		if md.mesh.dimension==3 & md.flowequation.isstokes,
+		if md.mesh.dimension==3 and md.flowequation.isstokes:
+			pos=numpy.nonzero(numpy.logical_and(md.mask.vertexongroundedice,md.mesh.vertexonbed))
+			if numpy.any(numpy.logical_not(numpy.isnan(md.diagnostic.referential[pos,:]))):
+				md.checkmessage("no referential should be specified for basal vertices of grounded ice")
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spcvx','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','spcvy','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','spcvz','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','restol','format','Double')
+		WriteData(fid,'object',self,'fieldname','reltol','format','Double')
+		WriteData(fid,'object',self,'fieldname','abstol','format','Double')
+		WriteData(fid,'object',self,'fieldname','isnewton','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','stokesreconditioning','format','Double')
+		WriteData(fid,'object',self,'fieldname','viscosity_overshoot','format','Double')
+		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
+		WriteData(fid,'object',self,'fieldname','shelf_dampening','format','Integer')
+		WriteData(fid,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
+		WriteData(fid,'object',self,'fieldname','rift_penalty_lock','format','Integer')
+		WriteData(fid,'object',self,'fieldname','rift_penalty_threshold','format','Integer')
+		WriteData(fid,'object',self,'fieldname','referential','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3)
+
+		#marshall ice front
+		data=self.icefront
+		data[numpy.nonzero(data[:,-1]==0),-1]=AirEnum()
+		data[numpy.nonzero(data[:,-1]==1),-1]=WaterEnum()
+		data[numpy.nonzero(data[:,-1]==2),-1]=IceEnum()
+		WriteData(fid,'data',data,'enum',DiagnosticIcefrontEnum(),'format','DoubleMat','mattype',3)
+	# }}}
+
Index: /issm/trunk/src/m/classes/flaim.m
===================================================================
--- /issm/trunk/src/m/classes/flaim.m	(revision 13394)
+++ /issm/trunk/src/m/classes/flaim.m	(revision 13395)
@@ -35,5 +35,5 @@
 
 			%Early return
-			if solution~=FlaimSolutionEnum, return; end
+			if solution~=FlaimSolutionEnum(), return; end
 
 			md = checkfield(md,'flaim.tracks','file',1);
Index: /issm/trunk/src/m/classes/flaim.py
===================================================================
--- /issm/trunk/src/m/classes/flaim.py	(revision 13394)
+++ /issm/trunk/src/m/classes/flaim.py	(revision 13395)
@@ -1,6 +1,18 @@
 #module imports
+import numpy
+from collections import OrderedDict
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class flaim:
+class flaim(object):
+	"""
+	FLAIM class definition
+
+	   Usage:
+	      flaim=flaim();
+	"""
+
 	#properties
 	def __init__(self):
@@ -8,5 +20,5 @@
 		self.targets            = ''
 		self.tracks             = ''
-		self.flightreqs         = {}
+		self.flightreqs         = OrderedDict()
 		self.criterion          = float('NaN')
 		self.gridsatequator     = 200000
@@ -20,31 +32,47 @@
 		self.opt_niter          = 30000
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Displa
 		string='   FLAIM - Flight Line Adaptation using Ice sheet Modeling:'
 
 		string="%s\n\n%s"%(string,'      Input:')
-		string="%s\n%s"%(string,fielddisplay(obj,'targets'            ,'name of kml output targets file '))
-		string="%s\n%s"%(string,fielddisplay(obj,'tracks'             ,'name of kml input tracks file '))
-		string="%s\n%s"%(string,fielddisplay(obj,'flightreqs'         ,'structure of kml flight requirements (not used yet)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'criterion'          ,'element or nodal criterion for flight path evaluation (metric)'))
+		string="%s\n%s"%(string,fielddisplay(self,'targets'            ,'name of kml output targets file '))
+		string="%s\n%s"%(string,fielddisplay(self,'tracks'             ,'name of kml input tracks file '))
+		string="%s\n%s"%(string,fielddisplay(self,'flightreqs'         ,'structure of kml flight requirements (not used yet)'))
+		string="%s\n%s"%(string,fielddisplay(self,'criterion'          ,'element or nodal criterion for flight path evaluation (metric)'))
 
 		string="%s\n\n%s"%(string,'      Arguments:')
-		string="%s\n%s"%(string,fielddisplay(obj,'gridsatequator'     ,'number of grids at equator (determines resolution)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'usevalueordering'   ,'flag to consider target values for flight path evaluation'))
-		string="%s\n%s"%(string,fielddisplay(obj,'split_antimeridian' ,'flag to split polygons on the antimeridian'))
+		string="%s\n%s"%(string,fielddisplay(self,'gridsatequator'     ,'number of grids at equator (determines resolution)'))
+		string="%s\n%s"%(string,fielddisplay(self,'usevalueordering'   ,'flag to consider target values for flight path evaluation'))
+		string="%s\n%s"%(string,fielddisplay(self,'split_antimeridian' ,'flag to split polygons on the antimeridian'))
 		
 		string="%s\n\n%s"%(string,'      Optimization:')
-		string="%s\n%s"%(string,fielddisplay(obj,'path_optimize'     ,'optimize? (default false)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'opt_ndir'     ,['number of directions to test when moving a point.  If this value = 1, a random direction is tested.',\
+		string="%s\n%s"%(string,fielddisplay(self,'path_optimize'     ,'optimize? (default false)'))
+		string="%s\n%s"%(string,fielddisplay(self,'opt_ndir'     ,['number of directions to test when moving a point.  If this value = 1, a random direction is tested.',\
 										  'A value > 1 results in directions equally spaced from [0, 2*PI] being tested.',\
 										  'For example, 4 would result in directions [0, PI/2, PI, 3PI/2].']))
-		string="%s\n%s"%(string,fielddisplay(obj,'opt_dist'     ,'specifies the distance in km (default 25) to move a randomly selected path point on each iteration'))
-		string="%s\n%s"%(string,fielddisplay(obj,'opt_niter'     ,['number of iterations (default 30,000) to run for flightplan optimization',\
+		string="%s\n%s"%(string,fielddisplay(self,'opt_dist'     ,'specifies the distance in km (default 25) to move a randomly selected path point on each iteration'))
+		string="%s\n%s"%(string,fielddisplay(self,'opt_niter'     ,['number of iterations (default 30,000) to run for flightplan optimization',\
 										   'i.e. the number of times to randomly select a point and move it.']))
 
 		string="%s\n\n%s"%(string,'      Output:')
-		string="%s\n%s"%(string,fielddisplay(obj,'solution'           ,'name of kml solution file'))
-		string="%s\n%s"%(string,fielddisplay(obj,'quality'            ,'quality of kml solution'))
+		string="%s\n%s"%(string,fielddisplay(self,'solution'           ,'name of kml solution file'))
+		string="%s\n%s"%(string,fielddisplay(self,'quality'            ,'quality of kml solution'))
 		return string
 		#}}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not solution==FlaimSolutionEnum():
+			return md
+
+		md = checkfield(md,'flaim.tracks','file',1)
+		if numpy.any(numpy.isnan(md.flaim.criterion)) or not md.flaim.criterion:
+			md = checkfield(md,'flaim.targets','file',1)
+		else:
+			md = checkfield(md,'flaim.criterion','numel',[md.mesh.numberofvertices,md.mesh.numberofelements])
+
+		return md
+	# }}}
+
Index: /issm/trunk/src/m/classes/flowequation.m
===================================================================
--- /issm/trunk/src/m/classes/flowequation.m	(revision 13394)
+++ /issm/trunk/src/m/classes/flowequation.m	(revision 13395)
@@ -8,4 +8,5 @@
 		ismacayealpattyn     = 0;
 		ishutter             = 0;
+		isl1l2               = 0;
 		isstokes             = 0;
 		vertex_equation      = NaN;
@@ -29,9 +30,10 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			if ismember(DiagnosticHorizAnalysisEnum,analyses),
+			if ismember(DiagnosticHorizAnalysisEnum(),analyses),
 
-				md = checkfield(md,'flowequation.ismacayealpattyn','numel',1,'values',[0 1]);
-				md = checkfield(md,'flowequation.ishutter','numel',1,'values',[0 1]);
-				md = checkfield(md,'flowequation.isstokes','numel',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.isl1l2','numel',[1],'values',[0 1]);
+				md = checkfield(md,'flowequation.isstokes','numel',[1],'values',[0 1]);
 				md = checkfield(md,'flowequation.bordermacayeal','size',[md.mesh.numberofvertices 1],'values',[0 1]);
 				md = checkfield(md,'flowequation.borderpattyn','size',[md.mesh.numberofvertices 1],'values',[0 1]);
@@ -41,14 +43,14 @@
 					md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[1:2]);
 				else
-					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]);
+					md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[0:8]);
+					md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[0:8]);
 				end
-				if (md.flowequation.ismacayealpattyn==0 && md.flowequation.ishutter==0 && md.flowequation.isstokes==0),
+				if ~(obj.ismacayealpattyn || obj.ishutter || obj.isstokes || obj.isl1l2),
 					md = checkmessage(md,['no element types set for this model. At least one of ismacayealpattyn, ishutter or isstokes need to be =1']);
 				end
 			end
-			if ismember(DiagnosticHutterAnalysisEnum,analyses),
-				if any(md.flowequation.element_equation==1),
-					if(md.flowequation.element_equation & md.mask.elementonfloatingice),
+			if ismember(DiagnosticHutterAnalysisEnum(),analyses),
+				if any(obj.element_equation==1),
+					if(obj.element_equation & md.mask.elementonfloatingice),
 						disp(sprintf('\n !!! Warning: Hutter''s model is not consistent on ice shelves !!!\n'));
 					end
@@ -62,4 +64,5 @@
 			fielddisplay(obj,'ismacayealpattyn','is the macayeal or pattyn approximation used ?');
 			fielddisplay(obj,'ishutter','is the shallow ice approximation used ?');
+			fielddisplay(obj,'isl1l2','is the l1l2 approximation used ?');
 			fielddisplay(obj,'isstokes','are the Full-Stokes equations used ?');
 			fielddisplay(obj,'vertex_equation','flow equation for each vertex');
@@ -73,4 +76,5 @@
 			WriteData(fid,'object',obj,'fieldname','ismacayealpattyn','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','ishutter','format','Boolean');
+			WriteData(fid,'object',obj,'fieldname','isl1l2','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','isstokes','format','Boolean');
 			WriteData(fid,'object',obj,'fieldname','bordermacayeal','format','DoubleMat','mattype',1);
@@ -79,23 +83,25 @@
 			%convert approximations to enums
 			data=obj.vertex_equation;
-			pos=find(data==0); data(pos,end)=NoneApproximationEnum;
-			pos=find(data==1); data(pos,end)=HutterApproximationEnum;
-			pos=find(data==2); data(pos,end)=MacAyealApproximationEnum;
-			pos=find(data==3); data(pos,end)=PattynApproximationEnum;
-			pos=find(data==4); data(pos,end)=StokesApproximationEnum;
-			pos=find(data==5); data(pos,end)=MacAyealPattynApproximationEnum;
-			pos=find(data==6); data(pos,end)=MacAyealStokesApproximationEnum;
-			pos=find(data==7); data(pos,end)=PattynStokesApproximationEnum;
-			WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum,'format','DoubleMat','mattype',1);
+			pos=find(data==0); data(pos,end)=NoneApproximationEnum();
+			pos=find(data==1); data(pos,end)=HutterApproximationEnum();
+			pos=find(data==2); data(pos,end)=MacAyealApproximationEnum();
+			pos=find(data==3); data(pos,end)=PattynApproximationEnum();
+			pos=find(data==4); data(pos,end)=StokesApproximationEnum();
+			pos=find(data==5); data(pos,end)=MacAyealPattynApproximationEnum();
+			pos=find(data==6); data(pos,end)=MacAyealStokesApproximationEnum();
+			pos=find(data==7); data(pos,end)=PattynStokesApproximationEnum();
+			pos=find(data==8); data(pos,end)=L1L2ApproximationEnum();
+			WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1);
 			data=obj.element_equation;
-			pos=find(data==0); data(pos,end)=NoneApproximationEnum;
-			pos=find(data==1); data(pos,end)=HutterApproximationEnum;
-			pos=find(data==2); data(pos,end)=MacAyealApproximationEnum;
-			pos=find(data==3); data(pos,end)=PattynApproximationEnum;
-			pos=find(data==4); data(pos,end)=StokesApproximationEnum;
-			pos=find(data==5); data(pos,end)=MacAyealPattynApproximationEnum;
-			pos=find(data==6); data(pos,end)=MacAyealStokesApproximationEnum;
-			pos=find(data==7); data(pos,end)=PattynStokesApproximationEnum;
-			WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum,'format','DoubleMat','mattype',2);
+			pos=find(data==0); data(pos,end)=NoneApproximationEnum();
+			pos=find(data==1); data(pos,end)=HutterApproximationEnum();
+			pos=find(data==2); data(pos,end)=MacAyealApproximationEnum();
+			pos=find(data==3); data(pos,end)=PattynApproximationEnum();
+			pos=find(data==4); data(pos,end)=StokesApproximationEnum();
+			pos=find(data==5); data(pos,end)=MacAyealPattynApproximationEnum();
+			pos=find(data==6); data(pos,end)=MacAyealStokesApproximationEnum();
+			pos=find(data==7); data(pos,end)=PattynStokesApproximationEnum();
+			pos=find(data==8); data(pos,end)=L1L2ApproximationEnum();
+			WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum(),'format','DoubleMat','mattype',2);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/flowequation.py
===================================================================
--- /issm/trunk/src/m/classes/flowequation.py	(revision 13394)
+++ /issm/trunk/src/m/classes/flowequation.py	(revision 13395)
@@ -1,6 +1,17 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class flowequation:
+class flowequation(object):
+	"""
+	FLOWEQUATION class definition
+
+	   Usage:
+	      flowequation=flowequation();
+	"""
+
 	#properties
 	def __init__(self):
@@ -9,4 +20,5 @@
 		self.ismacayealpattyn     = 0;
 		self.ishutter             = 0;
+		self.isl1l2             = 0;
 		self.isstokes             = 0;
 		self.vertex_equation      = float('NaN')
@@ -20,22 +32,83 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   flow equation parameters:'
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,'ismacayealpattyn','is the macayeal or pattyn approximation used ?'))
-		string="%s\n%s"%(string,fielddisplay(obj,'ishutter','is the shallow ice approximation used ?'))
-		string="%s\n%s"%(string,fielddisplay(obj,'isstokes','are the Full-Stokes equations used ?'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vertex_equation','flow equation for each vertex'))
-		string="%s\n%s"%(string,fielddisplay(obj,'element_equation','flow equation for each element'))
-		string="%s\n%s"%(string,fielddisplay(obj,'bordermacayeal','vertices on MacAyeal''s border (for tiling)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'borderpattyn','vertices on Pattyn''s border (for tiling)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'borderstokes','vertices on Stokes'' border (for tiling)'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'ismacayealpattyn','is the macayeal or pattyn approximation used ?'))
+		string="%s\n%s"%(string,fielddisplay(self,'ishutter','is the shallow ice approximation used ?'))
+		string="%s\n%s"%(string,fielddisplay(self,'isl1l2','are l1l2 equations used ?'))
+		string="%s\n%s"%(string,fielddisplay(self,'isstokes','are the Full-Stokes equations used ?'))
+		string="%s\n%s"%(string,fielddisplay(self,'vertex_equation','flow equation for each vertex'))
+		string="%s\n%s"%(string,fielddisplay(self,'element_equation','flow equation for each element'))
+		string="%s\n%s"%(string,fielddisplay(self,'bordermacayeal','vertices on MacAyeal''s border (for tiling)'))
+		string="%s\n%s"%(string,fielddisplay(self,'borderpattyn','vertices on Pattyn''s border (for tiling)'))
+		string="%s\n%s"%(string,fielddisplay(self,'borderstokes','vertices on Stokes'' border (for tiling)'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if DiagnosticHorizAnalysisEnum() in analyses:
+			md = checkfield(md,'flowequation.ismacayealpattyn','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.ishutter','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.isl1l2','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.isstokes','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.bordermacayeal','size',[md.mesh.numberofvertices],'values',[0,1])
+			md = checkfield(md,'flowequation.borderpattyn','size',[md.mesh.numberofvertices],'values',[0,1])
+			md = checkfield(md,'flowequation.borderstokes','size',[md.mesh.numberofvertices],'values',[0,1])
+			if md.mesh.dimension==2:
+				md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[1,2])
+				md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',[1,2])
+			else:
+				md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',range(0,7+1))
+				md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',range(0,7+1))
+			if not (self.ismacayealpattyn or self.ishutter or self.isstokes or self.isl1l2):
+				md.checkmessage("no element types set for this model. At least one of ismacayealpattyn, ishutter or isstokes need to be =1")
+
+		if DiagnosticHutterAnalysisEnum() in analyses:
+			if any(self.element_equation==1):
+				if numpy.any(numpy.logical_and(self.element_equation,md.mask.elementonfloatingice)):
+					print "\n !!! Warning: Hutter's model is not consistent on ice shelves !!!\n"
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','ismacayealpattyn','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','ishutter','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isl1l2','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isstokes','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','bordermacayeal','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','borderpattyn','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','borderstokes','format','DoubleMat','mattype',1)
+		#convert approximations to enums
+		data=self.vertex_equation
+		data[numpy.nonzero(data==0)]=NoneApproximationEnum()
+		data[numpy.nonzero(data==1)]=HutterApproximationEnum()
+		data[numpy.nonzero(data==2)]=MacAyealApproximationEnum()
+		data[numpy.nonzero(data==3)]=PattynApproximationEnum()
+		data[numpy.nonzero(data==4)]=StokesApproximationEnum()
+		data[numpy.nonzero(data==5)]=MacAyealPattynApproximationEnum()
+		data[numpy.nonzero(data==6)]=MacAyealStokesApproximationEnum()
+		data[numpy.nonzero(data==7)]=PattynStokesApproximationEnum()
+		data[numpy.nonzero(data==8)]=L1L2ApproximationEnum()
+		WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1)
+		data=self.element_equation
+		data[numpy.nonzero(data==0)]=NoneApproximationEnum()
+		data[numpy.nonzero(data==1)]=HutterApproximationEnum()
+		data[numpy.nonzero(data==2)]=MacAyealApproximationEnum()
+		data[numpy.nonzero(data==3)]=PattynApproximationEnum()
+		data[numpy.nonzero(data==4)]=StokesApproximationEnum()
+		data[numpy.nonzero(data==5)]=MacAyealPattynApproximationEnum()
+		data[numpy.nonzero(data==6)]=MacAyealStokesApproximationEnum()
+		data[numpy.nonzero(data==7)]=PattynStokesApproximationEnum()
+		data[numpy.nonzero(data==8)]=L1L2ApproximationEnum()
+		WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum(),'format','DoubleMat','mattype',2)
+	# }}}
+
Index: /issm/trunk/src/m/classes/friction.m
===================================================================
--- /issm/trunk/src/m/classes/friction.m	(revision 13394)
+++ /issm/trunk/src/m/classes/friction.m	(revision 13395)
@@ -25,5 +25,5 @@
 
 			%Early return
-			if ~ismember(DiagnosticHorizAnalysisEnum,analyses) & ~ismember(ThermalAnalysisEnum,analyses), return; end
+			if ~ismember(DiagnosticHorizAnalysisEnum(),analyses) & ~ismember(ThermalAnalysisEnum(),analyses), return; end
 
 			md = checkfield(md,'friction.coefficient','NaN',1,'size',[md.mesh.numberofvertices 1]);
Index: /issm/trunk/src/m/classes/friction.py
===================================================================
--- /issm/trunk/src/m/classes/friction.py	(revision 13394)
+++ /issm/trunk/src/m/classes/friction.py	(revision 13395)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class friction:
+class friction(object):
+	"""
+	FRICTION class definition
+
+	   Usage:
+	      friction=friction();
+	"""
+
 	#properties
 	def __init__(self):
@@ -14,16 +24,35 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p"
-		string="%s\n\n%s"%(string,fielddisplay(obj,"coefficient","friction coefficient [SI]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"p","p exponent"))
-		string="%s\n%s"%(string,fielddisplay(obj,"q","q exponent"))
+		string="%s\n\n%s"%(string,fielddisplay(self,"coefficient","friction coefficient [SI]"))
+		string="%s\n%s"%(string,fielddisplay(self,"p","p exponent"))
+		string="%s\n%s"%(string,fielddisplay(self,"q","q exponent"))
 		return string
 		#}}}
 
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if DiagnosticHorizAnalysisEnum() not in analyses and ThermalAnalysisEnum() not in analyses:
+			return md
+
+		md = checkfield(md,'friction.coefficient','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'friction.q','NaN',1,'size',[md.mesh.numberofelements])
+		md = checkfield(md,'friction.p','NaN',1,'size',[md.mesh.numberofelements])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','p','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','q','format','DoubleMat','mattype',2)
+	# }}}
+
Index: /issm/trunk/src/m/classes/geometry.m
===================================================================
--- /issm/trunk/src/m/classes/geometry.m	(revision 13394)
+++ /issm/trunk/src/m/classes/geometry.m	(revision 13395)
@@ -32,5 +32,5 @@
 				md = checkmessage(md,['equality thickness=surface-bed violated']);
 			end 
-			if solution==TransientSolutionEnum & md.transient.isgroundingline,
+			if solution==TransientSolutionEnum() & md.transient.isgroundingline,
 				md = checkfield(md,'geometry.bathymetry','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
@@ -47,8 +47,8 @@
 		end % }}}
 		function marshall(obj,fid) % {{{
-			WriteData(fid,'data',obj.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum);
-			WriteData(fid,'data',obj.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum);
-			WriteData(fid,'data',obj.bed,'format','DoubleMat','mattype',1,'enum',BedEnum);
-			WriteData(fid,'data',obj.bathymetry,'format','DoubleMat','mattype',1,'enum',BathymetryEnum);
+			WriteData(fid,'data',obj.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum());
+			WriteData(fid,'data',obj.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum());
+			WriteData(fid,'data',obj.bed,'format','DoubleMat','mattype',1,'enum',BedEnum());
+			WriteData(fid,'data',obj.bathymetry,'format','DoubleMat','mattype',1,'enum',BathymetryEnum());
 			WriteData(fid,'object',obj,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1);
 		end % }}}
Index: /issm/trunk/src/m/classes/geometry.py
===================================================================
--- /issm/trunk/src/m/classes/geometry.py	(revision 13394)
+++ /issm/trunk/src/m/classes/geometry.py	(revision 13395)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class geometry:
+class geometry(object):
+	"""
+	GEOMETRY class definition
+
+	   Usage:
+	      geometry=geometry();
+	"""
+
 	#properties
 	def __init__(self):
@@ -16,20 +26,41 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 
 		string="   geometry parameters:"
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,'surface','surface elevation'))
-		string="%s\n%s"%(string,fielddisplay(obj,'thickness','ice thickness'))
-		string="%s\n%s"%(string,fielddisplay(obj,'bed','bed elevation'))
-		string="%s\n%s"%(string,fielddisplay(obj,'bathymetry','bathymetry elevation'))
-		string="%s\n%s"%(string,fielddisplay(obj,'hydrostatic_ratio','coefficient for ice shelves'' thickness correction: hydrostatic_ratio H_obs+ (1-hydrostatic_ratio) H_hydro'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'surface','surface elevation'))
+		string="%s\n%s"%(string,fielddisplay(self,'thickness','ice thickness'))
+		string="%s\n%s"%(string,fielddisplay(self,'bed','bed elevation'))
+		string="%s\n%s"%(string,fielddisplay(self,'bathymetry','bathymetry elevation'))
+		string="%s\n%s"%(string,fielddisplay(self,'hydrostatic_ratio','coefficient for ice shelves'' thickness correction: hydrostatic_ratio H_obs+ (1-hydrostatic_ratio) H_hydro'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'geometry.surface'  ,'NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'geometry.bed'      ,'NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices],'>',0)
+		if any((self.thickness-self.surface+self.bed)>10**-9):
+			md.checkmessage("equality thickness=surface-bed violated")
+		if solution==TransientSolutionEnum() and md.transient.isgroundingline:
+			md = checkfield(md,'geometry.bathymetry','NaN',1,'size',[md.mesh.numberofvertices])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'data',self.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum())
+		WriteData(fid,'data',self.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum())
+		WriteData(fid,'data',self.bed,'format','DoubleMat','mattype',1,'enum',BedEnum())
+		WriteData(fid,'data',self.bathymetry,'format','DoubleMat','mattype',1,'enum',BathymetryEnum())
+		WriteData(fid,'object',self,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1)
+	# }}}
+
Index: /issm/trunk/src/m/classes/groundingline.m
===================================================================
--- /issm/trunk/src/m/classes/groundingline.m	(revision 13394)
+++ /issm/trunk/src/m/classes/groundingline.m	(revision 13395)
@@ -36,11 +36,11 @@
 					md = checkmessage(md,['requesting grounding line migration, but bathymetry is absent!']);
 				end
-				pos=find(md.mask.vertexongroundedice); 
+				pos=find(md.mask.vertexongroundedice);
 				if any(abs(md.geometry.bed(pos)-md.geometry.bathymetry(pos))>10^-10),
-					md = checkmessage(md,['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); 
+				pos=find(md.mask.vertexonfloatingice);
 				if any(md.geometry.bathymetry(pos)-md.geometry.bed(pos)>10^-9),
-					md = checkmessage(md,['bathymetry superior to bed on floating ice !']);
+					md = checkmessage(md,['bathymetry superior to bed on floating ice!']);
 				end
 			end
@@ -55,5 +55,5 @@
 		end % }}}
 		function marshall(obj,fid) % {{{
-			WriteData(fid,'data',StringToEnum(obj.migration),'enum',GroundinglineMigrationEnum,'format','Integer');
+			WriteData(fid,'data',StringToEnum(obj.migration),'enum',GroundinglineMigrationEnum(),'format','Integer');
 			WriteData(fid,'object',obj,'fieldname','melting_rate','format','Double');
 		end % }}}
Index: /issm/trunk/src/m/classes/groundingline.py
===================================================================
--- /issm/trunk/src/m/classes/groundingline.py	(revision 13394)
+++ /issm/trunk/src/m/classes/groundingline.py	(revision 13395)
@@ -1,6 +1,19 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import *
+from WriteData import *
+from MatlabFuncs import *
 
-class groundingline:
+class groundingline(object):
+	"""
+	CONSTANTS class definition
+
+	   Usage:
+	      groundingline=groundingline();
+	"""
+
 	#properties
 	def __init__(self):
@@ -13,22 +26,44 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   grounding line solution parameters:'
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,'migration','type of grounding line migration: ''SoftMigration'',''AgressiveMigration'' or ''None'''))
-		string="%s\n%s"%(string,fielddisplay(obj,'melting_rate','melting rate applied when previously grounded parts start floating'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'migration','type of grounding line migration: ''SoftMigration'',''AgressiveMigration'' or ''None'''))
+		string="%s\n%s"%(string,fielddisplay(self,'melting_rate','melting rate applied when previously grounded parts start floating'))
 		return string
 		#}}}	
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 
 		#Type of migration
-		obj.migration='None'
+		self.migration='None'
 
 		#basal melting rate correction: 
-		obj.melting_rate=0;
+		self.melting_rate=0;
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'groundingline.migration','values',['None','AgressiveMigration','SoftMigration'])
+
+		if not strcmp(self.migration,'None'):
+			if numpy.any(numpy.isnan(md.geometry.bathymetry)):
+				md.checkmessage("requesting grounding line migration, but bathymetry is absent!")
+			pos=numpy.nonzero(md.mask.vertexongroundedice)
+			if any(numpy.abs(md.geometry.bed[pos]-md.geometry.bathymetry[pos])>10**-10):
+				md.checkmessage("bathymetry not equal to bed on grounded ice!")
+			pos=numpy.nonzero(md.mask.vertexonfloatingice)
+			if any(md.geometry.bathymetry[pos]-md.geometry.bed[pos]>10**-9):
+				md.checkmessage("bathymetry superior to bed on floating ice!")
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'data',StringToEnum(self.migration)[0],'enum',GroundinglineMigrationEnum(),'format','Integer')
+		WriteData(fid,'object',self,'fieldname','melting_rate','format','Double')
+	# }}}
+
Index: /issm/trunk/src/m/classes/hydrology.m
===================================================================
--- /issm/trunk/src/m/classes/hydrology.m	(revision 13394)
+++ /issm/trunk/src/m/classes/hydrology.m	(revision 13395)
@@ -38,5 +38,5 @@
 
 			%Early return
-			if ~ismember(HydrologyAnalysisEnum,analyses), return; end
+			if ~ismember(HydrologyAnalysisEnum(),analyses), return; end
 
 			md = checkfield(md,'hydrology.spcwatercolumn','forcing',1);
@@ -57,5 +57,5 @@
 		function marshall(obj,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','n','format','Double'); 
+			WriteData(fid,'object',obj,'fieldname','n','format','Double');
 			WriteData(fid,'object',obj,'fieldname','CR','format','Double');
 			WriteData(fid,'object',obj,'fieldname','p','format','Double');
Index: /issm/trunk/src/m/classes/hydrology.py
===================================================================
--- /issm/trunk/src/m/classes/hydrology.py	(revision 13394)
+++ /issm/trunk/src/m/classes/hydrology.py	(revision 13395)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class hydrology:
+class hydrology(object):
+	"""
+	HYDROLOGY class definition
+
+	   Usage:
+	      hydrology=hydrology();
+	"""
+
 	#properties
 	def __init__(self):
@@ -17,34 +27,55 @@
 		self.setdefaultparameters()
 
-	
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		
 		string='   hydrology solution parameters:'
-		string="%s\n\n%s"%(string,fielddisplay(obj,'spcwatercolumn','water thickness constraints (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'n','Manning roughness coefficient'))
-		string="%s\n%s"%(string,fielddisplay(obj,'CR','tortuosity parameter'))
-		string="%s\n%s"%(string,fielddisplay(obj,'p','dimensionless exponent in Manning velocity formula'))
-		string="%s\n%s"%(string,fielddisplay(obj,'q','dimensionless exponent in Manning velocity formula'))
-		string="%s\n%s"%(string,fielddisplay(obj,'kn','parameter in effective pressure formula'))
-		string="%s\n%s"%(string,fielddisplay(obj,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'spcwatercolumn','water thickness constraints (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'n','Manning roughness coefficient'))
+		string="%s\n%s"%(string,fielddisplay(self,'CR','tortuosity parameter'))
+		string="%s\n%s"%(string,fielddisplay(self,'p','dimensionless exponent in Manning velocity formula'))
+		string="%s\n%s"%(string,fielddisplay(self,'q','dimensionless exponent in Manning velocity formula'))
+		string="%s\n%s"%(string,fielddisplay(self,'kn','parameter in effective pressure formula'))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#Parameters from Johnson's 2002 thesis, section 3.5.4			 
-		obj.n=.02			
-		obj.CR=.01
-		obj.p=2
-		obj.q=1
-		obj.kn=0
+		self.n=.02			
+		self.CR=.01
+		self.p=2
+		self.q=1
+		self.kn=0
 
 		#Type of stabilization to use 0:nothing 1:artificial_diffusivity
-		obj.stabilization=1
+		self.stabilization=1
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if HydrologyAnalysisEnum() not in analyses:
+			return md
+
+		md = checkfield(md,'hydrology.spcwatercolumn','forcing',1)
+		md = checkfield(md,'hydrology.stabilization','>=',0)
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','n','format','Double')
+		WriteData(fid,'object',self,'fieldname','CR','format','Double')
+		WriteData(fid,'object',self,'fieldname','p','format','Double')
+		WriteData(fid,'object',self,'fieldname','q','format','Double')
+		WriteData(fid,'object',self,'fieldname','kn','format','Double')
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Double')
+	# }}}
+
Index: /issm/trunk/src/m/classes/initialization.m
===================================================================
--- /issm/trunk/src/m/classes/initialization.m	(revision 13394)
+++ /issm/trunk/src/m/classes/initialization.m	(revision 13395)
@@ -12,4 +12,6 @@
 		pressure      = NaN;
 		temperature   = NaN;
+		surfacetemp   = NaN;
+		basaltemp     = NaN;
 		watercolumn   = NaN;
 		waterfraction = NaN;
@@ -28,18 +30,18 @@
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
-			if ismember(DiagnosticHorizAnalysisEnum,analyses)
-				if ~isnan(md.initialization.vx) & ~isnan(md.initialization.vy),
+			if ismember(DiagnosticHorizAnalysisEnum(),analyses)
+				if ~(isnan(md.initialization.vx) | isnan(md.initialization.vy)),
 					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),
+			if ismember(PrognosticAnalysisEnum(),analyses),
 				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
-			if ismember(HydrologyAnalysisEnum,analyses),
+			if ismember(HydrologyAnalysisEnum(),analyses),
 				md = checkfield(md,'initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
-			if ismember(BalancethicknessAnalysisEnum,analyses),
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
 				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
@@ -49,5 +51,5 @@
 				end
 			end
-			if ismember(ThermalAnalysisEnum,analyses),
+			if ismember(ThermalAnalysisEnum(),analyses),
 				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
@@ -55,5 +57,5 @@
 				md = checkfield(md,'initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
-			if (ismember(EnthalpyAnalysisEnum,analyses) & md.thermal.isenthalpy) | solution==EnthalpySolutionEnum,
+			if (ismember(EnthalpyAnalysisEnum(),analyses) & md.thermal.isenthalpy) | solution==EnthalpySolutionEnum(),
 				md = checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices 1]);
 			end
@@ -68,4 +70,6 @@
 			fielddisplay(obj,'pressure','pressure field');
 			fielddisplay(obj,'temperature','temperature in Kelvins');
+			fielddisplay(obj,'surfacetemp','surface temperature in Kelvins');
+			fielddisplay(obj,'basaltemp','basal temperature in Kelvins');
 			fielddisplay(obj,'watercolumn','thickness of subglacial water');
 			fielddisplay(obj,'waterfraction','fraction of water in the ice');
Index: /issm/trunk/src/m/classes/initialization.py
===================================================================
--- /issm/trunk/src/m/classes/initialization.py	(revision 13394)
+++ /issm/trunk/src/m/classes/initialization.py	(revision 13395)
@@ -1,6 +1,17 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class initialization:
+class initialization(object):
+	"""
+	INITIALIZATION class definition
+
+	   Usage:
+	      initialization=initialization();
+	"""
+
 	#properties
 	def __init__(self):
@@ -20,23 +31,61 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   initial field values:'
 
-		string="%s\n%s"%(string,fielddisplay(obj,'vx','x component of velocity'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vy','y component of velocity'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vz','z component of velocity'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vel','velocity norm'))
-		string="%s\n%s"%(string,fielddisplay(obj,'pressure','pressure field'))
-		string="%s\n%s"%(string,fielddisplay(obj,'temperature','temperature in Kelvins'))
-		string="%s\n%s"%(string,fielddisplay(obj,'watercolumn','thickness of subglacial water'))
-		string="%s\n%s"%(string,fielddisplay(obj,'waterfraction','fraction of water in the ice'))
+		string="%s\n%s"%(string,fielddisplay(self,'vx','x component of velocity'))
+		string="%s\n%s"%(string,fielddisplay(self,'vy','y component of velocity'))
+		string="%s\n%s"%(string,fielddisplay(self,'vz','z component of velocity'))
+		string="%s\n%s"%(string,fielddisplay(self,'vel','velocity norm'))
+		string="%s\n%s"%(string,fielddisplay(self,'pressure','pressure field'))
+		string="%s\n%s"%(string,fielddisplay(self,'temperature','temperature in Kelvins'))
+		string="%s\n%s"%(string,fielddisplay(self,'watercolumn','thickness of subglacial water'))
+		string="%s\n%s"%(string,fielddisplay(self,'waterfraction','fraction of water in the ice'))
 
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		if DiagnosticHorizAnalysisEnum() in analyses:
+			if not numpy.any(numpy.logical_or(numpy.isnan(md.initialization.vx),numpy.isnan(md.initialization.vy))):
+				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
+				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+		if PrognosticAnalysisEnum() in analyses:
+			md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+		if HydrologyAnalysisEnum() in analyses:
+			md = checkfield(md,'initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices])
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+			#Triangle with zero velocity
+			if numpy.any(numpy.logical_and(numpy.sum(numpy.abs(md.initialization.vx[md.mesh.elements.astype(int)-1]),axis=1)==0,\
+			                               numpy.sum(numpy.abs(md.initialization.vy[md.mesh.elements.astype(int)-1]),axis=1)==0)):
+				md.checkmessage("at least one triangle has all its vertices with a zero velocity")
+		if ThermalAnalysisEnum() in analyses:
+			md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'initialization.vz','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices])
+		if (EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy) or solution==EnthalpySolutionEnum():
+			md = checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'data',self.vx,'format','DoubleMat','mattype',1,'enum',VxEnum())
+		WriteData(fid,'data',self.vy,'format','DoubleMat','mattype',1,'enum',VyEnum())
+		WriteData(fid,'data',self.vz,'format','DoubleMat','mattype',1,'enum',VzEnum())
+		WriteData(fid,'data',self.pressure,'format','DoubleMat','mattype',1,'enum',PressureEnum())
+		WriteData(fid,'data',self.temperature,'format','DoubleMat','mattype',1,'enum',TemperatureEnum())
+		WriteData(fid,'data',self.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum())
+		WriteData(fid,'data',self.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum())
+	# }}}
+
Index: /issm/trunk/src/m/classes/inversion.m
===================================================================
--- /issm/trunk/src/m/classes/inversion.m	(revision 13394)
+++ /issm/trunk/src/m/classes/inversion.m	(revision 13395)
@@ -1,3 +1,3 @@
-%CONSTANTS class definition
+%INVERSION class definition
 %
 %   Usage:
@@ -86,9 +86,9 @@
 			md = checkfield(md,'inversion.tao','values',[0 1]);
 			md = checkfield(md,'inversion.incomplete_adjoint','values',[0 1]);
-			md = checkfield(md,'inversion.control_parameters','cell',1,'values',{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'Vx' 'Vy'});
+			md = checkfield(md,'inversion.control_parameters','cell',1,'values',{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'MaterialsRheologyZbar' 'Vx' 'Vy'});
 			md = checkfield(md,'inversion.nsteps','numel',1,'>=',1);
 			md = checkfield(md,'inversion.maxiter_per_step','size',[md.inversion.nsteps 1],'>=',0);
 			md = checkfield(md,'inversion.step_threshold','size',[md.inversion.nsteps 1]);
-			md = checkfield(md,'inversion.cost_functions','size',[md.inversion.nsteps num_costfunc],'values',[101:105 201 501:503]);
+			md = checkfield(md,'inversion.cost_functions','size',[md.inversion.nsteps num_costfunc],'values',[101:105 201 501:505]);
 			md = checkfield(md,'inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
 			md = checkfield(md,'inversion.gradient_only','values',[0 1]);
@@ -97,5 +97,5 @@
 			md = checkfield(md,'inversion.max_parameters','size',[md.mesh.numberofvertices num_controls]);
 
-			if solution==BalancethicknessSolutionEnum
+			if solution==BalancethicknessSolutionEnum()
 				md = checkfield(md,'inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
 			else
@@ -159,21 +159,23 @@
 				data(i)=StringToEnum(obj.control_parameters{i});
 			end
-			WriteData(fid,'data',data,'enum',InversionControlParametersEnum,'format','DoubleMat','mattype',3);
-			WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum,'format','Integer');
+			WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer');
 
 			%process cost functions
 			num_cost_functions=size(obj.cost_functions,2);
 			data=obj.cost_functions;
-			pos=find(data==101); data(pos)=SurfaceAbsVelMisfitEnum;
-			pos=find(data==102); data(pos)=SurfaceRelVelMisfitEnum;
-			pos=find(data==103); data(pos)=SurfaceLogVelMisfitEnum;
-			pos=find(data==104); data(pos)=SurfaceLogVxVyMisfitEnum;
-			pos=find(data==105); data(pos)=SurfaceAverageVelMisfitEnum;
-			pos=find(data==201); data(pos)=ThicknessAbsMisfitEnum;
-			pos=find(data==501); data(pos)=DragCoefficientAbsGradientEnum;
-			pos=find(data==502); data(pos)=RheologyBbarAbsGradientEnum;
-			pos=find(data==503); data(pos)=ThicknessAbsGradientEnum;
-			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum,'format','DoubleMat','mattype',3);
-			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum,'format','Integer');
+			pos=find(data==101); data(pos)=SurfaceAbsVelMisfitEnum();
+			pos=find(data==102); data(pos)=SurfaceRelVelMisfitEnum();
+			pos=find(data==103); data(pos)=SurfaceLogVelMisfitEnum();
+			pos=find(data==104); data(pos)=SurfaceLogVxVyMisfitEnum();
+			pos=find(data==105); data(pos)=SurfaceAverageVelMisfitEnum();
+			pos=find(data==201); data(pos)=ThicknessAbsMisfitEnum();
+			pos=find(data==501); data(pos)=DragCoefficientAbsGradientEnum();
+			pos=find(data==502); data(pos)=RheologyBbarAbsGradientEnum();
+			pos=find(data==503); data(pos)=ThicknessAbsGradientEnum();
+			pos=find(data==504); data(pos)=ThicknessAlongGradientEnum();
+			pos=find(data==505); data(pos)=ThicknessAcrossGradientEnum();
+			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/inversion.py
===================================================================
--- /issm/trunk/src/m/classes/inversion.py	(revision 13394)
+++ /issm/trunk/src/m/classes/inversion.py	(revision 13395)
@@ -1,6 +1,18 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import *
+from WriteData import *
 
-class inversion:
+class inversion(object):
+	"""
+	INVERSION class definition
+
+	   Usage:
+	      inversion=inversion();
+	"""
+
 	#properties
 	def __init__(self):
@@ -25,25 +37,29 @@
 		self.vel_obs                     = float('NaN')
 		self.thickness_obs               = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='\n   Inversion parameters:'
-		string="%s\n%s"%(string,fielddisplay(obj,'iscontrol','is inversion activated?'))
-		string="%s\n%s"%(string,fielddisplay(obj,'incomplete_adjoint','do we assume linear viscosity?'))
-		string="%s\n%s"%(string,fielddisplay(obj,'control_parameters','parameter where inverse control is carried out; ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}'))
-		string="%s\n%s"%(string,fielddisplay(obj,'nsteps','number of optimization searches'))
-		string="%s\n%s"%(string,fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step'))
-		string="%s\n%s"%(string,fielddisplay(obj,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter'))
-		string="%s\n%s"%(string,fielddisplay(obj,'cost_function_threshold','misfit convergence criterion. Default is 1%, NaN if not applied'))
-		string="%s\n%s"%(string,fielddisplay(obj,'maxiter_per_step','maximum iterations during each optimization step'))
-		string="%s\n%s"%(string,fielddisplay(obj,'gradient_scaling','scaling factor on gradient direction during optimization, for each optimization step'))
-		string="%s\n%s"%(string,fielddisplay(obj,'step_threshold','decrease threshold for misfit, default is 30%'))
-		string="%s\n%s"%(string,fielddisplay(obj,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex'))
-		string="%s\n%s"%(string,fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex'))
-		string="%s\n%s"%(string,fielddisplay(obj,'gradient_only','stop control method solution at gradient'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vx_obs','observed velocity x component [m/a]'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vy_obs','observed velocity y component [m/a]'))
-		string="%s\n%s"%(string,fielddisplay(obj,'vel_obs','observed velocity magnitude [m/a]'))
-		string="%s\n%s"%(string,fielddisplay(obj,'thickness_obs','observed thickness [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'iscontrol','is inversion activated?'))
+		string="%s\n%s"%(string,fielddisplay(self,'incomplete_adjoint','do we assume linear viscosity?'))
+		string="%s\n%s"%(string,fielddisplay(self,'control_parameters','parameter where inverse control is carried out; ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}'))
+		string="%s\n%s"%(string,fielddisplay(self,'nsteps','number of optimization searches'))
+		string="%s\n%s"%(string,fielddisplay(self,'cost_functions','indicate the type of response for each optimization step'))
+		string="%s\n%s"%(string,fielddisplay(self,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter'))
+		string="%s\n%s"%(string,fielddisplay(self,'cost_function_threshold','misfit convergence criterion. Default is 1%, NaN if not applied'))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter_per_step','maximum iterations during each optimization step'))
+		string="%s\n%s"%(string,fielddisplay(self,'gradient_scaling','scaling factor on gradient direction during optimization, for each optimization step'))
+		string="%s\n%s"%(string,fielddisplay(self,'step_threshold','decrease threshold for misfit, default is 30%'))
+		string="%s\n%s"%(string,fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex'))
+		string="%s\n%s"%(string,fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex'))
+		string="%s\n%s"%(string,fielddisplay(self,'gradient_only','stop control method solution at gradient'))
+		string="%s\n%s"%(string,fielddisplay(self,'vx_obs','observed velocity x component [m/a]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vy_obs','observed velocity y component [m/a]'))
+		string="%s\n%s"%(string,fielddisplay(self,'vel_obs','observed velocity magnitude [m/a]'))
+		string="%s\n%s"%(string,fielddisplay(self,'thickness_obs','observed thickness [m]'))
 		string="%s\n%s"%(string,'Available cost functions:')
 		string="%s\n%s"%(string,'   101: SurfaceAbsVelMisfit')
@@ -59,20 +75,19 @@
 		#}}}
 
-	def setdefaultparameters(obj):
-		# {{{setdefaultparameters
+	def setdefaultparameters(self): # {{{
 		
 		#default is incomplete adjoint for now
-		obj.incomplete_adjoint=1
+		self.incomplete_adjoint=1
 
 		#parameter to be inferred by control methods (only
 		#drag and B are supported yet)
-		obj.control_parameters=['FrictionCoefficient']
+		self.control_parameters='FrictionCoefficient'
 
 		#number of steps in the control methods
-		obj.nsteps=20
+		self.nsteps=20
 
 		#maximum number of iteration in the optimization algorithm for
 		#each step
-		obj.maxiter_per_step=20*ones(obj.nsteps)
+		self.maxiter_per_step=20*numpy.ones(self.nsteps)
 
 		#the inversed parameter is updated as follows:
@@ -81,24 +96,100 @@
 		#inversed parameter (10^8 for B, 50 for drag) and can be decreased
 		#after the first iterations
-		obj.gradient_scaling=50*ones(obj.nsteps)
+		self.gradient_scaling=50*numpy.ones(self.nsteps)
 
 		#several responses can be used:
-		obj.cost_functions=101*ones(obj.nsteps)
+		self.cost_functions=101*numpy.ones(self.nsteps)
 
 		#step_threshold is used to speed up control method. When
-		#misfit(1)/misfit(0) < obj.step_threshold, we go directly to
+		#misfit(1)/misfit(0) < self.step_threshold, we go directly to
 		#the next step
-		obj.step_threshold=.7*ones(obj.nsteps) #30 per cent decrement
+		self.step_threshold=.7*numpy.ones(self.nsteps) #30 per cent decrement
 
 		#stop control solution at the gradient computation and return it? 
-		obj.gradient_only=0
+		self.gradient_only=0
 
 		#cost_function_threshold is a criteria to stop the control methods.
 		#if J[n]-J[n-1]/J[n] < criteria, the control run stops
 		#NaN if not applied
-		obj.cost_function_threshold=NaN #not activated 
+		self.cost_function_threshold=float('NaN')    #not activated 
 
-		return obj
-		#}}}
+		return self
+	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
 
+		#Early return
+		if not self.iscontrol:
+			return md
+
+		num_controls=numpy.size(md.inversion.control_parameters)
+		num_costfunc=numpy.size(md.inversion.cost_functions,1)
+
+		md = checkfield(md,'inversion.iscontrol','values',[0,1])
+		md = checkfield(md,'inversion.tao','values',[0,1])
+		md = checkfield(md,'inversion.incomplete_adjoint','values',[0,1])
+		md = checkfield(md,'inversion.control_parameters','cell',1,'values',['BalancethicknessThickeningRate','FrictionCoefficient','MaterialsRheologyBbar','Vx','Vy'])
+		md = checkfield(md,'inversion.nsteps','numel',[1],'>=',1)
+		md = checkfield(md,'inversion.maxiter_per_step','size',[md.inversion.nsteps],'>=',0)
+		md = checkfield(md,'inversion.step_threshold','size',[md.inversion.nsteps])
+		md = checkfield(md,'inversion.cost_functions','size',[md.inversion.nsteps,num_costfunc],'values',[101,102,103,104,105,201,501,502,503,504,505])
+		md = checkfield(md,'inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices,num_costfunc],'>=',0)
+		md = checkfield(md,'inversion.gradient_only','values',[0,1])
+		md = checkfield(md,'inversion.gradient_scaling','size',[md.inversion.nsteps,num_controls])
+		md = checkfield(md,'inversion.min_parameters','size',[md.mesh.numberofvertices,num_controls])
+		md = checkfield(md,'inversion.max_parameters','size',[md.mesh.numberofvertices,num_controls])
+
+		if solution==BalancethicknessSolutionEnum():
+			md = checkfield(md,'inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1)
+		else:
+			md = checkfield(md,'inversion.vx_obs','size',[md.mesh.numberofvertices],'NaN',1)
+			md = checkfield(md,'inversion.vy_obs','size',[md.mesh.numberofvertices],'NaN',1)
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+
+		WriteData(fid,'object',self,'fieldname','iscontrol','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','tao','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','incomplete_adjoint','format','Boolean')
+		if not self.iscontrol:
+			return
+		WriteData(fid,'object',self,'fieldname','nsteps','format','Integer')
+		WriteData(fid,'object',self,'fieldname','maxiter_per_step','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','gradient_scaling','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','cost_function_threshold','format','Double')
+		WriteData(fid,'object',self,'fieldname','min_parameters','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','max_parameters','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','step_threshold','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','gradient_only','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','vx_obs','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','vy_obs','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','vz_obs','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','thickness_obs','format','DoubleMat','mattype',1)
+
+		#process control parameters
+		num_control_parameters=numpy.size(self.control_parameters)
+		data=[StringToEnum(self.control_parameters[i])[0] for i in xrange(0,num_control_parameters)]
+		WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3)
+		WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer')
+
+		#process cost functions
+		num_cost_functions=size(self.cost_functions,1)
+		data=self.cost_functions
+		data[numpy.nonzero(data==101)]=SurfaceAbsVelMisfitEnum()
+		data[numpy.nonzero(data==102)]=SurfaceRelVelMisfitEnum()
+		data[numpy.nonzero(data==103)]=SurfaceLogVelMisfitEnum()
+		data[numpy.nonzero(data==104)]=SurfaceLogVxVyMisfitEnum()
+		data[numpy.nonzero(data==105)]=SurfaceAverageVelMisfitEnum()
+		data[numpy.nonzero(data==201)]=ThicknessAbsMisfitEnum()
+		data[numpy.nonzero(data==501)]=DragCoefficientAbsGradientEnum()
+		data[numpy.nonzero(data==502)]=RheologyBbarAbsGradientEnum()
+		data[numpy.nonzero(data==503)]=ThicknessAbsGradientEnum()
+		data[numpy.nonzero(data==504)]=ThicknessAlongGradientEnum()
+		data[numpy.nonzero(data==505)]=ThicknessAcrossGradientEnum()
+		WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)
+		WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')
+	# }}}
+
Index: /issm/trunk/src/m/classes/mask.py
===================================================================
--- /issm/trunk/src/m/classes/mask.py	(revision 13394)
+++ /issm/trunk/src/m/classes/mask.py	(revision 13395)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class mask:
+class mask(object):
+	"""
+	MASK class definition
+
+	   Usage:
+	      mask=mask();
+	"""
+
 	#properties
 	def __init__(self):
@@ -17,20 +27,41 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 
 		string="";
-		string="%s\n%s"%(string,fielddisplay(obj,"elementonfloatingice","element on floating ice flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexonfloatingice","vertex on floating ice flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"elementongroundedice","element on grounded ice  list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexongroundedice","vertex on grounded ice flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"elementonwater","element on water flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexonwater","vertex on water flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementonfloatingice","element on floating ice flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonfloatingice","vertex on floating ice flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementongroundedice","element on grounded ice  list"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexongroundedice","vertex on grounded ice flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementonwater","element on water flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonwater","vertex on water flags list"))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'mask.elementonfloatingice','size',[md.mesh.numberofelements],'values',[0,1])
+		md = checkfield(md,'mask.elementongroundedice','size',[md.mesh.numberofelements],'values',[0,1])
+		md = checkfield(md,'mask.elementonwater'      ,'size',[md.mesh.numberofelements],'values',[0,1])
+		md = checkfield(md,'mask.vertexonfloatingice' ,'size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'mask.vertexongroundedice' ,'size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'mask.vertexonwater'       ,'size',[md.mesh.numberofvertices],'values',[0,1])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','elementonfloatingice','format','BooleanMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','elementongroundedice','format','BooleanMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','elementonwater','format','BooleanMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','vertexonfloatingice','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','vertexongroundedice','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','vertexonwater','format','DoubleMat','mattype',1)
+	# }}}
+
Index: /issm/trunk/src/m/classes/matdamageice.m
===================================================================
--- /issm/trunk/src/m/classes/matdamageice.m	(revision 13395)
+++ /issm/trunk/src/m/classes/matdamageice.m	(revision 13395)
@@ -0,0 +1,130 @@
+%MATDAMAGEICE class definition
+%
+%   Usage:
+%      matdamageice=matdamageice();
+
+classdef matdamageice
+	properties (SetAccess=public) 
+		rho_ice                    = 0.;
+		rho_water                  = 0.;
+		rho_freshwater             = 0.;
+		mu_water                   = 0.;
+		heatcapacity               = 0.;
+		latentheat                 = 0.;
+		thermalconductivity        = 0.;
+		meltingpoint               = 0.;
+		beta                       = 0.;
+		mixed_layer_capacity       = 0.;
+		thermal_exchange_velocity  = 0.;
+		rheology_B   = NaN;
+		rheology_n   = NaN;
+		rheology_Z   = NaN;
+		rheology_law = '';
+	end
+	methods
+		function obj = matdamageice(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('matdamageice');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%ice density (kg/m^3)
+			obj.rho_ice=917.;
+
+			%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)
+			obj.mu_water=0.001787;  
+
+			%ice heat capacity cp (J/kg/K)
+			obj.heatcapacity=2093.;
+
+			%ice latent heat of fusion L (J/kg)
+			obj.latentheat=3.34*10^5;
+
+			%ice thermal conductivity (W/m/K)
+			obj.thermalconductivity=2.4;
+
+			%the melting point of ice at 1 atmosphere of pressure in K
+			obj.meltingpoint=273.15;
+
+			%rate of change of melting point with pressure (K/Pa)
+			obj.beta=9.8*10^-8;
+
+			%mixed layer (ice-water interface) heat capacity (J/kg/K)
+			obj.mixed_layer_capacity=3974.;
+
+			%thermal exchange velocity (ice-water interface) (m/s)
+			obj.thermal_exchange_velocity=1.00*10^-4;
+
+			%Rheology law: what is the temperature dependence of B with T
+			%available: none, paterson and arrhenius
+			obj.rheology_law='Paterson';
+		end % }}}
+		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_Z','>',0,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'materials.rheology_law','values',{'None' 'Paterson' 'Arrhenius'});
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Materials:\n'));
+
+			fielddisplay(obj,'rho_ice','ice density [kg/m^3]');
+			fielddisplay(obj,'rho_water','ocean water density [kg/m^3]');
+			fielddisplay(obj,'rho_freshwater','fresh water density [kg/m^3]');
+			fielddisplay(obj,'mu_water','water viscosity [N s/m^2]');
+			fielddisplay(obj,'heatcapacity','heat capacity [J/kg/K]');
+			fielddisplay(obj,'thermalconductivity','ice thermal conductivity [W/m/K]');
+			fielddisplay(obj,'meltingpoint','melting point of ice at 1atm in K');
+			fielddisplay(obj,'latentheat','latent heat of fusion [J/m^3]');
+			fielddisplay(obj,'beta','rate of change of melting point with pressure [K/Pa]');
+			fielddisplay(obj,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
+			fielddisplay(obj,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
+			fielddisplay(obj,'rheology_B','flow law parameter [Pa/s^(1/n)]');
+			fielddisplay(obj,'rheology_n','Glen''s flow law exponent');
+			fielddisplay(obj,'rheology_Z','rheology multiplier');
+			fielddisplay(obj,'rheology_law','law for the temperature dependance of the rheology: ''None'', ''Paterson'' or ''Arrhenius''');
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'enum',MaterialsEnum(),'data',MatdamageiceEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rho_ice','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rho_water','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rho_freshwater','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','mu_water','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','heatcapacity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','latentheat','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','thermalconductivity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','meltingpoint','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','beta','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','mixed_layer_capacity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','thermal_exchange_velocity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_Z','format','DoubleMat','mattype',1);
+			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum(),'format','Integer');
+		end % }}}
+	end
+end
Index: sm/trunk/src/m/classes/materials.m
===================================================================
--- /issm/trunk/src/m/classes/materials.m	(revision 13394)
+++ 	(revision )
@@ -1,115 +1,0 @@
-%MATERIALS class definition
-%
-%   Usage:
-%      materials=materials();
-
-classdef materials
-	properties (SetAccess=public) 
-		rho_ice                    = 0;
-		rho_water                  = 0;
-		rho_freshwater             = 0;
-		mu_water                   = 0;
-		heatcapacity               = 0;
-		latentheat                 = 0;
-		thermalconductivity        = 0;
-		meltingpoint               = 0;
-		beta                       = 0;
-		mixed_layer_capacity       = 0;
-		thermal_exchange_velocity  = 0;
-		rheology_B   = NaN;
-		rheology_n   = NaN;
-		rheology_law = '';
-	end
-	methods
-		function obj = materials(varargin) % {{{
-			switch nargin
-				case 0
-					obj=setdefaultparameters(obj);
-				otherwise
-					error('constructor not supported');
-			end
-		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
-
-			%ice density (kg/m^3)
-			obj.rho_ice=917;
-
-			%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)
-			obj.mu_water=0.001787;  
-
-			%ice heat capacity cp (J/kg/K)
-			obj.heatcapacity=2093;
-
-			%ice latent heat of fusion L (J/kg)
-			obj.latentheat=3.34*10^5;
-
-			%ice thermal conductivity (W/m/K)
-			obj.thermalconductivity=2.4;
-
-			%the melting point of ice at 1 atmosphere of pressure in K
-			obj.meltingpoint=273.15;
-
-			%rate of change of melting point with pressure (K/Pa)
-			obj.beta=9.8*10^-8;
-
-			%mixed layer (ice-water interface) heat capacity (J/kg/K)
-			obj.mixed_layer_capacity=3974;
-
-			%thermal exchange velocity (ice-water interface) (m/s)
-			obj.thermal_exchange_velocity=1.00*10^-4;
-
-			%Rheology law: what is the temperature dependence of B with T
-			%available: none, paterson and arrhenius
-			obj.rheology_law='Paterson';
-		end % }}}
-		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) % {{{
-			disp(sprintf('   Materials:\n'));
-
-			fielddisplay(obj,'rho_ice','ice density [kg/m^3]');
-			fielddisplay(obj,'rho_water','ocean water density [kg/m^3]');
-			fielddisplay(obj,'rho_freshwater','fresh water density [kg/m^3]');
-			fielddisplay(obj,'mu_water','water viscosity [N s/m^2]');
-			fielddisplay(obj,'heatcapacity','heat capacity [J/kg/K]');
-			fielddisplay(obj,'thermalconductivity','ice thermal conductivity [W/m/K]');
-			fielddisplay(obj,'meltingpoint','melting point of ice at 1atm in K');
-			fielddisplay(obj,'latentheat','latent heat of fusion [J/m^3]');
-			fielddisplay(obj,'beta','rate of change of melting point with pressure [K/Pa]');
-			fielddisplay(obj,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
-			fielddisplay(obj,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
-			fielddisplay(obj,'rheology_B','flow law parameter [Pa/s^(1/n)]');
-			fielddisplay(obj,'rheology_n','Glen''s flow law exponent');
-			fielddisplay(obj,'rheology_law','law for the temperature dependance of the rheology: ''None'', ''Paterson'' or ''Arrhenius''');
-		end % }}}
-		function marshall(obj,fid) % {{{
-			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');
-			WriteData(fid,'object',obj,'fieldname','latentheat','format','Double');
-			WriteData(fid,'object',obj,'fieldname','thermalconductivity','format','Double');
-			WriteData(fid,'object',obj,'fieldname','meltingpoint','format','Double');
-			WriteData(fid,'object',obj,'fieldname','beta','format','Double');
-			WriteData(fid,'object',obj,'fieldname','mixed_layer_capacity','format','Double');
-			WriteData(fid,'object',obj,'fieldname','thermal_exchange_velocity','format','Double');
-			WriteData(fid,'object',obj,'fieldname','rheology_B','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','rheology_n','format','DoubleMat','mattype',2);
-			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum,'format','Integer');
-		end % }}}
-	end
-end
Index: sm/trunk/src/m/classes/materials.py
===================================================================
--- /issm/trunk/src/m/classes/materials.py	(revision 13394)
+++ 	(revision )
@@ -1,80 +1,0 @@
-#module imports
-from fielddisplay import fielddisplay
-
-class materials:
-	#properties
-	def __init__(self):
-		# {{{ Properties
-		self.rho_ice                    = 0;
-		self.rho_water                  = 0;
-		self.mu_water                   = 0;
-		self.heatcapacity               = 0;
-		self.latentheat                 = 0;
-		self.thermalconductivity        = 0;
-		self.meltingpoint               = 0;
-		self.beta                       = 0;
-		self.mixed_layer_capacity       = 0;
-		self.thermal_exchange_velocity  = 0;
-		self.rheology_B   = float('NaN')
-		self.rheology_n   = float('NaN')
-		self.rheology_law = "";
-
-		self.setdefaultparameters()
-		#}}}
-	def __repr__(obj):
-		# {{{ Display
-		string="   Materials:"
-
-		string="%s\n\n%s"%(string,fielddisplay(obj,"rho_ice","ice density [kg/m^3]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"rho_water","water density [kg/m^3]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"mu_water","water viscosity [N s/m^2]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"heatcapacity","heat capacity [J/kg/K]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"thermalconductivity","ice thermal conductivity [W/m/K]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"meltingpoint","melting point of ice at 1atm in K"))
-		string="%s\n%s"%(string,fielddisplay(obj,"latentheat","latent heat of fusion [J/m^3]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"beta","rate of change of melting point with pressure [K/Pa]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"mixed_layer_capacity","mixed layer capacity [W/kg/K]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"thermal_exchange_velocity","thermal exchange velocity [m/s]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"rheology_B","flow law parameter [Pa/s^(1/n)]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"rheology_n","Glen""s flow law exponent"))
-		string="%s\n%s"%(string,fielddisplay(obj,"rheology_law","law for the temperature dependance of the rheology: ""None"", ""Paterson"" or ""Arrhenius"""))
-
-		return string
-		#}}}
-	def setdefaultparameters(obj):
-		# {{{setdefaultparameters
-		#ice density (kg/m^3)
-		obj.rho_ice=917
-
-		#water density (kg/m^3)
-		obj.rho_water=1023
-
-		#water viscosity (N.s/m^2)
-		obj.mu_water=0.001787  
-
-		#ice heat capacity cp (J/kg/K)
-		obj.heatcapacity=2093
-
-		#ice latent heat of fusion L (J/kg)
-		obj.latentheat=3.34*10**5
-
-		#ice thermal conductivity (W/m/K)
-		obj.thermalconductivity=2.4
-
-		#the melting point of ice at 1 atmosphere of pressure in K
-		obj.meltingpoint=273.15
-
-		#rate of change of melting point with pressure (K/Pa)
-		obj.beta=9.8*10**-8
-
-		#mixed layer (ice-water interface) heat capacity (J/kg/K)
-		obj.mixed_layer_capacity=3974
-
-		#thermal exchange velocity (ice-water interface) (m/s)
-		obj.thermal_exchange_velocity=1.00*10**-4
-
-		#Rheology law: what is the temperature dependence of B with T
-		#available: none, paterson and arrhenius
-		obj.rheology_law='Paterson'
-		return obj
-		#}}}
Index: /issm/trunk/src/m/classes/matice.m
===================================================================
--- /issm/trunk/src/m/classes/matice.m	(revision 13395)
+++ /issm/trunk/src/m/classes/matice.m	(revision 13395)
@@ -0,0 +1,126 @@
+%MATICE class definition
+%
+%   Usage:
+%      matice=matice();
+
+classdef matice
+	properties (SetAccess=public) 
+		rho_ice                    = 0.;
+		rho_water                  = 0.;
+		rho_freshwater             = 0.;
+		mu_water                   = 0.;
+		heatcapacity               = 0.;
+		latentheat                 = 0.;
+		thermalconductivity        = 0.;
+		meltingpoint               = 0.;
+		beta                       = 0.;
+		mixed_layer_capacity       = 0.;
+		thermal_exchange_velocity  = 0.;
+		rheology_B   = NaN;
+		rheology_n   = NaN;
+		rheology_law = '';
+	end
+	methods
+		function obj = matice(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('matice');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%ice density (kg/m^3)
+			obj.rho_ice=917.;
+
+			%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)
+			obj.mu_water=0.001787;  
+
+			%ice heat capacity cp (J/kg/K)
+			obj.heatcapacity=2093.;
+
+			%ice latent heat of fusion L (J/kg)
+			obj.latentheat=3.34*10^5;
+
+			%ice thermal conductivity (W/m/K)
+			obj.thermalconductivity=2.4;
+
+			%the melting point of ice at 1 atmosphere of pressure in K
+			obj.meltingpoint=273.15;
+
+			%rate of change of melting point with pressure (K/Pa)
+			obj.beta=9.8*10^-8;
+
+			%mixed layer (ice-water interface) heat capacity (J/kg/K)
+			obj.mixed_layer_capacity=3974.;
+
+			%thermal exchange velocity (ice-water interface) (m/s)
+			obj.thermal_exchange_velocity=1.00*10^-4;
+
+			%Rheology law: what is the temperature dependence of B with T
+			%available: none, paterson and arrhenius
+			obj.rheology_law='Paterson';
+		end % }}}
+		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) % {{{
+			disp(sprintf('   Materials:\n'));
+
+			fielddisplay(obj,'rho_ice','ice density [kg/m^3]');
+			fielddisplay(obj,'rho_water','ocean water density [kg/m^3]');
+			fielddisplay(obj,'rho_freshwater','fresh water density [kg/m^3]');
+			fielddisplay(obj,'mu_water','water viscosity [N s/m^2]');
+			fielddisplay(obj,'heatcapacity','heat capacity [J/kg/K]');
+			fielddisplay(obj,'thermalconductivity','ice thermal conductivity [W/m/K]');
+			fielddisplay(obj,'meltingpoint','melting point of ice at 1atm in K');
+			fielddisplay(obj,'latentheat','latent heat of fusion [J/m^3]');
+			fielddisplay(obj,'beta','rate of change of melting point with pressure [K/Pa]');
+			fielddisplay(obj,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
+			fielddisplay(obj,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
+			fielddisplay(obj,'rheology_B','flow law parameter [Pa/s^(1/n)]');
+			fielddisplay(obj,'rheology_n','Glen''s flow law exponent');
+			fielddisplay(obj,'rheology_law','law for the temperature dependance of the rheology: ''None'', ''Paterson'' or ''Arrhenius''');
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'enum',MaterialsEnum(),'data',MaticeEnum(),'format','Integer');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rho_ice','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rho_water','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rho_freshwater','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','mu_water','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','heatcapacity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','latentheat','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','thermalconductivity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','meltingpoint','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','beta','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','mixed_layer_capacity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','thermal_exchange_velocity','format','Double');
+			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2);
+			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum(),'format','Integer');
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/matice.py
===================================================================
--- /issm/trunk/src/m/classes/matice.py	(revision 13395)
+++ /issm/trunk/src/m/classes/matice.py	(revision 13395)
@@ -0,0 +1,126 @@
+#module imports
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import *
+from WriteData import *
+
+class matice(object):
+	"""
+	MATERIALS class definition
+
+	   Usage:
+	      matice=matice();
+	"""
+
+	#properties
+	def __init__(self):
+		# {{{ Properties
+		self.rho_ice                    = 0.
+		self.rho_water                  = 0.
+		self.rho_freshwater             = 0.
+		self.mu_water                   = 0.
+		self.heatcapacity               = 0.
+		self.latentheat                 = 0.
+		self.thermalconductivity        = 0.
+		self.meltingpoint               = 0.
+		self.beta                       = 0.
+		self.mixed_layer_capacity       = 0.
+		self.thermal_exchange_velocity  = 0.
+		self.rheology_B   = float('NaN')
+		self.rheology_n   = float('NaN')
+		self.rheology_law = ''
+
+		self.setdefaultparameters()
+		#}}}
+	def __repr__(self):
+		# {{{ Display
+		string="   Materials:"
+
+		string="%s\n\n%s"%(string,fielddisplay(self,"rho_ice","ice density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rho_water","water density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rho_freshwater","fresh water density [kg/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mu_water","water viscosity [N s/m^2]"))
+		string="%s\n%s"%(string,fielddisplay(self,"heatcapacity","heat capacity [J/kg/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"thermalconductivity","ice thermal conductivity [W/m/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"meltingpoint","melting point of ice at 1atm in K"))
+		string="%s\n%s"%(string,fielddisplay(self,"latentheat","latent heat of fusion [J/m^3]"))
+		string="%s\n%s"%(string,fielddisplay(self,"beta","rate of change of melting point with pressure [K/Pa]"))
+		string="%s\n%s"%(string,fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]"))
+		string="%s\n%s"%(string,fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa/s^(1/n)]"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_n","Glen's flow law exponent"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'Paterson' or 'Arrhenius'"))
+
+		return string
+		#}}}
+	def setdefaultparameters(self):
+		# {{{setdefaultparameters
+		#ice density (kg/m^3)
+		self.rho_ice=917.
+
+		#ocean water density (kg/m^3)
+		self.rho_water=1023.
+
+		#fresh water density (kg/m^3)
+		self.rho_freshwater=1000.
+
+		#water viscosity (N.s/m^2)
+		self.mu_water=0.001787  
+
+		#ice heat capacity cp (J/kg/K)
+		self.heatcapacity=2093.
+
+		#ice latent heat of fusion L (J/kg)
+		self.latentheat=3.34*10**5
+
+		#ice thermal conductivity (W/m/K)
+		self.thermalconductivity=2.4
+
+		#the melting point of ice at 1 atmosphere of pressure in K
+		self.meltingpoint=273.15
+
+		#rate of change of melting point with pressure (K/Pa)
+		self.beta=9.8*10**-8
+
+		#mixed layer (ice-water interface) heat capacity (J/kg/K)
+		self.mixed_layer_capacity=3974.
+
+		#thermal exchange velocity (ice-water interface) (m/s)
+		self.thermal_exchange_velocity=1.00*10**-4
+
+		#Rheology law: what is the temperature dependence of B with T
+		#available: none, paterson and arrhenius
+		self.rheology_law='Paterson'
+		return self
+		#}}}
+
+	def checkconsistency(self,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])
+		md = checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements])
+		md = checkfield(md,'materials.rheology_law','values',['None','Paterson','Arrhenius'])
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'enum',MaterialsEnum(),'data',MaticeEnum(),'format','Integer');
+		WriteData(fid,'object',self,'class','materials','fieldname','rho_ice','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','rho_water','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','rho_freshwater','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','mu_water','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','heatcapacity','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','latentheat','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','thermalconductivity','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','meltingpoint','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','beta','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)
+		WriteData(fid,'data',StringToEnum(self.rheology_law)[0],'enum',MaterialsRheologyLawEnum(),'format','Integer')
+	# }}}
+
Index: /issm/trunk/src/m/classes/mesh.m
===================================================================
--- /issm/trunk/src/m/classes/mesh.m	(revision 13394)
+++ /issm/trunk/src/m/classes/mesh.m	(revision 13395)
@@ -57,5 +57,5 @@
 		function obj = setdefaultparameters(obj) % {{{
 
-			%the connectivity is the avergaded number of nodes linked to a
+			%the connectivity is the averaged number of nodes linked to a
 			%given node through an edge. This connectivity is used to initially
 			%allocate memory to the stiffness matrix. A value of 16 seems to
@@ -87,4 +87,8 @@
 			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==3),
+				md = checkfield(md,'mesh.z','>=',md.geometry.bed-10^-10,'message','''mesh.z'' lower than bedrock');
+				md = checkfield(md,'mesh.z','<=',md.geometry.surface+10^-10,'message','''mesh.z'' higher than surface elevation');
+			end
 			if (md.mesh.dimension==2),
 				md = checkfield(md,'mesh.average_vertex_connectivity','>=',9,'message','''mesh.average_vertex_connectivity'' should be at least 9 in 2d');
@@ -96,5 +100,5 @@
 			%Solution specific checks
 			switch(solution),
-				case PrognosticSolutionEnum,
+				case PrognosticSolutionEnum(),
 					if md.prognostic.stabilization==3,
 						md = checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
@@ -102,5 +106,5 @@
 						md = checkfield(md,'mesh.edges(:,1:3)','>',0);
 					end
-				case BalancethicknessSolutionEnum,
+				case BalancethicknessSolutionEnum(),
 					if md.balancethickness.stabilization==3,
 						md = checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
@@ -108,5 +112,5 @@
 						md = checkfield(md,'mesh.edges(:,1:3)','>',0);
 					end
-				case TransientSolutionEnum,
+				case TransientSolutionEnum(),
 					if md.transient.isprognostic & md.prognostic.stabilization==3,
 						md = checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
@@ -114,5 +118,5 @@
 						md = checkfield(md,'mesh.edges(:,1:3)','>',0);
 					end
-				case ThermalSolutionEnum,
+				case ThermalSolutionEnum(),
 					md = checkfield(md,'mesh.dimension','values',3,'message','thermal solution only supported on 3d meshes');
 			end
Index: /issm/trunk/src/m/classes/mesh.py
===================================================================
--- /issm/trunk/src/m/classes/mesh.py	(revision 13394)
+++ /issm/trunk/src/m/classes/mesh.py	(revision 13395)
@@ -1,6 +1,17 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
-
-class mesh:
+from EnumDefinitions import *
+from checkfield import *
+from MatlabFuncs import *
+
+class mesh(object):
+	"""
+	MESH class definition
+
+	   Usage:
+	      mesh=mesh();
+	"""
+
 	#properties
 	def __init__(self):
@@ -50,76 +61,141 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 
-		if obj.dimension==3:
+		if self.dimension==3:
 			string="\n%s"%("      Elements and vertices of the original 2d mesh:")
 			
-			string="%s\n%s"%(string,fielddisplay(obj,"numberofelements2d","number of elements"))
-			string="%s\n%s"%(string,fielddisplay(obj,"numberofvertices2d","number of vertices"))
-			string="%s\n%s"%(string,fielddisplay(obj,"elements2d","index into (x,y,z), coordinates of the vertices"))
-			string="%s\n%s"%(string,fielddisplay(obj,"x2d","vertices x coordinate"))
-			string="%s\n%s"%(string,fielddisplay(obj,"y2d","vertices y coordinate"))
+			string="%s\n%s"%(string,fielddisplay(self,"numberofelements2d","number of elements"))
+			string="%s\n%s"%(string,fielddisplay(self,"numberofvertices2d","number of vertices"))
+			string="%s\n%s"%(string,fielddisplay(self,"elements2d","index into (x,y,z), coordinates of the vertices"))
+			string="%s\n%s"%(string,fielddisplay(self,"x2d","vertices x coordinate"))
+			string="%s\n%s"%(string,fielddisplay(self,"y2d","vertices y coordinate"))
 
 			string="%s\n%s" %(string,"Elements and vertices of the extruded 3d mesh:")
 		else:
 			string="\n%s"%("      Elements and vertices:")
-
-		string="%s\n%s"%(string,fielddisplay(obj,"numberofelements","number of elements"))
-		
-
-
-
-		string="%s\n%s"%(string,fielddisplay(obj,"numberofvertices","number of vertices"))
-		string="%s\n%s"%(string,fielddisplay(obj,"elements","index into (x,y,z), coordinates of the vertices"))
-		string="%s\n%s"%(string,fielddisplay(obj,"x","vertices x coordinate"))
-		string="%s\n%s"%(string,fielddisplay(obj,"y","vertices y coordinate"))
-		string="%s\n%s"%(string,fielddisplay(obj,"z","vertices z coordinate"))
-		string="%s\n%s"%(string,fielddisplay(obj,"edges","edges of the 2d mesh (vertex1 vertex2 element1 element2)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"numberofedges","number of edges of the 2d mesh"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofelements","number of elements"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofvertices","number of vertices"))
+		string="%s\n%s"%(string,fielddisplay(self,"elements","index into (x,y,z), coordinates of the vertices"))
+		string="%s\n%s"%(string,fielddisplay(self,"x","vertices x coordinate"))
+		string="%s\n%s"%(string,fielddisplay(self,"y","vertices y coordinate"))
+		string="%s\n%s"%(string,fielddisplay(self,"z","vertices z coordinate"))
+		string="%s\n%s"%(string,fielddisplay(self,"edges","edges of the 2d mesh (vertex1 vertex2 element1 element2)"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberofedges","number of edges of the 2d mesh"))
 
 		string="%s%s"%(string,"\n      Properties:")
-		
-		string="%s\n%s"%(string,fielddisplay(obj,"dimension","mesh dimension (2d or 3d)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"numberoflayers","number of extrusion layers"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexonbed","lower vertices flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"elementonbed","lower elements flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexonsurface","upper vertices flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"elementonsurface","upper elements flags list"))
-		string="%s\n%s"%(string,fielddisplay(obj,"uppervertex","upper vertex list (NaN for vertex on the upper surface)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"upperelements","upper element list (NaN for element on the upper layer)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"lowervertex","lower vertex list (NaN for vertex on the lower surface)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"lowerelements","lower element list (NaN for element on the lower layer"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexonboundary","vertices on the boundary of the domain flag list"))
-		
-		string="%s\n%s"%(string,fielddisplay(obj,"segments","edges on domain boundary (vertex1 vertex2 element)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"segmentmarkers","number associated to each segment"))
-		string="%s\n%s"%(string,fielddisplay(obj,"vertexconnectivity","list of vertices connected to vertex_i"))
-		string="%s\n%s"%(string,fielddisplay(obj,"elementconnectivity","list of vertices connected to element_i"))
-		string="%s\n%s"%(string,fielddisplay(obj,"average_vertex_connectivity","average number of vertices connected to one vertex"))
+		string="%s\n%s"%(string,fielddisplay(self,"dimension","mesh dimension (2d or 3d)"))
+		string="%s\n%s"%(string,fielddisplay(self,"numberoflayers","number of extrusion layers"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonbed","lower vertices flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementonbed","lower elements flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonsurface","upper vertices flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementonsurface","upper elements flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"uppervertex","upper vertex list (NaN for vertex on the upper surface)"))
+		string="%s\n%s"%(string,fielddisplay(self,"upperelements","upper element list (NaN for element on the upper layer)"))
+		string="%s\n%s"%(string,fielddisplay(self,"lowervertex","lower vertex list (NaN for vertex on the lower surface)"))
+		string="%s\n%s"%(string,fielddisplay(self,"lowerelements","lower element list (NaN for element on the lower layer"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexonboundary","vertices on the boundary of the domain flag list"))
+		string="%s\n%s"%(string,fielddisplay(self,"segments","edges on domain boundary (vertex1 vertex2 element)"))
+		string="%s\n%s"%(string,fielddisplay(self,"segmentmarkers","number associated to each segment"))
+		string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of vertices connected to vertex_i"))
+		string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of vertices connected to element_i"))
+		string="%s\n%s"%(string,fielddisplay(self,"average_vertex_connectivity","average number of vertices connected to one vertex"))
 
 		string="%s%s"%(string,"\n      Extracted model:")
-
-		string="%s\n%s"%(string,fielddisplay(obj,"extractedvertices","vertices extracted from the model"))
-		string="%s\n%s"%(string,fielddisplay(obj,"extractedelements","elements extracted from the model"))
+		string="%s\n%s"%(string,fielddisplay(self,"extractedvertices","vertices extracted from the model"))
+		string="%s\n%s"%(string,fielddisplay(self,"extractedelements","elements extracted from the model"))
 
 		string="%s%s"%(string,"\n      Projection:")
-		string="%s\n%s"%(string,fielddisplay(obj,"lat","vertices latitude"))
-		string="%s\n%s"%(string,fielddisplay(obj,"long","vertices longitude"))
-		string="%s\n%s"%(string,fielddisplay(obj,"hemisphere","Indicate hemisphere ""n"" or ""s"" "))
+		string="%s\n%s"%(string,fielddisplay(self,"lat","vertices latitude"))
+		string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude"))
+		string="%s\n%s"%(string,fielddisplay(self,"hemisphere","Indicate hemisphere 'n' or 's'"))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
-		#the connectivity is the avergaded number of nodes linked to a
+		#the connectivity is the averaged number of nodes linked to a
 		#given node through an edge. This connectivity is used to initially
 		#allocate memory to the stiffness matrix. A value of 16 seems to
 		#give a good memory/time ration. This value can be checked in
 		#trunk/test/Miscellaneous/runme.m
-		obj.average_vertex_connectivity=25
-
-		return obj
+		self.average_vertex_connectivity=25
+
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		md = checkfield(md,'mesh.x','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'mesh.y','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'mesh.z','NaN',1,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'mesh.elements','NaN',1,'>',0,'values',range(1,md.mesh.numberofvertices+1))
+		if md.mesh.dimension==2:
+			md = checkfield(md,'mesh.elements','size',[md.mesh.numberofelements,3])
+		else:
+			md = checkfield(md,'mesh.elements','size',[md.mesh.numberofelements,6])
+		if numpy.any(numpy.logical_not(ismember(range(1,md.mesh.numberofvertices+1),md.mesh.elements))):
+			md.checkmessage("orphan nodes have been found. Check the mesh outline")
+		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
+		md = checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements],'values',[0,1])
+		md = checkfield(md,'mesh.elementonsurface','size',[md.mesh.numberofelements],'values',[0,1])
+		md = checkfield(md,'mesh.vertexonbed','size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'mesh.vertexonsurface','size',[md.mesh.numberofvertices],'values',[0,1])
+		if md.mesh.dimension==2:
+			md = checkfield(md,'mesh.average_vertex_connectivity','>=',9,'message',"'mesh.average_vertex_connectivity' should be at least 9 in 2d")
+		else:
+			md = checkfield(md,'mesh.average_vertex_connectivity','>=',24,'message',"'mesh.average_vertex_connectivity' should be at least 24 in 3d")
+		md = checkfield(md,'mesh.elementconnectivity','size',[md.mesh.numberofelements,3],'NaN',1)
+
+		#Solution specific checks
+		if   solution==PrognosticSolutionEnum():
+			if md.prognostic.stabilization==3:
+				md = checkfield(md,'mesh.dimension','values',2,'message',"Discontinuous Galerkin only supported for 2d meshes")
+				md = checkfield(md,'mesh.edges','size',[float('NaN'),4])
+				md = checkfield(md,'mesh.edges[:,1:3]','>',0)
+		elif solution==BalancethicknessSolutionEnum():
+			if md.balancethickness.stabilization==3:
+				md = checkfield(md,'mesh.dimension','values',2,'message',"Discontinuous Galerkin only supported for 2d meshes")
+				md = checkfield(md,'mesh.edges','size',[float('NaN'),4])
+				md = checkfield(md,'mesh.edges[:,1:3]','>',0)
+		elif solution==TransientSolutionEnum():
+			if md.transient.isprognostic and md.prognostic.stabilization==3:
+				md = checkfield(md,'mesh.dimension','values',2,'message',"Discontinuous Galerkin only supported for 2d meshes")
+				md = checkfield(md,'mesh.edges','size',[float('NaN'),4])
+				md = checkfield(md,'mesh.edges[:,1:3]','>',0)
+		elif solution==ThermalSolutionEnum():
+			md = checkfield(md,'mesh.dimension','values',3,'message','thermal solution only supported on 3d meshes')
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','x','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','y','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','z','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','elements','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','dimension','format','Integer')
+		WriteData(fid,'object',self,'fieldname','numberoflayers','format','Integer')
+		WriteData(fid,'object',self,'fieldname','numberofelements','format','Integer')
+		WriteData(fid,'object',self,'fieldname','numberofvertices','format','Integer')
+		WriteData(fid,'object',self,'fieldname','numberofedges','format','Integer')
+		WriteData(fid,'object',self,'fieldname','elementonbed','format','BooleanMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','elementonsurface','format','BooleanMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','vertexonbed','format','BooleanMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','vertexonsurface','format','BooleanMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','lowerelements','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','upperelements','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','edges','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','elementconnectivity','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','average_vertex_connectivity','format','Integer')
+		WriteData(fid,'object',self,'fieldname','elements2d','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','numberofvertices2d','format','Integer')
+		WriteData(fid,'object',self,'fieldname','numberofelements2d','format','Integer')
+	# }}}
+
Index: /issm/trunk/src/m/classes/miscellaneous.m
===================================================================
--- /issm/trunk/src/m/classes/miscellaneous.m	(revision 13394)
+++ /issm/trunk/src/m/classes/miscellaneous.m	(revision 13395)
@@ -1,3 +1,3 @@
-%MISCELANEOUS class definition
+%MISCELLANEOUS class definition
 %
 %   Usage:
Index: /issm/trunk/src/m/classes/miscellaneous.py
===================================================================
--- /issm/trunk/src/m/classes/miscellaneous.py	(revision 13394)
+++ /issm/trunk/src/m/classes/miscellaneous.py	(revision 13395)
@@ -1,6 +1,17 @@
 #module imports
+from collections import OrderedDict
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class miscellaneous:
+class miscellaneous(object):
+	"""
+	MISCELLANEOUS class definition
+
+	   Usage:
+	      miscellaneous=miscellaneous();
+	"""
+
 	#properties
 	def __init__(self):
@@ -8,5 +19,5 @@
 		self.notes = ''
 		self.name  = ''
-		self.dummy = {}
+		self.dummy = OrderedDict()
 
 		#set defaults
@@ -14,17 +25,26 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   miscellaneous parameters:'
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,'notes','notes in a cell of strings'))
-		string="%s\n%s"%(string,fielddisplay(obj,'name','model name'))
-		string="%s\n%s"%(string,fielddisplay(obj,'dummy','empty field to store some data'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'notes','notes in a cell of strings'))
+		string="%s\n%s"%(string,fielddisplay(self,'name','model name'))
+		string="%s\n%s"%(string,fielddisplay(self,'dummy','empty field to store some data'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		md = checkfield(md,'miscellaneous.name','empty',1)
+		return md
+	# }}}
+
+	def marshall(self,fid):    #  {{{
+		WriteData(fid,'object',self,'fieldname','name','format','String')
+	# }}}
+
Index: /issm/trunk/src/m/classes/model/model.m
===================================================================
--- /issm/trunk/src/m/classes/model/model.m	(revision 13394)
+++ /issm/trunk/src/m/classes/model/model.m	(revision 13395)
@@ -72,4 +72,15 @@
 				 md = structtomodel(model,md);
 			 end
+
+			 %2012 August 4th
+			 if isa(md.materials,'materials'),
+				 disp('Recovering old materials');
+				 if numel(md.materials.rheology_Z)==1 & isnan(md.materials.rheology_Z),
+					 md.materials=matice(md.materials);
+				 else
+					 md.materials=matdamageice(md.materials);
+				 end
+			 end
+
 		 end% }}}
 	 end
@@ -91,4 +102,673 @@
 		 end
 		 %}}}
+		 function md = collapse(md)% {{{
+			 %COLLAPSE - collapses a 3d mesh into a 2d mesh
+			 %
+			 %   This routine collapses a 3d model into a 2d model
+			 %   and collapses all the fileds of the 3d model by
+			 %   taking their depth-averaged values
+			 %
+			 %   Usage:
+			 %      md=collapse(md)
+			 %
+			 %   See also: EXTRUDE, MODELEXTRACT
+
+			 %Check that the model is really a 3d model
+			 if ~md.mesh.dimension==3,
+				 error('collapse error message: only 3d mesh can be collapsed')
+			 end
+
+			 %Start with changing alle the fields from the 3d mesh 
+
+			 %drag is limited to nodes that are on the bedrock.
+			 md.friction.coefficient=project2d(md,md.friction.coefficient,1);
+
+			 %p and q (same deal, except for element that are on the bedrock: )
+			 md.friction.p=project2d(md,md.friction.p,1);
+			 md.friction.q=project2d(md,md.friction.q,1);
+
+			 %observations
+			 if ~isnan(md.inversion.vx_obs), md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers); end;
+			 if ~isnan(md.inversion.vy_obs), md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers); end;
+			 if ~isnan(md.inversion.vel_obs), md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers); end;
+			 if ~isnan(md.inversion.cost_functions_coefficients), md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers); end;
+			 if numel(md.inversion.min_parameters)>1, md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers); end;
+			 if numel(md.inversion.max_parameters)>1, md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers); end;
+			 if ~isnan(md.surfaceforcings.mass_balance),
+				 md.surfaceforcings.mass_balance=project2d(md,md.surfaceforcings.mass_balance,md.mesh.numberoflayers); 
+			 end;
+			 if ~isnan(md.balancethickness.thickening_rate), md.balancethickness.thickening_rate=project2d(md,md.balancethickness.thickening_rate,md.mesh.numberoflayers); end;
+
+			 %results
+			 if ~isnan(md.initialization.vx),md.initialization.vx=DepthAverage(md,md.initialization.vx);end;
+			 if ~isnan(md.initialization.vy),md.initialization.vy=DepthAverage(md,md.initialization.vy);end;
+			 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
+			 md.mesh.elementonbed=ones(md.mesh.numberofelements2d,1);
+			 md.mesh.elementonsurface=ones(md.mesh.numberofelements2d,1);
+			 md.mesh.vertexonbed=ones(md.mesh.numberofvertices2d,1);
+			 md.mesh.vertexonsurface=ones(md.mesh.numberofvertices2d,1);
+
+			 %elementstype
+			 if ~isnan(md.flowequation.element_equation)
+				 md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1);
+				 md.flowequation.vertex_equation=project2d(md,md.flowequation.vertex_equation,1);
+				 md.flowequation.bordermacayeal=project2d(md,md.flowequation.bordermacayeal,1);
+				 md.flowequation.borderpattyn=project2d(md,md.flowequation.borderpattyn,1);
+				 md.flowequation.borderstokes=project2d(md,md.flowequation.borderstokes,1);
+			 end	
+
+			 %boundary conditions
+			 md.diagnostic.spcvx=project2d(md,md.diagnostic.spcvx,md.mesh.numberoflayers);
+			 md.diagnostic.spcvy=project2d(md,md.diagnostic.spcvy,md.mesh.numberoflayers);
+			 md.diagnostic.spcvz=project2d(md,md.diagnostic.spcvz,md.mesh.numberoflayers);
+			 md.diagnostic.referential=project2d(md,md.diagnostic.referential,md.mesh.numberoflayers);
+			 md.prognostic.spcthickness=project2d(md,md.prognostic.spcthickness,md.mesh.numberoflayers);
+			 md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
+
+			 %Extrusion of Neumann BC
+			 if ~isnan(md.diagnostic.icefront),
+				 numberofneumann2d=size(md.diagnostic.icefront,1)/(md.mesh.numberoflayers-1);
+				 md.diagnostic.icefront=[md.diagnostic.icefront(1:numberofneumann2d,1:2) md.diagnostic.icefront(1:numberofneumann2d,5:6)]; %Add two columns on the first layer 
+			 end
+
+			 %materials
+			 md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B);
+			 md.materials.rheology_n=project2d(md,md.materials.rheology_n,1);
+			 if isa(md.materials,'matdamageice')
+				 md.materials.rheology_Z=DepthAverage(md,md.materials.rheology_Z);
+			 end
+
+			 %special for thermal modeling:
+			 md.basalforcings.melting_rate=project2d(md,md.basalforcings.melting_rate,1); 
+			 md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1); %bedrock only gets geothermal flux
+
+			 %update of connectivity matrix
+			 md.mesh.average_vertex_connectivity=25;
+
+			 %Collapse the mesh
+			 nodes2d=md.mesh.numberofvertices2d;
+			 elements2d=md.mesh.numberofelements2d;
+
+			 %parameters
+			 md.geometry.surface=project2d(md,md.geometry.surface,1);
+			 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);
+			 md.mask.elementonfloatingice=project2d(md,md.mask.elementonfloatingice,1);
+			 md.mask.vertexonfloatingice=project2d(md,md.mask.vertexonfloatingice,1);
+			 md.mask.elementongroundedice=project2d(md,md.mask.elementongroundedice,1);
+			 md.mask.vertexongroundedice=project2d(md,md.mask.vertexongroundedice,1);
+			 md.mask.elementonwater=project2d(md,md.mask.elementonwater,1);
+			 md.mask.vertexonwater=project2d(md,md.mask.vertexonwater,1);
+
+			 %lat long
+			 if numel(md.mesh.lat) ==md.mesh.numberofvertices,  md.mesh.lat=project2d(md,md.mesh.lat,1); end
+			 if numel(md.mesh.long)==md.mesh.numberofvertices, md.mesh.long=project2d(md,md.mesh.long,1); end
+
+			 %Initialize with the 2d mesh
+			 md.mesh.x=md.mesh.x2d;
+			 md.mesh.y=md.mesh.y2d;
+			 md.mesh.z=zeros(size(md.mesh.x2d));
+			 md.mesh.numberofvertices=md.mesh.numberofvertices2d;
+			 md.mesh.numberofelements=md.mesh.numberofelements2d;
+			 md.mesh.elements=md.mesh.elements2d;
+
+			 %Keep a trace of lower and upper nodes
+			 md.mesh.lowervertex=NaN;
+			 md.mesh.uppervertex=NaN;
+			 md.mesh.lowerelements=NaN;
+			 md.mesh.upperelements=NaN;
+
+			 %Remove old mesh 
+			 md.mesh.x2d=NaN;
+			 md.mesh.y2d=NaN;
+			 md.mesh.elements2d=NaN;
+			 md.mesh.numberofelements2d=md.mesh.numberofelements;
+			 md.mesh.numberofvertices2d=md.mesh.numberofvertices;
+			 md.mesh.numberoflayers=0;
+
+			 %Update mesh type
+			 md.mesh.dimension=2;
+		 end % }}}
+		 function md2 = extract(md,area) % {{{
+			 %extract - extract a model according to an Argus contour or flag list
+			 %
+			 %   This routine extracts a submodel from a bigger model with respect to a given contour
+			 %   md must be followed by the corresponding exp file or flags list
+			 %   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
+			 %   If user wants every element outside the domain to be 
+			 %   extract2d, add '~' to the name of the domain file (ex: '~Pattyn.exp');
+			 %   an empty string '' will be considered as an empty domain
+			 %   a string 'all' will be considered as the entire domain
+			 %   add an argument 0 if you do not want the elements to be checked (faster)
+			 %
+			 %   Usage:
+			 %      md2=extract(md,area);
+			 %
+			 %   Examples:
+			 %      md2=extract(md,'Domain.exp');
+			 %      md2=extract(md,md.mask.elementonfloatingice);
+			 %
+			 %   See also: EXTRUDE, COLLAPSE
+
+			 %copy model
+			 md1=md;
+
+			 %some checks
+			 if ((nargin~=2) | (nargout~=1)),
+				 help extract
+				 error('extract error message: bad usage');
+			 end
+
+			 %get check option
+			 if (nargin==3 & varargin{1}==0),
+				 checkoutline=0;
+			 else
+				 checkoutline=1;
+			 end
+
+			 %get elements that are inside area
+			 flag_elem=FlagElements(md1,area);
+			 if ~any(flag_elem),
+				 error('extracted model is empty');
+			 end
+
+			 %kick out all elements with 3 dirichlets
+			 spc_elem=find(~flag_elem);
+			 spc_node=sort(unique(md1.mesh.elements(spc_elem,:)));
+			 flag=ones(md1.mesh.numberofvertices,1);
+			 flag(spc_node)=0;
+			 pos=find(sum(flag(md1.mesh.elements),2)==0);
+			 flag_elem(pos)=0;
+
+			 %extracted elements and nodes lists
+			 pos_elem=find(flag_elem);
+			 pos_node=sort(unique(md1.mesh.elements(pos_elem,:)));
+
+			 %keep track of some fields
+			 numberofvertices1=md1.mesh.numberofvertices;
+			 numberofelements1=md1.mesh.numberofelements;
+			 numberofvertices2=length(pos_node);
+			 numberofelements2=length(pos_elem);
+			 flag_node=zeros(numberofvertices1,1);
+			 flag_node(pos_node)=1;
+
+			 %Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)
+			 Pelem=zeros(numberofelements1,1);
+			 Pelem(pos_elem)=[1:numberofelements2]';
+			 Pnode=zeros(numberofvertices1,1);
+			 Pnode(pos_node)=[1:numberofvertices2]';
+
+			 %renumber the elements (some node won't exist anymore)
+			 elements_1=md1.mesh.elements;
+			 elements_2=elements_1(pos_elem,:);
+			 elements_2(:,1)=Pnode(elements_2(:,1));
+			 elements_2(:,2)=Pnode(elements_2(:,2));
+			 elements_2(:,3)=Pnode(elements_2(:,3));
+			 if md1.mesh.dimension==3,
+				 elements_2(:,4)=Pnode(elements_2(:,4));
+				 elements_2(:,5)=Pnode(elements_2(:,5));
+				 elements_2(:,6)=Pnode(elements_2(:,6));
+			 end
+
+			 %OK, now create the new model !
+
+			 %take every fields from model
+			 md2=md1;
+
+			 %automatically modify fields
+
+			 %loop over model fields
+			 model_fields=fields(md1);
+			 for i=1:length(model_fields),
+				 %get field
+				 field=md1.(model_fields{i});
+				 fieldsize=size(field);
+				 if isobject(field), %recursive call
+					 object_fields=fields(md1.(model_fields{i}));
+					 for j=1:length(object_fields),
+						 %get field
+						 field=md1.(model_fields{i}).(object_fields{j});
+						 fieldsize=size(field);
+						 %size = number of nodes * n
+						 if fieldsize(1)==numberofvertices1
+							 md2.(model_fields{i}).(object_fields{j})=field(pos_node,:);
+						 elseif (fieldsize(1)==numberofvertices1+1)
+							 md2.(model_fields{i}).(object_fields{j})=[field(pos_node,:); field(end,:)];
+							 %size = number of elements * n
+						 elseif fieldsize(1)==numberofelements1
+							 md2.(model_fields{i}).(object_fields{j})=field(pos_elem,:);
+						 end
+					 end
+				 else
+					 %size = number of nodes * n
+					 if fieldsize(1)==numberofvertices1
+						 md2.(model_fields{i})=field(pos_node,:);
+					 elseif (fieldsize(1)==numberofvertices1+1)
+						 md2.(model_fields{i})=[field(pos_node,:); field(end,:)];
+						 %size = number of elements * n
+					 elseif fieldsize(1)==numberofelements1
+						 md2.(model_fields{i})=field(pos_elem,:);
+					 end
+				 end
+			 end
+
+			 %modify some specific fields
+
+			 %Mesh
+			 md2.mesh.numberofelements=numberofelements2;
+			 md2.mesh.numberofvertices=numberofvertices2;
+			 md2.mesh.elements=elements_2;
+
+			 %mesh.uppervertex mesh.lowervertex
+			 if md1.mesh.dimension==3
+				 md2.mesh.uppervertex=md1.mesh.uppervertex(pos_node);
+				 pos=find(~isnan(md2.mesh.uppervertex));
+				 md2.mesh.uppervertex(pos)=Pnode(md2.mesh.uppervertex(pos));
+
+				 md2.mesh.lowervertex=md1.mesh.lowervertex(pos_node);
+				 pos=find(~isnan(md2.mesh.lowervertex));
+				 md2.mesh.lowervertex(pos)=Pnode(md2.mesh.lowervertex(pos));
+
+				 md2.mesh.upperelements=md1.mesh.upperelements(pos_elem);
+				 pos=find(~isnan(md2.mesh.upperelements));
+				 md2.mesh.upperelements(pos)=Pelem(md2.mesh.upperelements(pos));
+
+				 md2.mesh.lowerelements=md1.mesh.lowerelements(pos_elem);
+				 pos=find(~isnan(md2.mesh.lowerelements));
+				 md2.mesh.lowerelements(pos)=Pelem(md2.mesh.lowerelements(pos));
+			 end
+
+			 %Initial 2d mesh 
+			 if md1.mesh.dimension==3
+				 flag_elem_2d=flag_elem(1:md1.mesh.numberofelements2d);
+				 pos_elem_2d=find(flag_elem_2d);
+				 flag_node_2d=flag_node(1:md1.mesh.numberofvertices2d);
+				 pos_node_2d=find(flag_node_2d);
+
+				 md2.mesh.numberofelements2d=length(pos_elem_2d);
+				 md2.mesh.numberofvertices2d=length(pos_node_2d);
+				 md2.mesh.elements2d=md1.mesh.elements2d(pos_elem_2d,:);
+				 md2.mesh.elements2d(:,1)=Pnode(md2.mesh.elements2d(:,1));
+				 md2.mesh.elements2d(:,2)=Pnode(md2.mesh.elements2d(:,2));
+				 md2.mesh.elements2d(:,3)=Pnode(md2.mesh.elements2d(:,3));
+
+				 md2.mesh.x2d=md1.mesh.x(pos_node_2d);
+				 md2.mesh.y2d=md1.mesh.y(pos_node_2d);
+			 end
+
+			 %Edges
+			 if size(md2.mesh.edges,2)>1, %do not use ~isnan because there are some NaNs...
+				 %renumber first two columns
+				 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)); 
+				 md2.mesh.edges(:  ,3)=Pelem(md2.mesh.edges(:,3));
+				 md2.mesh.edges(pos,4)=Pelem(md2.mesh.edges(pos,4));
+				 %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 -1 in the last two columns;
+				 pos=find(md2.mesh.edges(:,3)==0);
+				 md2.mesh.edges(pos,3)=-1;
+				 pos=find(md2.mesh.edges(:,4)==0);
+				 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)=-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(md2.mesh.edges(:,3)==-1 & md2.mesh.edges(:,4)==-1);
+				 md2.mesh.edges(pos,:)=[];
+			 end
+
+			 %Penalties
+			 if ~isnan(md2.diagnostic.vertex_pairing),
+				 for i=1:size(md1.diagnostic.vertex_pairing,1);
+					 md2.diagnostic.vertex_pairing(i,:)=Pnode(md1.diagnostic.vertex_pairing(i,:));
+				 end
+				 md2.diagnostic.vertex_pairing=md2.diagnostic.vertex_pairing(find(md2.diagnostic.vertex_pairing(:,1)),:);
+			 end
+			 if ~isnan(md2.prognostic.vertex_pairing),
+				 for i=1:size(md1.prognostic.vertex_pairing,1);
+					 md2.prognostic.vertex_pairing(i,:)=Pnode(md1.prognostic.vertex_pairing(i,:));
+				 end
+				 md2.prognostic.vertex_pairing=md2.prognostic.vertex_pairing(find(md2.prognostic.vertex_pairing(:,1)),:);
+			 end
+
+			 %recreate segments
+			 if md1.mesh.dimension==2
+				 md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices);
+				 md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity);
+				 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
+
+			 %Boundary conditions: Dirichlets on new boundary
+			 %Catch the elements that have not been extracted
+			 orphans_elem=find(~flag_elem);
+			 orphans_node=unique(md1.mesh.elements(orphans_elem,:))';
+			 %Figure out which node are on the boundary between md2 and md1
+			 nodestoflag1=intersect(orphans_node,pos_node);
+			 nodestoflag2=Pnode(nodestoflag1);
+			 if numel(md1.diagnostic.spcvx)>1 & numel(md1.diagnostic.spcvy)>2 & numel(md1.diagnostic.spcvz)>2,
+				 if numel(md1.inversion.vx_obs)>1 & numel(md1.inversion.vy_obs)>1
+					 md2.diagnostic.spcvx(nodestoflag2)=md2.inversion.vx_obs(nodestoflag2); 
+					 md2.diagnostic.spcvy(nodestoflag2)=md2.inversion.vy_obs(nodestoflag2);
+				 else
+					 md2.diagnostic.spcvx(nodestoflag2)=NaN;
+					 md2.diagnostic.spcvy(nodestoflag2)=NaN;
+					 disp(' ')
+					 disp('!! extract warning: spc values should be checked !!')
+					 disp(' ')
+				 end
+				 %put 0 for vz
+				 md2.diagnostic.spcvz(nodestoflag2)=0;
+			 end
+			 if ~isnan(md1.thermal.spctemperature),
+				 md2.thermal.spctemperature(nodestoflag2,1)=1;
+			 end
+
+			 %Diagnostic
+			 if ~isnan(md2.diagnostic.icefront)
+				 md2.diagnostic.icefront(:,1)=Pnode(md1.diagnostic.icefront(:,1)); 
+				 md2.diagnostic.icefront(:,2)=Pnode(md1.diagnostic.icefront(:,2)); 
+				 md2.diagnostic.icefront(:,end-1)=Pelem(md1.diagnostic.icefront(:,end-1));
+				 if md1.mesh.dimension==3
+					 md2.diagnostic.icefront(:,3)=Pnode(md1.diagnostic.icefront(:,3)); 
+					 md2.diagnostic.icefront(:,4)=Pnode(md1.diagnostic.icefront(:,4)); 
+				 end
+				 md2.diagnostic.icefront=md2.diagnostic.icefront(find(md2.diagnostic.icefront(:,1) & md2.diagnostic.icefront(:,2) & md2.diagnostic.icefront(:,end)),:);
+			 end
+
+			 %Results fields
+			 if isstruct(md1.results),
+				 md2.results=struct();
+				 solutionfields=fields(md1.results);
+				 for i=1:length(solutionfields),
+					 %get subfields
+					 solutionsubfields=fields(md1.results.(solutionfields{i}));
+					 for j=1:length(solutionsubfields),
+						 field=md1.results.(solutionfields{i}).(solutionsubfields{j});
+						 if length(field)==numberofvertices1,
+							 md2.results.(solutionfields{i}).(solutionsubfields{j})=field(pos_node);
+						 elseif length(field)==numberofelements1,
+							 md2.results.(solutionfields{i}).(solutionsubfields{j})=field(pos_elem);
+						 else
+							 md2.results.(solutionfields{i}).(solutionsubfields{j})=field;
+						 end
+					 end
+				 end
+			 end
+
+			 %Keep track of pos_node and pos_elem
+			 md2.mesh.extractedvertices=pos_node;
+			 md2.mesh.extractedelements=pos_elem;
+		 end % }}}
+		 function md = extrude(md,varargin) % {{{
+			 %EXTRUDE - vertically extrude a 2d mesh
+			 %
+			 %   vertically extrude a 2d mesh and create corresponding 3d mesh.
+			 %   The vertical distribution can:
+			 %    - follow a polynomial law
+			 %    - follow two polynomial laws, one for the lower part and one for the upper part of the mesh
+			 %    - be discribed by a list of coefficients (between 0 and 1)
+			 %   
+			 %
+			 %   Usage:
+			 %      md=extrude(md,numlayers,extrusionexponent);
+			 %      md=extrude(md,numlayers,lowerexponent,upperexponent);
+			 %      md=extrude(md,listofcoefficients);
+			 %
+			 %   Example:
+			 %      md=extrude(md,8,3);
+			 %      md=extrude(md,8,3,2);
+			 %      md=extrude(md,[0 0.2 0.5 0.7 0.9 0.95 1]);
+			 %
+			 %   See also: MODELEXTRACT, COLLAPSE
+
+			 %some checks on list of arguments
+			 if ((nargin>4) | (nargin<2) | (nargout~=1)),
+				 help extrude;
+				 error('extrude error message');
+			 end
+
+			 %Extrude the mesh
+			 if nargin==2, %list of coefficients
+				 clist=varargin{1};
+				 if any(clist<0) | any(clist>1),
+					 error('extrusioncoefficients must be between 0 and 1');
+				 end
+				 extrusionlist=sort(unique([clist(:);0;1]));
+				 numlayers=length(extrusionlist);
+			 elseif nargin==3, %one polynomial law
+				 if varargin{2}<=0,
+					 help extrude;
+					 error('extrusionexponent must be >=0');
+				 end
+				 numlayers=varargin{1};
+				 extrusionlist=((0:1:numlayers-1)/(numlayers-1)).^varargin{2};
+			 elseif nargin==4, %two polynomial laws
+				 numlayers=varargin{1};
+				 lowerexp=varargin{2};
+				 upperexp=varargin{3};
+
+				 if varargin{2}<=0 | varargin{3}<=0,
+					 help extrude;
+					 error('lower and upper extrusionexponents must be >=0');
+				 end
+
+				 lowerextrusionlist=[(0:2/(numlayers-1):1).^lowerexp]/2;
+				 upperextrusionlist=[(0:2/(numlayers-1):1).^upperexp]/2;
+				 extrusionlist=sort(unique([lowerextrusionlist 1-upperextrusionlist]));
+
+			 end
+
+			 if numlayers<2,
+				 error('number of layers should be at least 2');
+			 end
+			 if md.mesh.dimension==3,
+				 error('Cannot extrude a 3d mesh (extrude cannot be called more than once)');
+			 end
+
+			 %Initialize with the 2d mesh
+			 x3d=[]; 
+			 y3d=[];
+			 z3d=[];  %the lower node is on the bed
+			 thickness3d=md.geometry.thickness; %thickness and bed for these nodes
+			 bed3d=md.geometry.bed;
+
+			 %Create the new layers
+			 for i=1:numlayers,
+				 x3d=[x3d; md.mesh.x]; 
+				 y3d=[y3d; md.mesh.y];
+				 %nodes are distributed between bed and surface accordingly to the given exponent
+				 z3d=[z3d; bed3d+thickness3d*extrusionlist(i)]; 
+			 end
+			 number_nodes3d=size(x3d,1); %number of 3d nodes for the non extruded part of the mesh
+
+			 %Extrude elements 
+			 elements3d=[];
+			 for i=1:numlayers-1,
+				 elements3d=[elements3d;[md.mesh.elements+(i-1)*md.mesh.numberofvertices md.mesh.elements+i*md.mesh.numberofvertices]]; %Create the elements of the 3d mesh for the non extruded part
+			 end
+			 number_el3d=size(elements3d,1); %number of 3d nodes for the non extruded part of the mesh
+
+			 %Keep a trace of lower and upper nodes
+			 mesh.lowervertex=NaN*ones(number_nodes3d,1);
+			 mesh.uppervertex=NaN*ones(number_nodes3d,1);
+			 mesh.lowervertex(md.mesh.numberofvertices+1:end)=1:(numlayers-1)*md.mesh.numberofvertices;
+			 mesh.uppervertex(1:(numlayers-1)*md.mesh.numberofvertices)=md.mesh.numberofvertices+1:number_nodes3d;
+			 md.mesh.lowervertex=mesh.lowervertex;
+			 md.mesh.uppervertex=mesh.uppervertex;
+
+			 %same for lower and upper elements
+			 mesh.lowerelements=NaN*ones(number_el3d,1);
+			 mesh.upperelements=NaN*ones(number_el3d,1);
+			 mesh.lowerelements(md.mesh.numberofelements+1:end)=1:(numlayers-2)*md.mesh.numberofelements;
+			 mesh.upperelements(1:(numlayers-2)*md.mesh.numberofelements)=md.mesh.numberofelements+1:(numlayers-1)*md.mesh.numberofelements;
+			 md.mesh.lowerelements=mesh.lowerelements;
+			 md.mesh.upperelements=mesh.upperelements;
+
+			 %Save old mesh 
+			 md.mesh.x2d=md.mesh.x;
+			 md.mesh.y2d=md.mesh.y;
+			 md.mesh.elements2d=md.mesh.elements;
+			 md.mesh.numberofelements2d=md.mesh.numberofelements;
+			 md.mesh.numberofvertices2d=md.mesh.numberofvertices;
+
+			 %Update mesh type
+			 md.mesh.dimension=3;
+
+			 %Build global 3d mesh 
+			 md.mesh.elements=elements3d;
+			 md.mesh.x=x3d;
+			 md.mesh.y=y3d;
+			 md.mesh.z=z3d;
+			 md.mesh.numberofelements=number_el3d;
+			 md.mesh.numberofvertices=number_nodes3d;
+			 md.mesh.numberoflayers=numlayers;
+
+			 %Ok, now deal with the other fields from the 2d mesh:
+
+			 %lat long
+			 md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node');
+			 md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node');
+
+			 %drag coefficient is limited to nodes that are on the bedrock.
+			 md.friction.coefficient=project3d(md,'vector',md.friction.coefficient,'type','node','layer',1);
+
+			 %p and q (same deal, except for element that are on the bedrock: )
+			 md.friction.p=project3d(md,'vector',md.friction.p,'type','element');
+			 md.friction.q=project3d(md,'vector',md.friction.q,'type','element');
+
+			 %observations
+			 md.inversion.vx_obs=project3d(md,'vector',md.inversion.vx_obs,'type','node');
+			 md.inversion.vy_obs=project3d(md,'vector',md.inversion.vy_obs,'type','node');
+			 md.inversion.vel_obs=project3d(md,'vector',md.inversion.vel_obs,'type','node');
+			 md.surfaceforcings.mass_balance=project3d(md,'vector',md.surfaceforcings.mass_balance,'type','node');
+			 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
+			 if ~isnan(md.initialization.vx),md.initialization.vx=project3d(md,'vector',md.initialization.vx,'type','node');end;
+			 if ~isnan(md.initialization.vy),md.initialization.vy=project3d(md,'vector',md.initialization.vy,'type','node');end;
+			 if ~isnan(md.initialization.vz),md.initialization.vz=project3d(md,'vector',md.initialization.vz,'type','node');end;
+			 if ~isnan(md.initialization.vel),md.initialization.vel=project3d(md,'vector',md.initialization.vel,'type','node');end;
+			 if ~isnan(md.initialization.temperature),md.initialization.temperature=project3d(md,'vector',md.initialization.temperature,'type','node');end;
+			 if ~isnan(md.initialization.waterfraction),md.initialization.waterfraction=project3d(md,'vector',md.initialization.waterfraction,'type','node');end;
+
+			 %bedinfo and surface info
+			 md.mesh.elementonbed=project3d(md,'vector',ones(md.mesh.numberofelements2d,1),'type','element','layer',1);
+			 md.mesh.elementonsurface=project3d(md,'vector',ones(md.mesh.numberofelements2d,1),'type','element','layer',md.mesh.numberoflayers-1);
+			 md.mesh.vertexonbed=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',1);
+			 md.mesh.vertexonsurface=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',md.mesh.numberoflayers);
+
+			 %elementstype
+			 if ~isnan(md.flowequation.element_equation)
+				 oldelements_type=md.flowequation.element_equation;
+				 md.flowequation.element_equation=zeros(number_el3d,1);
+				 md.flowequation.element_equation=project3d(md,'vector',oldelements_type,'type','element');
+			 end
+
+			 %verticestype
+			 if ~isnan(md.flowequation.vertex_equation)
+				 oldvertices_type=md.flowequation.vertex_equation;
+				 md.flowequation.vertex_equation=zeros(number_nodes3d,1);
+				 md.flowequation.vertex_equation=project3d(md,'vector',oldvertices_type,'type','node');
+			 end
+			 md.flowequation.bordermacayeal=project3d(md,'vector',md.flowequation.bordermacayeal,'type','node');
+			 md.flowequation.borderpattyn=project3d(md,'vector',md.flowequation.borderpattyn,'type','node');
+			 md.flowequation.borderstokes=project3d(md,'vector',md.flowequation.borderstokes,'type','node');
+
+			 %boundary conditions
+			 md.diagnostic.spcvx=project3d(md,'vector',md.diagnostic.spcvx,'type','node');
+			 md.diagnostic.spcvy=project3d(md,'vector',md.diagnostic.spcvy,'type','node');
+			 md.diagnostic.spcvz=project3d(md,'vector',md.diagnostic.spcvz,'type','node');
+			 md.thermal.spctemperature=project3d(md,'vector',md.thermal.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',NaN);
+			 md.prognostic.spcthickness=project3d(md,'vector',md.prognostic.spcthickness,'type','node');
+			 md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node');
+			 md.diagnostic.referential=project3d(md,'vector',md.diagnostic.referential,'type','node');
+
+			 %in 3d, pressureload: [node1 node2 node3 node4 element]
+			 pressureload_layer1=[md.diagnostic.icefront(:,1:2)  md.diagnostic.icefront(:,2)+md.mesh.numberofvertices2d  md.diagnostic.icefront(:,1)+md.mesh.numberofvertices2d  md.diagnostic.icefront(:,3:4)]; %Add two columns on the first layer 
+			 pressureload=[];
+			 for i=1:numlayers-1,
+				 pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d pressureload_layer1(:,6)];
+			 end
+			 md.diagnostic.icefront=pressureload;
+
+			 %connectivity
+			 md.mesh.elementconnectivity=repmat(md.mesh.elementconnectivity,numlayers-1,1);
+			 md.mesh.elementconnectivity(find(md.mesh.elementconnectivity==0))=NaN;
+			 for i=2:numlayers-1,
+				 md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)...
+					 =md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)+md.mesh.numberofelements2d;
+			 end
+			 md.mesh.elementconnectivity(find(isnan(md.mesh.elementconnectivity)))=0;
+
+			 %materials
+			 md.materials.rheology_B=project3d(md,'vector',md.materials.rheology_B,'type','node');
+			 md.materials.rheology_n=project3d(md,'vector',md.materials.rheology_n,'type','element');
+			 if isa(md.materials,'matdamageice')
+				 md.materials.rheology_Z=project3d(md,'vector',md.materials.rheology_Z,'type','node');
+			 end
+
+			 %parameters
+			 md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node');
+			 md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node');
+			 md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node');
+			 md.geometry.bed=project3d(md,'vector',md.geometry.bed,'type','node');
+			 md.geometry.bathymetry=project3d(md,'vector',md.geometry.bathymetry,'type','node');
+			 md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node');
+			 md.mask.elementonfloatingice=project3d(md,'vector',md.mask.elementonfloatingice,'type','element');
+			 md.mask.vertexonfloatingice=project3d(md,'vector',md.mask.vertexonfloatingice,'type','node');
+			 md.mask.elementongroundedice=project3d(md,'vector',md.mask.elementongroundedice,'type','element');
+			 md.mask.vertexongroundedice=project3d(md,'vector',md.mask.vertexongroundedice,'type','node');
+			 md.mask.elementonwater=project3d(md,'vector',md.mask.elementonwater,'type','element');
+			 md.mask.vertexonwater=project3d(md,'vector',md.mask.vertexonwater,'type','node');
+			 if ~isnan(md.inversion.cost_functions_coefficients),md.inversion.cost_functions_coefficients=project3d(md,'vector',md.inversion.cost_functions_coefficients,'type','node');end;
+			 if ~isnan(md.inversion.min_parameters),md.inversion.min_parameters=project3d(md,'vector',md.inversion.min_parameters,'type','node');end;
+			 if ~isnan(md.inversion.max_parameters),md.inversion.max_parameters=project3d(md,'vector',md.inversion.max_parameters,'type','node');end;
+			 if ~isnan(md.qmu.partition),md.qmu.partition=project3d(md,'vector',md.qmu.partition','type','node');end
+			 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
+			 if ~isnan(md.initialization.pressure),
+				 md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z);
+			 end
+
+			 %special for thermal modeling:
+			 md.basalforcings.melting_rate=project3d(md,'vector',md.basalforcings.melting_rate,'type','node','layer',1); 
+			 if ~isnan(md.basalforcings.geothermalflux)
+				 md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1); %bedrock only gets geothermal flux
+			 end
+
+			 %increase connectivity if less than 25:
+			 if md.mesh.average_vertex_connectivity<=25,
+				 md.mesh.average_vertex_connectivity=100;
+			 end
+			end % }}}
 		 function md = structtomodel(md,structmd) % {{{
 
@@ -377,5 +1057,5 @@
 			 md.timestepping     = timestepping();
 			 md.groundingline    = groundingline();
-			 md.materials        = materials();
+			 md.materials        = matice();
 			 md.flowequation     = flowequation();
 			 md.debug            = debug();
@@ -383,8 +1063,8 @@
 			 md.settings         = settings();
 			 md.solver           = solver();
-			 if ismumps,
-				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum,mumpsoptions);
+			 if ismumps(),
+				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),mumpsoptions());
 			 else
-				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum,iluasmoptions);
+				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),iluasmoptions());
 			 end
 			 md.cluster          = generic();
Index: /issm/trunk/src/m/classes/model/model.py
===================================================================
--- /issm/trunk/src/m/classes/model/model.py	(revision 13394)
+++ /issm/trunk/src/m/classes/model/model.py	(revision 13395)
@@ -1,3 +1,4 @@
 #module imports {{{
+import numpy
 from mesh import mesh
 from mask import mask
@@ -6,5 +7,5 @@
 from surfaceforcings import surfaceforcings
 from basalforcings import basalforcings
-from materials import materials
+from matice import matice
 from friction import friction
 from flowequation import flowequation
@@ -32,6 +33,13 @@
 from miscellaneous import miscellaneous
 from private import private
+from collections import OrderedDict
+from EnumDefinitions import *
+from ismumps import *
+from mumpsoptions import *
+from iluasmoptions import *
+from project3d import *
 #}}}
-class model:
+
+class model(object):
 	#properties
 	def __init__(self):
@@ -43,5 +51,5 @@
 		self.surfaceforcings  = surfaceforcings()
 		self.basalforcings    = basalforcings()
-		self.materials        = materials()
+		self.materials        = matice()
 		self.friction         = friction()
 		self.flowequation     = flowequation()
@@ -51,7 +59,11 @@
 
 		self.debug            = debug()
-		self.verbose          = verbose()
+		self.verbose          = verbose('solution',True,'qmu',True,'control',True)
 		self.settings         = settings()
 		self.solver           = solver()
+		if ismumps():
+			self.solver.addoptions(DiagnosticVertAnalysisEnum(),mumpsoptions())
+		else:
+			self.solver.addoptions(DiagnosticVertAnalysisEnum(),iluasmoptions())
 		self.cluster          = generic()
 
@@ -70,9 +82,47 @@
 		self.qmu              = qmu()
 
-		self.results          = [];
+		self.results          = OrderedDict()
 		self.radaroverlay     = radaroverlay()
 		self.miscellaneous    = miscellaneous()
 		self.private          = private()
 		#}}}
+
+	def properties(self):    # {{{
+		# ordered list of properties since vars(self) is random
+		return ['mesh',\
+		        'mask',\
+		        'geometry',\
+		        'constants',\
+		        'surfaceforcings',\
+		        'basalforcings',\
+		        'materials',\
+		        'friction',\
+		        'flowequation',\
+		        'timestepping',\
+		        'initialization',\
+		        'rifts',\
+		        'debug',\
+		        'verbose',\
+		        'settings',\
+		        'solver',\
+		        'cluster',\
+		        'balancethickness',\
+		        'diagnostic',\
+		        'groundingline',\
+		        'hydrology',\
+		        'prognostic',\
+		        'thermal',\
+		        'steadystate',\
+		        'transient',\
+		        'autodiff',\
+		        'flaim',\
+		        'inversion',\
+		        'qmu',\
+		        'results',\
+		        'radaroverlay',\
+		        'miscellaneous',\
+		        'private']
+	# }}}
+
 	def __repr__(obj):
 		# {{{ Display
@@ -90,9 +140,9 @@
 		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" % ("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" % ("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"))
@@ -108,7 +158,260 @@
 		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" % ("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;
-		 #}}}
+		return string
+	# }}}
+
+	def checkmessage(self,string):    # {{{
+		print ("model not consistent: %s" % string)
+		self.private.isconsistent=False
+	# }}}
+
+	def extrude(md,*args):    # {{{
+		"""
+		EXTRUDE - vertically extrude a 2d mesh
+
+		   vertically extrude a 2d mesh and create corresponding 3d mesh.
+		   The vertical distribution can:
+		    - follow a polynomial law
+		    - follow two polynomial laws, one for the lower part and one for the upper part of the mesh
+		    - be discribed by a list of coefficients (between 0 and 1)
+ 
+
+		   Usage:
+		      md=extrude(md,numlayers,extrusionexponent);
+		      md=extrude(md,numlayers,lowerexponent,upperexponent);
+		      md=extrude(md,listofcoefficients);
+
+		   Example:
+		      md=extrude(md,8,3);
+		      md=extrude(md,8,3,2);
+		      md=extrude(md,[0 0.2 0.5 0.7 0.9 0.95 1]);
+
+		   See also: MODELEXTRACT, COLLAPSE
+		"""
+
+		#some checks on list of arguments
+		if len(args)>3 or len(args)<1:
+			raise RuntimeError("extrude error message")
+
+		#Extrude the mesh
+		if   len(args)==1:    #list of coefficients
+			clist=args[0]
+			if any(clist<0) or any(clist>1):
+				raise TypeError("extrusioncoefficients must be between 0 and 1")
+			clist.extend([0.,1.])
+			clist.sort()
+			extrusionlist=list(set(clist))
+			numlayers=len(extrusionlist)
+
+		elif len(args)==2:    #one polynomial law
+			if args[1]<=0:
+				raise TypeError("extrusionexponent must be >=0")
+			numlayers=args[0]
+			extrusionlist=(numpy.arange(0.,float(numlayers-1)+1.,1.)/float(numlayers-1))**args[1]
+
+		elif len(args)==3:    #two polynomial laws
+			numlayers=args[0]
+			lowerexp=args[1]
+			upperexp=args[2]
+
+			if args[1]<=0 or args[2]<=0:
+				raise TypeError("lower and upper extrusionexponents must be >=0")
+
+			lowerextrusionlist=(numpy.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**lowerexp/2.
+			upperextrusionlist=(numpy.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**upperexp/2.
+			extrusionlist=numpy.unique(numpy.concatenate((lowerextrusionlist,1.-upperextrusionlist)))
+
+		if numlayers<2:
+			raise TypeError("number of layers should be at least 2")
+		if md.mesh.dimension==3:
+			raise TypeError("Cannot extrude a 3d mesh (extrude cannot be called more than once)")
+
+		#Initialize with the 2d mesh
+		x3d=numpy.empty((0))
+		y3d=numpy.empty((0))
+		z3d=numpy.empty((0))    #the lower node is on the bed
+		thickness3d=md.geometry.thickness    #thickness and bed for these nodes
+		bed3d=md.geometry.bed
+
+		#Create the new layers
+		for i in xrange(numlayers):
+			x3d=numpy.concatenate((x3d,md.mesh.x))
+			y3d=numpy.concatenate((y3d,md.mesh.y))
+			#nodes are distributed between bed and surface accordingly to the given exponent
+			z3d=numpy.concatenate((z3d,bed3d+thickness3d*extrusionlist[i]))
+		number_nodes3d=numpy.size(x3d)    #number of 3d nodes for the non extruded part of the mesh
+
+		#Extrude elements 
+		elements3d=numpy.empty((0,6))
+		for i in xrange(numlayers-1):
+			elements3d=numpy.vstack((elements3d,numpy.hstack((md.mesh.elements+i*md.mesh.numberofvertices,md.mesh.elements+(i+1)*md.mesh.numberofvertices))))    #Create the elements of the 3d mesh for the non extruded part
+		number_el3d=numpy.size(elements3d,axis=0)    #number of 3d nodes for the non extruded part of the mesh
+
+		#Keep a trace of lower and upper nodes
+		mesh.lowervertex=float('NaN')*numpy.ones(number_nodes3d)
+		mesh.uppervertex=float('NaN')*numpy.ones(number_nodes3d)
+		mesh.lowervertex[md.mesh.numberofvertices:]=numpy.arange(1,(numlayers-1)*md.mesh.numberofvertices+1)
+		mesh.uppervertex[:(numlayers-1)*md.mesh.numberofvertices]=numpy.arange(md.mesh.numberofvertices+1,number_nodes3d+1)
+		md.mesh.lowervertex=mesh.lowervertex
+		md.mesh.uppervertex=mesh.uppervertex
+
+		#same for lower and upper elements
+		mesh.lowerelements=float('NaN')*numpy.ones(number_el3d)
+		mesh.upperelements=float('NaN')*numpy.ones(number_el3d)
+		mesh.lowerelements[md.mesh.numberofelements:]=numpy.arange(1,(numlayers-2)*md.mesh.numberofelements+1)
+		mesh.upperelements[:(numlayers-2)*md.mesh.numberofelements]=numpy.arange(md.mesh.numberofelements+1,(numlayers-1)*md.mesh.numberofelements+1)
+		md.mesh.lowerelements=mesh.lowerelements
+		md.mesh.upperelements=mesh.upperelements
+
+		#Save old mesh 
+		md.mesh.x2d=md.mesh.x
+		md.mesh.y2d=md.mesh.y
+		md.mesh.elements2d=md.mesh.elements
+		md.mesh.numberofelements2d=md.mesh.numberofelements
+		md.mesh.numberofvertices2d=md.mesh.numberofvertices
+
+		#Update mesh type
+		md.mesh.dimension=3
+
+		#Build global 3d mesh 
+		md.mesh.elements=elements3d
+		md.mesh.x=x3d
+		md.mesh.y=y3d
+		md.mesh.z=z3d
+		md.mesh.numberofelements=number_el3d
+		md.mesh.numberofvertices=number_nodes3d
+		md.mesh.numberoflayers=numlayers
+
+		#Ok, now deal with the other fields from the 2d mesh:
+
+		#lat long
+		md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node')
+		md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node')
+
+		#drag coefficient is limited to nodes that are on the bedrock.
+		md.friction.coefficient=project3d(md,'vector',md.friction.coefficient,'type','node','layer',1)
+
+		#p and q (same deal, except for element that are on the bedrock: )
+		md.friction.p=project3d(md,'vector',md.friction.p,'type','element')
+		md.friction.q=project3d(md,'vector',md.friction.q,'type','element')
+
+		#observations
+		md.inversion.vx_obs=project3d(md,'vector',md.inversion.vx_obs,'type','node')
+		md.inversion.vy_obs=project3d(md,'vector',md.inversion.vy_obs,'type','node')
+		md.inversion.vel_obs=project3d(md,'vector',md.inversion.vel_obs,'type','node')
+		md.surfaceforcings.mass_balance=project3d(md,'vector',md.surfaceforcings.mass_balance,'type','node')
+		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
+		if not numpy.any(numpy.isnan(md.initialization.vx)):
+			md.initialization.vx=project3d(md,'vector',md.initialization.vx,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.vy)):
+			md.initialization.vy=project3d(md,'vector',md.initialization.vy,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.vz)):
+			md.initialization.vz=project3d(md,'vector',md.initialization.vz,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.vel)):
+			md.initialization.vel=project3d(md,'vector',md.initialization.vel,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.temperature)):
+			md.initialization.temperature=project3d(md,'vector',md.initialization.temperature,'type','node')
+		if not numpy.any(numpy.isnan(md.initialization.waterfraction)):
+			md.initialization.waterfraction=project3d(md,'vector',md.initialization.waterfraction,'type','node')
+
+		#bedinfo and surface info
+		md.mesh.elementonbed=project3d(md,'vector',numpy.ones(md.mesh.numberofelements2d),'type','element','layer',1)
+		md.mesh.elementonsurface=project3d(md,'vector',numpy.ones(md.mesh.numberofelements2d),'type','element','layer',md.mesh.numberoflayers-1)
+		md.mesh.vertexonbed=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d),'type','node','layer',1)
+		md.mesh.vertexonsurface=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d),'type','node','layer',md.mesh.numberoflayers)
+
+		#elementstype
+		if not numpy.any(numpy.isnan(md.flowequation.element_equation)):
+			oldelements_type=md.flowequation.element_equation
+			md.flowequation.element_equation=numpy.zeros(number_el3d)
+			md.flowequation.element_equation=project3d(md,'vector',oldelements_type,'type','element')
+
+		#verticestype
+		if not numpy.any(numpy.isnan(md.flowequation.vertex_equation)):
+			oldvertices_type=md.flowequation.vertex_equation
+			md.flowequation.vertex_equation=numpy.zeros(number_nodes3d)
+			md.flowequation.vertex_equation=project3d(md,'vector',oldvertices_type,'type','node')
+
+		md.flowequation.bordermacayeal=project3d(md,'vector',md.flowequation.bordermacayeal,'type','node')
+		md.flowequation.borderpattyn=project3d(md,'vector',md.flowequation.borderpattyn,'type','node')
+		md.flowequation.borderstokes=project3d(md,'vector',md.flowequation.borderstokes,'type','node')
+
+		#boundary conditions
+		md.diagnostic.spcvx=project3d(md,'vector',md.diagnostic.spcvx,'type','node')
+		md.diagnostic.spcvy=project3d(md,'vector',md.diagnostic.spcvy,'type','node')
+		md.diagnostic.spcvz=project3d(md,'vector',md.diagnostic.spcvz,'type','node')
+		md.thermal.spctemperature=project3d(md,'vector',md.thermal.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',float('NaN'))
+		md.prognostic.spcthickness=project3d(md,'vector',md.prognostic.spcthickness,'type','node')
+		md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node')
+		md.diagnostic.referential=project3d(md,'vector',md.diagnostic.referential,'type','node')
+
+		#in 3d, pressureload: [node1 node2 node3 node4 element]
+		pressureload_layer1=numpy.hstack((md.diagnostic.icefront[:,0:2],md.diagnostic.icefront[:,1:2]+md.mesh.numberofvertices2d,md.diagnostic.icefront[:,0:1]+md.mesh.numberofvertices2d,md.diagnostic.icefront[:,2:4]))    #Add two columns on the first layer 
+		pressureload=numpy.empty((0,6))
+		for i in xrange(numlayers-1):
+			pressureload=numpy.vstack((pressureload,numpy.hstack((pressureload_layer1[:,0:4]+i*md.mesh.numberofvertices2d,pressureload_layer1[:,4:5]+i*md.mesh.numberofelements2d,pressureload_layer1[:,5:6]))))
+		md.diagnostic.icefront=pressureload
+
+		#connectivity
+		md.mesh.elementconnectivity=numpy.tile(md.mesh.elementconnectivity,(numlayers-1,1))
+		md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity==0)]=float('NaN')
+		for i in xrange(1,numlayers-1):
+			md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:] \
+				=md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:]+md.mesh.numberofelements2d
+		md.mesh.elementconnectivity[numpy.nonzero(numpy.isnan(md.mesh.elementconnectivity))]=0
+
+		#materials
+		md.materials.rheology_B=project3d(md,'vector',md.materials.rheology_B,'type','node')
+		md.materials.rheology_n=project3d(md,'vector',md.materials.rheology_n,'type','element')
+
+		#parameters
+		md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node')
+		md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node')
+		md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node')
+		md.geometry.bed=project3d(md,'vector',md.geometry.bed,'type','node')
+		md.geometry.bathymetry=project3d(md,'vector',md.geometry.bathymetry,'type','node')
+		md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node')
+		md.mask.elementonfloatingice=project3d(md,'vector',md.mask.elementonfloatingice,'type','element')
+		md.mask.vertexonfloatingice=project3d(md,'vector',md.mask.vertexonfloatingice,'type','node')
+		md.mask.elementongroundedice=project3d(md,'vector',md.mask.elementongroundedice,'type','element')
+		md.mask.vertexongroundedice=project3d(md,'vector',md.mask.vertexongroundedice,'type','node')
+		md.mask.elementonwater=project3d(md,'vector',md.mask.elementonwater,'type','element')
+		md.mask.vertexonwater=project3d(md,'vector',md.mask.vertexonwater,'type','node')
+		if not numpy.any(numpy.isnan(md.inversion.cost_functions_coefficients)):
+			md.inversion.cost_functions_coefficients=project3d(md,'vector',md.inversion.cost_functions_coefficients,'type','node');end;
+		if not numpy.any(numpy.isnan(md.inversion.min_parameters)):
+			md.inversion.min_parameters=project3d(md,'vector',md.inversion.min_parameters,'type','node')
+		if not numpy.any(numpy.isnan(md.inversion.max_parameters)):
+			md.inversion.max_parameters=project3d(md,'vector',md.inversion.max_parameters,'type','node')
+		if not numpy.any(numpy.isnan(md.qmu.partition)):
+			md.qmu.partition=project3d(md,'vector',numpy.transpose(md.qmu.partition),'type','node')
+		if(md.surfaceforcings.isdelta18o):
+			md.surfaceforcings.temperatures_lgm=project3d(md,'vector',md.surfaceforcings.temperatures_lgm,'type','node')
+		if(md.surfaceforcings.isdelta18o):
+			md.surfaceforcings.temperatures_presentday=project3d(md,'vector',md.surfaceforcings.temperatures_presentday,'type','node')
+		if(md.surfaceforcings.isdelta18o):
+			md.surfaceforcings.precipitations_presentday=project3d(md,'vector',md.surfaceforcings.precipitations_presentday,'type','node')
+
+		#Put lithostatic pressure if there is an existing pressure
+		if not numpy.any(numpy.isnan(md.initialization.pressure)):
+			md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z)
+
+		#special for thermal modeling:
+		md.basalforcings.melting_rate=project3d(md,'vector',md.basalforcings.melting_rate,'type','node','layer',1)
+		if not numpy.any(numpy.isnan(md.basalforcings.geothermalflux)):
+			md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1)    #bedrock only gets geothermal flux
+
+		#increase connectivity if less than 25:
+		if md.mesh.average_vertex_connectivity<=25:
+			md.mesh.average_vertex_connectivity=100
+
+		return md
+		# }}}
+
Index: /issm/trunk/src/m/classes/model/planet.m
===================================================================
--- /issm/trunk/src/m/classes/model/planet.m	(revision 13394)
+++ /issm/trunk/src/m/classes/model/planet.m	(revision 13395)
@@ -6,43 +6,59 @@
 classdef planet < model
     properties (SetAccess=public) %Planet fields
-		 % {{{
-		 %Planet specific fields
-		 r=NaN;
-		 theta=NaN;
-		 phi=NaN;
+	 end
+	 methods
+		 function md = planet(varargin) % {{{
+
+			 switch nargin
+				 case 0
+					 md=setdefaultparameters(md);
+				 otherwise
+					 error('planet constructor error message: 0 of 1 argument only in input.');
+				 end
+		 end
+		 %}}}
+		 function md = setdefaultparameters(md) % {{{
+
+			 %initialize subclasses
+			 md.mesh             = planetmesh();
+			 md.mask             = mask();
+			 md.constants        = constants();
+			 md.geometry         = geometry();
+			 md.initialization   = initialization();
+			 md.surfaceforcings  = surfaceforcings();
+			 md.basalforcings    = basalforcings();
+			 md.friction         = friction();
+			 md.rifts            = rifts();
+			 md.timestepping     = timestepping();
+			 md.groundingline    = groundingline();
+			 md.materials        = materials();
+			 md.flowequation     = flowequation();
+			 md.debug            = debug();
+			 md.verbose          = verbose('solution',true,'qmu',true,'control',true);
+			 md.settings         = settings();
+			 md.solver           = solver();
+			 if ismumps(),
+				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),mumpsoptions());
+			 else
+				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),iluasmoptions());
+			 end
+			 md.cluster          = generic();
+			 md.balancethickness = balancethickness();
+			 md.diagnostic       = diagnostic();
+			 md.hydrology        = hydrology();
+			 md.prognostic       = prognostic();
+			 md.thermal          = thermal();
+			 md.steadystate      = steadystate();
+			 md.transient        = transient();
+			 md.autodiff         = autodiff();
+			 md.flaim            = flaim();
+			 md.inversion        = inversion();
+			 md.qmu              = qmu();
+			 md.radaroverlay     = radaroverlay();
+			 md.results          = struct();
+			 md.miscellaneous    = miscellaneous();
+			 md.private          = private();
+		 end
 		 %}}}
 	 end
-	 methods
-		function md=planetmesh(md,varargin) % {{{
-		%PLANETMESH: build 2d shell mesh
-		%
-		% Usage: md=planetmesh(md,'method','mixed','radius',6378000,'angleresol',1);
-		%        md=planetmesh(md,'method','tria','shape','iso','radius',6378000,'refinement',5);
-		%
-
-		%recover options
-		options=pairoptions(varargin{:});
-
-		method=getfieldvalue(options,'method','mixed');
-		
-		if strcmpi(method,'mixed'),
-			%recover radius and angleresol: 
-			radius=getfieldvalue(options,'radius',6378000); %earth radius as default
-			angleresol=getfieldvalue(options,'angleresol',10); %10 degree resolution
-			
-			%call mixed mesh 
-			md=planetmixedmesh(md,radius,angleresol);
-		else
-			%recover radius, shape and level of refinmenet
-			radius=getfieldvalue(options,'radius',6378000); %earth radius as default
-			refinement=getfieldvalue(options,'refinement',5); %refine 5 times
-			shape=getfieldvalue(options,'shape','ico'); 
-			
-			%call triangular mesh
-			md=planettrimesh(md,shape,radius,refinement);
-		end
-
-		end
-		% }}}
-	 end
  end
Index: /issm/trunk/src/m/classes/modellist.m
===================================================================
--- /issm/trunk/src/m/classes/modellist.m	(revision 13394)
+++ /issm/trunk/src/m/classes/modellist.m	(revision 13395)
@@ -10,4 +10,116 @@
 	end
 	methods
+		function md_list=modelsextract(md,flags,minel,varargin) % {{{
+			%modelsextract - extract several self contained models according to a list of element flags.
+			%
+			%   The difference between this routine and the modelextract.m routine (without an 's') is that 
+			%   as many models are extracted as there are closed contours defined in area. 
+			%   This routine is needed for example when doing data assimilation of ice shelves in Antarctica. 
+			%   Many independent ice shelves are present, and we don't want data assimilation on one ice shelf 
+			%   to be hindered by another totally independent ice shelf.
+			%
+			%   Usage:
+			%      md_list=modelsextract(md,elementfalgs,minel);
+			%
+			%   Examples:
+			%      md_list=modelsextract(md,md.mask.elementonfloatingice,1000);
+			%
+			%   See also: EXTRUDE, COLLAPSE, MODELEXTRACT
+
+			disp('selecting pools of elements');
+			%go through flags and build as many independent element flags as there are groups of connected 1s
+			%in flags.
+
+			%2D or 3D?
+			if md.mesh.dimension==3,
+				numberofelements=md.mesh.numberofelements2d; %this will be forgotten when we get out.
+				flags=project2d(md,flags,1);
+			else
+				numberofelements=md.mesh.numberofelements;
+			end
+
+			%recover extra arguments: 
+			distance=0;
+			if nargin==4,
+				distance=varargin{1};
+			end
+
+			flag_list=cell(0,1);
+
+			for i=1:size(flags,1),
+
+				if (flags(i)),
+
+					%ok, we are sure element i is part of a new pool.
+					pool=zeros(numberofelements,1);
+					pool=PropagateFlagsFromConnectivity(md.mesh.elementconnectivity,pool,i,flags);
+					flag_list{end+1,1}=pool;
+
+					%speed up rest of computation by taking pool out of flags: 
+					pos=find(pool);flags(pos)=0;
+
+				end
+			end
+
+			%go through flag_list and discard any pool of less than minel elements: 
+			ex_pos=[];
+			for i=1:length(flag_list),
+				if length(find(flag_list{i}))<minel,
+					ex_pos=[ex_pos; i];
+				end
+			end
+			flag_list(ex_pos)=[];
+
+			%now, if distance was specified, expand the flag_list by distance km: 
+			if distance,
+				for i=1:length(flag_list),
+					flag_list{i}=PropagateFlagsUntilDistance(md,flag_list{i},distance);
+				end
+			end
+
+			%now, go use the pools of flags to extract models: 
+			disp(['extracting ' num2str(size(flag_list,1)) ' models']);
+			models=cell(0,1);
+
+			for i=1:size(flag_list,1),
+				disp(['   ' num2str(i) '/' num2str(size(flag_list,1))]);
+				if md.mesh.dimension==3,
+					flags2d=flag_list{i};
+					realflags=project3d(md,flags2d,'element');
+				else
+					realflags=flag_list{i};
+				end
+				models{end+1,1}=modelextract(md,realflags);
+			end
+
+			%return model list
+			md_list=modellist(models);
+
+		end %end of this function }}}
+		function md_list=modelsextractfromdomains(md,directory) % {{{
+			%modelsextractfromdomains- extract several self contained models according to a list of domains
+			%
+			%   Usage:
+			%      md_list=modelsextractfromdomains(md,'Basins/');
+			%
+			%   Examples:
+			%      md_list=modelsextract(md,'Basins/');
+			%
+			%   See also: MODELSEXTRACTS, MODELEXTRACT
+
+			%go into directory and get list of files.
+			cd(directory);
+			basins=listfiles;
+			cd ..
+
+			models=cell(0,1);
+			for i=1:length(basins),
+				models{end+1,1}=modelextract(md,[directory '/' basins{i}]);
+			end
+
+			%return model list: 
+			md_list=modellist(models);
+
+		end % }}}
 		function obj = modellist(varargin) % {{{
 
@@ -180,2 +292,96 @@
 	end
 end
+
+function BuildMultipleQueueingScript(cluster,name,executionpath,codepath)% {{{
+%BUILDMULTIPLEQUEUEINGSCRIPT - 
+%
+%   Usage:
+%      BuildMultipleQueueingScript(executionpath,codepath)
+
+disp('building queueing script');
+
+%First try and figure out if there is a special script for this particular cluster
+function_name=['BuildMultipleQueueingScript' cluster];
+
+%some specific treatment of identical cluster, gemini, castor and pollux
+if strcmpi(cluster,'castor') || strcmpi(cluster,'pollux'),
+	function_name='BuildMultipleQueueingScriptgemini';
+end
+
+if exist(function_name,'file'),
+	%Call this function:
+	eval([function_name '(name,executionpath,codepath);']);
+else
+	%Call the generic BuildQueueingScript:
+	BuildMultipleQueueingScriptGeneric(name,executionpath,codepath);
+end
+end % }}}
+function BuildQueueingScriptgemini(name,executionpath,codepath)% {{{
+%BUILDQUEUEINGSCRIPTGEMINI - ...
+%
+%   Usage:
+%      BuildQueueingScriptgemini(md,executionpath,codepath)
+
+scriptname=[name '.queue'];
+
+fid=fopen(scriptname,'w');
+if fid==-1,
+	error(['BuildQueueingScriptgeminierror message: could not open ' scriptname ' file for ascii writing']);
+end
+
+fprintf(fid,'#!/bin/sh\n');
+fprintf(fid,'cd %s\n',executionpath);
+fprintf(fid,'mkdir %s\n',name);
+fprintf(fid,'cd %s\n',name);
+fprintf(fid,'mv ../ModelList.tar.gz ./\n');
+fprintf(fid,'tar -zxvf ModelList.tar.gz\n');
+fprintf(fid,'foreach i (%s-*vs*.queue)\n',name);
+fprintf(fid,'qsub $i\n');
+fprintf(fid,'end\n');
+fclose(fid);
+end% }}}
+function LaunchMultipleQueueJob(cluster,name,executionpath)% {{{
+%LAUNCHMULTIPLEQUEUEJOB - ...
+%
+%   Usage:
+%      LaunchMultipleQueueJob(executionpath)
+
+%First try and figure out if there is a special script for thie particular cluster
+function_name=['LaunchMultipleQueueJob' cluster];
+
+%some specific treatment of identical cluster, gemini, castor and pollux
+if strcmpi(cluster,'castor') || strcmpi(cluster,'pollux'),
+	function_name='LaunchMultipleQueueJobgemini';
+end
+
+if exist(function_name,'file'),
+	%Call this function:
+	eval([function_name '(cluster,name,executionpath);']);
+else
+	%Call the generic LaunchMultipleQueueJob:
+	LaunchMultipleQueueJobGeneric(cluster,name,executionpath);
+end
+end% }}}
+function md=LaunchMultipleQueueJobgemini(cluster,name,executionpath)% {{{
+%LAUNCHMULTIPLEQUEUEJOBGEMINI - Launch multiple queueing script on Gemini cluster
+%
+%   Usage:
+%      LaunchMultipleQueueJobgemini(cluster,name,executionpath)
+
+
+%first, check we have the binary file and the queueing script
+if ~exist([ name '.queue'],'file'),
+	error('LaunchMultipleQueueJobgemini error message: queueing script issing, cannot go forward');
+end
+
+if ~exist('ModelList.tar.gz','file'),
+	error('LaunchMultipleQueueJobgemini error message: inputs models file missing, cannot go forward');
+end
+
+%upload both files to cluster
+disp('uploading input file,  queueing script and variables script');
+eval(['!scp ModelList.tar.gz ' name '.queue '  cluster ':' executionpath]);
+
+disp('launching solution sequence on remote cluster');
+issmssh(cluster,login,['"cd ' executionpath ' && source ' name '.queue "']);
+end% }}}
Index: /issm/trunk/src/m/classes/oldclasses/README
===================================================================
--- /issm/trunk/src/m/classes/oldclasses/README	(revision 13395)
+++ /issm/trunk/src/m/classes/oldclasses/README	(revision 13395)
@@ -0,0 +1,3 @@
+We put here all old classes so that matlab can still load old models
+When an object is renamed or deleted, matlab is not able to load it
+anymore. We keep it here so that matlab can load the object
Index: /issm/trunk/src/m/classes/oldclasses/materials.m
===================================================================
--- /issm/trunk/src/m/classes/oldclasses/materials.m	(revision 13395)
+++ /issm/trunk/src/m/classes/oldclasses/materials.m	(revision 13395)
@@ -0,0 +1,21 @@
+%OLD materials class definition
+
+classdef materials
+	properties (SetAccess=public) 
+		rho_ice                    = 0.;
+		rho_water                  = 0.;
+		rho_freshwater             = 0.;
+		mu_water                   = 0.;
+		heatcapacity               = 0.;
+		latentheat                 = 0.;
+		thermalconductivity        = 0.;
+		meltingpoint               = 0.;
+		beta                       = 0.;
+		mixed_layer_capacity       = 0.;
+		thermal_exchange_velocity  = 0.;
+		rheology_B   = NaN;
+		rheology_n   = NaN;
+		rheology_Z   = NaN;
+		rheology_law = '';
+	end
+end
Index: /issm/trunk/src/m/classes/pairoptions.py
===================================================================
--- /issm/trunk/src/m/classes/pairoptions.py	(revision 13394)
+++ /issm/trunk/src/m/classes/pairoptions.py	(revision 13395)
@@ -1,16 +1,17 @@
-"""
-PAIROPTIONS class definition
+from collections import OrderedDict
+from WriteData import *
+
+class pairoptions(object):
+	"""
+	PAIROPTIONS class definition
  
-    Usage:
-       pairoptions=pairoptions();
-       pairoptions=pairoptions('module',true,'solver',false);
-"""
-
-from WriteData import *
-
-class pairoptions(object):
+	   Usage:
+	      pairoptions=pairoptions();
+	      pairoptions=pairoptions('module',true,'solver',false);
+	"""
+
 	def __init__(self,*arg):
 		self.functionname = ''
-		self.list         = {}
+		self.list         = OrderedDict()
 
 		#get calling function name
@@ -36,5 +37,5 @@
 		#go through arg and build list of objects
 		for i in xrange(numoptions):
-			if isinstance(arg[2*i],str):
+			if isinstance(arg[2*i],(str,unicode)):
 				self.list[arg[2*i]] = arg[2*i+1];
 			else:
@@ -45,5 +46,5 @@
 	def addfield(self,field,value):    # {{{
 		"""ADDFIELD - add a field to an options list"""
-		if isinstance(field,str):
+		if isinstance(field,(str,unicode)):
 			if field in self.list:
 				print "WARNING: field '%s' with value=%s exists and will be overwritten with value=%s." % (field,str(self.list[field]),str(value))
@@ -53,6 +54,6 @@
 	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:
+		if isinstance(field,(str,unicode)):
+			if field not in self.list:
 				self.list[field] = value
 	# }}}
@@ -100,5 +101,5 @@
 			s+="   list: (%ix%i)\n\n" % (len(self.list),2)
 			for item in self.list.iteritems():
-				if   isinstance(item[1],str):
+				if   isinstance(item[1],(str,unicode)):
 					s+="     field: %-10s value: '%s'\n" % (item[0],item[1])
 				elif isinstance(item[1],(bool,int,long,float)):
@@ -117,5 +118,5 @@
 		if field == None or field == '':
 			raise ValueError('exist error message: bad usage');
-		if not isinstance(field,str):
+		if not isinstance(field,(str,unicode)):
 			raise TypeError("exist error message: field '%s' should be a string." % str(field));
 
@@ -157,5 +158,5 @@
 		if field == None or field == '':
 			raise ValueError('getfieldvalue error message: bad usage');
-		if not isinstance(field,str):
+		if not isinstance(field,(str,unicode)):
 			raise TypeError("getfieldvalue error message: field '%s' should be a string." % str(field));
 
@@ -204,5 +205,5 @@
 
 			#Write option value
-			if   isinstance(value,str):
+			if   isinstance(value,(str,unicode)):
 				WriteData(fid,'enum',(firstindex-1)+2*i+2,'data',value,'format','String')
 			elif isinstance(value,(bool,int,long,float)):
Index: /issm/trunk/src/m/classes/planetmesh.m
===================================================================
--- /issm/trunk/src/m/classes/planetmesh.m	(revision 13395)
+++ /issm/trunk/src/m/classes/planetmesh.m	(revision 13395)
@@ -0,0 +1,127 @@
+%MESH class definition
+%
+%   Usage:
+%      planetmesh=planetmesh();
+
+classdef planetmesh
+	properties (SetAccess=public) 
+		x                           = NaN;
+		y                           = NaN;
+		z                           = NaN;
+		r                           = NaN;
+		theta                       = NaN;
+		phi                         = NaN
+		elements                    = NaN
+		dimension                   = 0;
+		numberoflayers              = 0;
+		numberofelements            = 0;
+		numberofvertices            = 0;
+		
+		lat                         = NaN
+		long                        = NaN
+
+		vertexconnectivity          = NaN
+		elementconnectivity         = NaN
+		average_vertex_connectivity = 0;
+	end
+	methods
+		function obj = planetmesh(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%the connectivity is the avergaded number of nodes linked to a
+			%given node through an edge. This connectivity is used to initially
+			%allocate memory to the stiffness matrix. A value of 16 seems to
+			%give a good memory/time ration. This value can be checked in
+			%trunk/test/Miscellaneous/runme.m
+			obj.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'planetmesh.x','NaN',1,'size',[md.planetmesh.numberofvertices 1]);
+			md = checkfield(md,'planetmesh.y','NaN',1,'size',[md.planetmesh.numberofvertices 1]);
+			md = checkfield(md,'planetmesh.z','NaN',1,'size',[md.planetmesh.numberofvertices 1]);
+			md = checkfield(md,'planetmesh.r','NaN',1,'size',[md.planetmesh.numberofvertices 1]);
+			md = checkfield(md,'planetmesh.theta','NaN',1,'size',[md.planetmesh.numberofvertices 1]);
+			md = checkfield(md,'planetmesh.phi','NaN',1,'size',[md.planetmesh.numberofvertices 1]);
+			md = checkfield(md,'planetmesh.elements','NaN',1,'>',0,'values',1:md.planetmesh.numberofvertices);
+			if(md.planetmesh.dimension==2),
+				md = checkfield(md,'planetmesh.elements','size',[md.planetmesh.numberofelements 3]);
+			else
+				md = checkfield(md,'planetmesh.elements','size',[md.planetmesh.numberofelements 6]);
+			end
+			if any(~ismember(1:md.planetmesh.numberofvertices,sort(unique(md.planetmesh.elements(:)))));
+				md = checkmessage(md,'orphan nodes have been found. Check the planetmesh outline');
+			end
+			md = checkfield(md,'planetmesh.dimension','values',[2 3]);
+			md = checkfield(md,'planetmesh.numberoflayers','>=',0);
+			md = checkfield(md,'planetmesh.numberofelements','>',0);
+			md = checkfield(md,'planetmesh.numberofvertices','>',0);
+			%no checks for numberofedges lat long and hemisphere
+			if (md.planetmesh.dimension==2),
+				md = checkfield(md,'planetmesh.average_vertex_connectivity','>=',9,'message','''planetmesh.average_vertex_connectivity'' should be at least 9 in 2d');
+			else
+				md = checkfield(md,'planetmesh.average_vertex_connectivity','>=',24,'message','''planetmesh.average_vertex_connectivity'' should be at least 24 in 3d');
+			end
+			md = checkfield(md,'planetmesh.elementconnectivity','size',[md.planetmesh.numberofelements 3],'NaN',1);
+
+			%Solution specific checks
+			switch(solution),
+				case PrognosticSolutionEnum(),
+					if md.prognostic.stabilization==3,
+						md = checkfield(md,'planetmesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d planetmeshes');
+					end
+				case TransientSolutionEnum(),
+					if md.transient.isprognostic & md.prognostic.stabilization==3,
+						md = checkfield(md,'planetmesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d planetmeshes');
+					end
+				case ThermalSolutionEnum(),
+					md = checkfield(md,'planetmesh.dimension','values',3,'message','thermal solution only supported on 3d planetmeshes');
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Mesh:')); 
+
+			disp(sprintf('\n      Elements and vertices:'));
+			fielddisplay(obj,'numberofelements','number of elements');
+			fielddisplay(obj,'numberofvertices','number of vertices');
+			fielddisplay(obj,'elements','index into (x,y,z), coordinates of the vertices');
+			fielddisplay(obj,'x','vertices x coordinate');
+			fielddisplay(obj,'y','vertices y coordinate');
+			fielddisplay(obj,'z','vertices z coordinate');
+			fielddisplay(obj,'r','vertices r coordinate');
+			fielddisplay(obj,'theta','vertices theta coordinate');
+			fielddisplay(obj,'phi','vertices phi coordinate');
+
+			disp(sprintf('\n      Properties:'));
+			fielddisplay(obj,'dimension','planetmesh dimension (2d or 3d)');
+			fielddisplay(obj,'numberoflayers','number of extrusion layers');
+			
+			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+
+		end % }}}
+		function marshall(obj,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','z','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','r','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','theta','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','phi','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'fieldname','dimension','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberoflayers','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','elementconnectivity','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',obj,'fieldname','average_vertex_connectivity','format','Integer');
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/private.m
===================================================================
--- /issm/trunk/src/m/classes/private.m	(revision 13394)
+++ /issm/trunk/src/m/classes/private.m	(revision 13395)
@@ -31,5 +31,5 @@
 			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');
+			fielddisplay(obj,'bamg','structure with mesh properties constructed if bamg is used to mesh the domain');
 			fielddisplay(obj,'solution','type of solution launched');
 
Index: /issm/trunk/src/m/classes/private.py
===================================================================
--- /issm/trunk/src/m/classes/private.py	(revision 13394)
+++ /issm/trunk/src/m/classes/private.py	(revision 13395)
@@ -1,12 +1,23 @@
 #module imports
+from collections import OrderedDict
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
 
-class private:
+class private(object):
+	"""
+	PRIVATE class definition
+
+	   Usage:
+	      private=private();
+	"""
+
 	#properties
 	def __init__(self):
 		# {{{ Properties
-		self.runtimename = ''
-		self.bamg        = {}
-		self.solution    = '';
+		self.isconsistent = True
+		self.runtimename  = ''
+		self.bamg         = OrderedDict()
+		self.solution     = ''
 
 		#set defaults
@@ -14,16 +25,22 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   private parameters: do not change'
-		string="%s\n%s"%(string,fielddisplay(obj,'runtimename','name of the run launched'))
-		string="%s\n%s"%(string,fielddisplay(obj,'bamg','structure with mesh properties construced if bamg is used to mesh the domain'))
-		string="%s\n%s"%(string,fielddisplay(obj,'solution','type of solution launched'))
+
+		string="%s\n%s"%(string,fielddisplay(self,'isconsistent','is model self consistent'))
+		string="%s\n%s"%(string,fielddisplay(self,'runtimename','name of the run launched'))
+		string="%s\n%s"%(string,fielddisplay(self,'bamg','structure with mesh properties constructed if bamg is used to mesh the domain'))
+		string="%s\n%s"%(string,fielddisplay(self,'solution','type of solution launched'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		return md
+	# }}}
+
Index: /issm/trunk/src/m/classes/prognostic.m
===================================================================
--- /issm/trunk/src/m/classes/prognostic.m	(revision 13394)
+++ /issm/trunk/src/m/classes/prognostic.m	(revision 13395)
@@ -38,6 +38,6 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			%Early return,
-			if ~ismember(PrognosticAnalysisEnum,analyses) |  (solution==TransientSolutionEnum & md.transient.isprognostic==0), return; end
+			%Early return
+			if ~ismember(PrognosticAnalysisEnum(),analyses) |  (solution==TransientSolutionEnum() & md.transient.isprognostic==0), return; end
 
 			md = checkfield(md,'prognostic.spcthickness','forcing',1);
@@ -62,5 +62,5 @@
 			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1);
 			WriteData(fid,'object',obj,'fieldname','min_thickness','format','Double');
-			WriteData(fid,'data',StringToEnum(obj.hydrostatic_adjustment),'format','Integer','enum',PrognosticHydrostaticAdjustmentEnum);
+			WriteData(fid,'data',StringToEnum(obj.hydrostatic_adjustment),'format','Integer','enum',PrognosticHydrostaticAdjustmentEnum());
 			WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
 			WriteData(fid,'object',obj,'fieldname','vertex_pairing','format','DoubleMat','mattype',3);
Index: /issm/trunk/src/m/classes/prognostic.py
===================================================================
--- /issm/trunk/src/m/classes/prognostic.py	(revision 13394)
+++ /issm/trunk/src/m/classes/prognostic.py	(revision 13395)
@@ -1,6 +1,17 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import *
+from WriteData import *
 
-class prognostic:
+class prognostic(object):
+	"""
+	PROGNOSTIC class definition
+
+	   Usage:
+	      prognostic=prognostic();
+	"""
+
 	#properties
 	def __init__(self):
@@ -17,31 +28,54 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   Prognostic solution parameters:'
-		string="%s\n\n%s"%(string,fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'min_thickness','minimum ice thickness allowed'))
-		string="%s\n%s"%(string,fielddisplay(obj,'hydrostatic_adjustment','adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute'' '))
-		string="%s\n%s"%(string,fielddisplay(obj,'stabilization','0->no, 1->artificial_diffusivity, 2->streamline upwinding, 3->discontinuous Galerkin'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'min_thickness','minimum ice thickness allowed'))
+		string="%s\n%s"%(string,fielddisplay(self,'hydrostatic_adjustment','adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute'' '))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0->no, 1->artificial_diffusivity, 2->streamline upwinding, 3->discontinuous Galerkin'))
 
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#Type of stabilization to use 0:nothing 1:artificial_diffusivity 3:Discontinuous Galerkin
-		obj.stabilization=1
+		self.stabilization=1
 
 		#Factor applied to compute the penalties kappa=max(stiffness matrix)*10^penalty_factor
-		obj.penalty_factor=3
+		self.penalty_factor=3
 
 		#Minimum ice thickness that can be used
-		obj.min_thickness=1
+		self.min_thickness=1
 
 		#Hydrostatic adjustment
-		obj.hydrostatic_adjustment='Absolute'
+		self.hydrostatic_adjustment='Absolute'
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if (PrognosticAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum() and not md.transient.isprognostic):
+			return md
+
+		md = checkfield(md,'prognostic.spcthickness','forcing',1)
+		md = checkfield(md,'prognostic.hydrostatic_adjustment','values',['Absolute','Incremental'])
+		md = checkfield(md,'prognostic.stabilization','values',[0,1,2,3])
+		md = checkfield(md,'prognostic.min_thickness','>',0)
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','min_thickness','format','Double')
+		WriteData(fid,'data',StringToEnum(self.hydrostatic_adjustment)[0],'format','Integer','enum',PrognosticHydrostaticAdjustmentEnum())
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
+		WriteData(fid,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3)
+		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
+	# }}}
+
Index: /issm/trunk/src/m/classes/qmu.m
===================================================================
--- /issm/trunk/src/m/classes/qmu.m	(revision 13394)
+++ /issm/trunk/src/m/classes/qmu.m	(revision 13395)
@@ -47,18 +47,6 @@
 					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,
-					md = checkmessage(md,['user supplied partition should be indexed from 0 (c-convention)']);
-				end
 				if min(md.qmu.partition)~=0,
 					md = checkmessage(md,['partition vector not indexed from 0 on']);
-				end
-				if max(md.qmu.partition)>=md.mesh.numberofvertices,
-					md = checkmessage(md,['partition vector cannot have maximum index larger than number of nodes']);
-				end
-				if ~isempty(find(md.qmu.partition<0)),
-					md = checkmessage(md,['partition vector cannot have values less than 0']);
-				end
-				if ~isempty(find(md.qmu.partition>=md.qmu.numberofpartitions)),
-					md = checkmessage(md,['partition vector cannot have values more than md.qmu.numberofpartitions-1']);
 				end
 				if max(md.qmu.partition)>=md.qmu.numberofpartitions,
@@ -140,6 +128,6 @@
 				end
 			end
-			fielddisplay(obj,'partition','user provided mesh partitionition, defaults to metis if not specified') 
-			fielddisplay(obj,'numberofpartitions','number of partitions for semi-descrete qmu') 
+			fielddisplay(obj,'partition','user provided mesh partitioning, defaults to metis if not specified') 
+			fielddisplay(obj,'numberofpartitions','number of partitions for semi-discrete qmu') 
 			fielddisplay(obj,'variabledescriptors','');
 			fielddisplay(obj,'responsedescriptors','');
Index: /issm/trunk/src/m/classes/qmu.py
===================================================================
--- /issm/trunk/src/m/classes/qmu.py	(revision 13394)
+++ /issm/trunk/src/m/classes/qmu.py	(revision 13395)
@@ -1,15 +1,28 @@
 #module imports
+import numpy
+from collections import OrderedDict
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
+from MatlabFuncs import *
 
-class qmu:
+class qmu(object):
+	"""
+	QMU class definition
+
+	   Usage:
+	      qmu=qmu();
+	"""
+
 	#properties
 	def __init__(self):
 		# {{{ Properties
 		self.isdakota                    = 0
-		self.variables                   = {}
-		self.responses                   = {}
-		self.method                      = {}
-		self.params                      = {}
-		self.results                     = {}
+		self.variables                   = OrderedDict()
+		self.responses                   = OrderedDict()
+		self.method                      = OrderedDict()
+		self.params                      = OrderedDict()
+		self.results                     = OrderedDict()
 		self.partition                   = float('NaN')
 		self.numberofpartitions          = 0
@@ -27,13 +40,116 @@
 
 		#}}}
-	def __repr__(obj):
-		# {{{ Display
-		string="   qmu parameters: not implemented yet!"
-		return string
-		#}}}
-		
-	def setdefaultparameters(obj):
+
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not md.qmu.isdakota:
+			return
+
+		if not md.qmu.params.evaluation_concurrency==1:
+			md.checkmessage("concurrency should be set to 1 when running dakota in library mode")
+		if md.qmu.partition:
+			if not numpy.size(md.qmu.partition)==md.mesh.numberofvertices:
+				md.checkmessage("user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1")
+			if not min(md.qmu.partition)==0:
+				md.checkmessage("partition vector not indexed from 0 on")
+			if max(md.qmu.partition)>=md.qmu.numberofpartitions:
+				md.checkmessage("for qmu analysis, partitioning vector cannot go over npart, number of partition areas")
+
+		if not strcmpi(md.cluster.name,'none'):
+			if not md.settings.waitonlock:
+				md.checkmessage("waitonlock should be activated when running qmu in parallel mode!")
+
+		return md
+	# }}}
+
+	def __repr__(self):    # {{{
+		s ='   qmu parameters:\n'
+
+		s+="%s\n" % fielddisplay(self,'isdakota','is qmu analysis activated?')
+		for i,variable in enumerate(self.variables.iteritems()):
+			s+="         variables%s:  (arrays of each variable class)\n" % \
+				string_dim(self.variables,i)
+			fnames=vars(variable)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="'            %-*s:    [%ix%i]    '%s'\n" % \
+					(maxlen+1,fname,size(getattr(variable,fname)),type(getattr(variable,fname)))
+
+		for i,response in enumerate(self.responses.iteritems()):
+			s+="         responses%s:  (arrays of each response class)\n" % \
+				string_dim(self.responses,i)
+			fnames=vars(response)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="            %-*s:    [%ix%i]    '%s'\n" % \
+					(maxlen+1,fname,size(getattr(response,fname)),type(getattr(response,fname)))
+
+		s+="%s\n" % fielddisplay(self,'numberofresponses','number of responses') 
+
+		for i,method in enumerate(self.method.iteritems()):
+			if isinstance(method,'dakota_method'):
+				s+="            method%s :    '%s'\n" % \
+					(string_dim(method,i),method.method)
+
+		for i,param in enumerate(self.params.iteritems()):
+			s+="         params%s:  (array of method-independent parameters)\n" % \
+				string_dim(self.params,i)
+			fnames=vars(param)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="            %-*s: %s\n" % \
+					(maxlen+1,fname,any2str(getattr(param,fname)))
+
+		for i,result in enumerate(self.results.iteritems()):
+			s+="         results%s:  (information from dakota files)\n" % \
+				string_dim(self.results,i)
+			fnames=vars(result)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="            %-*s:    [%ix%i]    '%s'\n" % \
+					(maxlen+1,fname,size(getattr(result,fname)),type(getattr(result,fname)))
+
+		s+="%s\n" % fielddisplay(self,'partition','user provided mesh partitioning, defaults to metis if not specified') 
+		s+="%s\n" % fielddisplay(self,'numberofpartitions','number of partitions for semi-discrete qmu') 
+		s+="%s\n" % fielddisplay(self,'variabledescriptors','')
+		s+="%s\n" % fielddisplay(self,'responsedescriptors','')
+		s+="%s\n" % fielddisplay(self,'method','array of dakota_method class')
+		s+="%s\n" % fielddisplay(self,'mass_flux_profile_directory','directory for mass flux profiles')
+		s+="%s\n" % fielddisplay(self,'mass_flux_profiles','list of mass_flux profiles')
+		s+="%s\n" % fielddisplay(self,'mass_flux_segments','')
+		s+="%s\n" % fielddisplay(self,'adjacency','')
+		s+="%s\n" % fielddisplay(self,'vertex_weight','weight applied to each mesh vertex')
+
+		return s
+	# }}}
+		
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','isdakota','format','Boolean')
+		if not self.isdakota:
+			return
+		WriteData(fid,'object',self,'fieldname','partition','format','DoubleMat','mattype',2)
+		WriteData(fid,'object',self,'fieldname','numberofpartitions','format','Integer')
+		WriteData(fid,'object',self,'fieldname','numberofresponses','format','Integer')
+		WriteData(fid,'object',self,'fieldname','variabledescriptors','format','StringArray')
+		WriteData(fid,'object',self,'fieldname','responsedescriptors','format','StringArray')
+		WriteData(fid,'object',self,'fieldname','mass_flux_segments','format','MatArray')
+	# }}}
+
Index: /issm/trunk/src/m/classes/radaroverlay.py
===================================================================
--- /issm/trunk/src/m/classes/radaroverlay.py	(revision 13394)
+++ /issm/trunk/src/m/classes/radaroverlay.py	(revision 13395)
@@ -2,5 +2,12 @@
 from fielddisplay import fielddisplay
 
-class radaroverlay:
+class radaroverlay(object):
+	"""
+	RADAROVERLAY class definition
+
+	   Usage:
+	      radaroverlay=radaroverlay();
+	"""
+
 	#properties
 	def __init__(self):
@@ -14,16 +21,16 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   radaroverlay parameters:'
-		string="%s\n\n%s"%(string,fielddisplay(obj,'pwr','radar power image (matrix)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'x','corresponding x coordinates'))
-		string="%s\n%s"%(string,fielddisplay(obj,'y','corresponding y coordinates'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'pwr','radar power image (matrix)'))
+		string="%s\n%s"%(string,fielddisplay(self,'x','corresponding x coordinates'))
+		string="%s\n%s"%(string,fielddisplay(self,'y','corresponding y coordinates'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
Index: /issm/trunk/src/m/classes/rifts.m
===================================================================
--- /issm/trunk/src/m/classes/rifts.m	(revision 13394)
+++ /issm/trunk/src/m/classes/rifts.m	(revision 13395)
@@ -79,6 +79,6 @@
 			end
 
-			WriteData(fid,'data',numrifts,'enum',RiftsNumriftsEnum,'format','Integer');
-			WriteData(fid,'data',data,'enum',RiftsRiftstructEnum,'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',numrifts,'enum',RiftsNumriftsEnum(),'format','Integer');
+			WriteData(fid,'data',data,'enum',RiftsRiftstructEnum(),'format','DoubleMat','mattype',3);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/rifts.py
===================================================================
--- /issm/trunk/src/m/classes/rifts.py	(revision 13394)
+++ /issm/trunk/src/m/classes/rifts.py	(revision 13395)
@@ -1,6 +1,18 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
+from isnans import *
 
-class rifts:
+class rifts(object):
+	"""
+	RIFTS class definition
+
+	   Usage:
+	      rifts=rifts();
+	"""
+
 	#properties
 	def __init__(self):
@@ -13,16 +25,67 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   rifts parameters:'
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,'riftstruct','structure containing all rift information (vertices coordinates, segments, type of melange, ...)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'riftproperties',''))
+		string="%s\n\n%s"%(string,fielddisplay(self,'riftstruct','structure containing all rift information (vertices coordinates, segments, type of melange, ...)'))
+		string="%s\n%s"%(string,fielddisplay(self,'riftproperties',''))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		if (not self.riftstruct) or numpy.any(isnans(self.riftstruct)):
+			numrifts=0
+		else:
+			numrifts=len(self.riftstruct)
+
+		if numrifts:
+			if not md.mesh.dimension==2:
+				md.checkmessage("models with rifts are only supported in 2d for now!")
+			if not isinstance(self.riftstruct,list):
+				md.checkmessage("rifts.riftstruct should be a structure!")
+			if numpy.any(md.mesh.segmentmarkers>=2):
+				#We have segments with rift markers, but no rift structure!
+				md.checkmessage("model should be processed for rifts (run meshprocessrifts)!")
+			md = checkfield(md,'rifts.riftstruct.fill','values',[WaterEnum(),AirEnum(),IceEnum(),MelangeEnum()])
+		else:
+			if numpy.any(numpy.logical_not(isnans(self.riftstruct))):
+				md.checkmessage("riftstruct shoud be NaN since numrifts is 0!")
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+
+		#Process rift info
+		if (not self.riftstruct) or numpy.any(isnans(self.riftstruct)):
+			numrifts=0
+		else:
+			numrifts=len(self.riftstruct)
+
+		numpairs=0
+		for i in xrange(0,numrifts):
+			numpairs+=numpy.size(self.riftstruct[i].penaltypairs,0)
+
+		# 2 for nodes + 2 for elements+ 2 for  normals + 1 for length + 1 for fill + 1 for friction + 1 for fraction + 1 for fractionincrement + 1 for state.
+		data=numpy.zeros((numpairs,12))
+		count=0
+		for i in xrange(0,numrifts):
+			numpairsforthisrift=numpy.size(self.riftstruct[i]['penaltypairs'],0)
+			data[count:count+numpairsforthisrift-1,0:6]=self.riftstruct[i]['penaltypairs']
+			data[count:count+numpairsforthisrift-1,7]=self.riftstruct[i]['fill']
+			data[count:count+numpairsforthisrift-1,8]=self.riftstruct[i]['friction']
+			data[count:count+numpairsforthisrift-1,9]=self.riftstruct[i]['fraction']
+			data[count:count+numpairsforthisrift-1,10]=self.riftstruct[i]['fractionincrement']
+			data[count:count+numpairsforthisrift-1,11]=self.riftstruct[i]['state']
+			count+=numpairsforthisrift
+
+		WriteData(fid,'data',numrifts,'enum',RiftsNumriftsEnum(),'format','Integer')
+		WriteData(fid,'data',data,'enum',RiftsRiftstructEnum(),'format','DoubleMat','mattype',3)
+	# }}}
+
Index: /issm/trunk/src/m/classes/settings.m
===================================================================
--- /issm/trunk/src/m/classes/settings.m	(revision 13394)
+++ /issm/trunk/src/m/classes/settings.m	(revision 13395)
@@ -43,9 +43,9 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			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);
+			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/trunk/src/m/classes/settings.py
===================================================================
--- /issm/trunk/src/m/classes/settings.py	(revision 13394)
+++ /issm/trunk/src/m/classes/settings.py	(revision 13395)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class settings:
+class settings(object):
+	"""
+	SETTINGS class definition
+
+	   Usage:
+	      settings=settings();
+	"""
+
 	#properties
 	def __init__(self):
@@ -16,30 +26,30 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   general settings parameters:"
 
-		string="%s\n%s"%(string,fielddisplay(obj,"io_gather","I/O gathering strategy for result outputs (default 1)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"lowmem","is the memory limited ? (0 or 1)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"results_as_patches","provide results as patches for each element (0 or 1)"))
-		string="%s\n%s"%(string,fielddisplay(obj,"output_frequency","frequency at which results are saved in all solutions with multiple time_steps"))
-		string="%s\n%s"%(string,fielddisplay(obj,"waitonlock","maximum number of minutes to wait for batch results, or return 0"))
+		string="%s\n%s"%(string,fielddisplay(self,"io_gather","I/O gathering strategy for result outputs (default 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"lowmem","is the memory limited ? (0 or 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"results_as_patches","provide results as patches for each element (0 or 1)"))
+		string="%s\n%s"%(string,fielddisplay(self,"output_frequency","frequency at which results are saved in all solutions with multiple time_steps"))
+		string="%s\n%s"%(string,fielddisplay(self,"waitonlock","maximum number of minutes to wait for batch results, or return 0"))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#are we short in memory ? (0 faster but requires more memory)
-		obj.lowmem=0
+		self.lowmem=0
 
 		#i/o:
-		obj.io_gather=1
+		self.io_gather=1
 
 		#results frequency by default every step
-		obj.output_frequency=1
+		self.output_frequency=1
 
 		#do not use patches by default (difficult to plot)
-		obj.results_as_patches=0
+		self.results_as_patches=0
 
 		#this option can be activated to load automatically the results
@@ -47,7 +57,25 @@
 		#N minutes that is generated once the solution has converged
 		#0 to desactivate
-		obj.waitonlock=float('Inf')
+		self.waitonlock=float('Inf')
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		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])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','io_gather','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','lowmem','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','results_as_patches','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','output_frequency','format','Integer')
+		WriteData(fid,'object',self,'fieldname','waitonlock','format','Boolean')
+	# }}}
+
Index: /issm/trunk/src/m/classes/solver.m
===================================================================
--- /issm/trunk/src/m/classes/solver.m	(revision 13394)
+++ /issm/trunk/src/m/classes/solver.m	(revision 13395)
@@ -20,6 +20,6 @@
 		 function obj = addoptions(obj,analysis,varargin) % {{{
 		 % Usage example:
-		 %    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum,stokesoptions());
-		 %    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum);
+		 %    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum(),stokesoptions());
+		 %    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum());
 
 			 %Convert analysis from enum to string
@@ -38,8 +38,8 @@
 
 			 %MUMPS is the default solver
-			 if ismumps,
-				 obj.NoneAnalysis=mumpsoptions;
+			 if ismumps(),
+				 obj.NoneAnalysis=mumpsoptions();
 			 else
-				 obj.NoneAnalysis=iluasmoptions;
+				 obj.NoneAnalysis=iluasmoptions();
 			 end
 
Index: /issm/trunk/src/m/classes/solver.py
===================================================================
--- /issm/trunk/src/m/classes/solver.py	(revision 13394)
+++ /issm/trunk/src/m/classes/solver.py	(revision 13395)
@@ -1,49 +1,106 @@
-#module imports {{{
-import fielddisplay 
-import ismumps
-from  mumpsoptions import *
-from  iluasmoptions import *
-#}}}
-class solver:
-	#properties
-	def __init__(self):
-		# {{{ Properties
-		if ismumps:
-			self.options=[["NoneAnalysis",mumpsoptions()]]
+from ismumps import *
+from mumpsoptions import *
+from iluasmoptions import *
+from EnumToString import EnumToString
+from MatlabFuncs import *
+from EnumDefinitions import *
+from checkfield import *
+
+class solver(object):
+	"""
+	SOLVER class definition
+
+	   Usage:
+	      obj=solver();
+	"""
+
+	def __init__(self):    # {{{
+		#MUMPS is the default solver
+		if ismumps():
+			self.NoneAnalysis=mumpsoptions()
 		else:
-			self.options=[["NoneAnalysis",iluasmoptions()]]
-		#}}}
-	def __repr__(obj):
-		# {{{ Display
-		
-		string2="   solver parameters:"
-		for i in range(len(obj.options)):
-			option=obj.options[i]
-			analysis=option[0]
-			ioptions=option[1]
+			self.NoneAnalysis=iluasmoptions()
 
-			string=""
-			for i in range(len(ioptions)):
-				option=ioptions[i]
-				if not option:
-					#do nothing
-					pass
-				elif len(option)==1:
+		#The other properties are dynamic
+	# }}}
+
+	def addoptions(self,analysis,*args):    # {{{
+		# Usage example:
+		#    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum(),stokesoptions());
+		#    md.solver=addoptions(md.solver,DiagnosticHorizAnalysisEnum());
+
+		#Convert analysis from enum to string
+		[analysis]=EnumToString(analysis)
+
+		#Create dynamic property if property does not exist yet
+		if not hasattr(self,analysis):
+#			exec("self.%s = None" % analysis)
+			setattr(self,analysis,None)
+
+		#Add solver options to analysis
+		if len(args)==1:
+			setattr(self,analysis,args[0])
+
+		return self
+	# }}}
+
+	def __repr__(self):    # {{{
+		s ="List of solver options per analysis:\n\n"
+		for analysis in vars(self).iterkeys():
+			s+="%s :\n" % analysis
+			s+="%s\n" % getattr(self,analysis)
+
+		return s
+	# }}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		for analysis in vars(self).iterkeys():
+			if not getattr(self,analysis):
+				md.checkmessage("md.solver.%s is empty" % analysis)
+
+		return md
+	# }}}
+
+	def PetscFile(self,filename):    # {{{
+		"""
+		PETSCFILE - build petsc file
+
+		   Build a Petsc compatible options file, from the solver model field  + return options string
+
+		   Usage:     PetscFile(solver,filename);
+		"""
+
+		#open file for writing
+		try:
+			fid=open(filename,'w')
+		except IOError as e:
+			raise IOError("PetscFile error: could not open '%s' for writing." % filename)
+
+		#write header
+		fid.write("%s%s%s\n" % ('%Petsc options file: ',filename,' written from Matlab solver array'))
+
+		#start writing options
+		for analysis in vars(self).iterkeys():
+			options=getattr(self,analysis)
+
+			#first write analysis:
+			fid.write("\n+%s\n" % analysis)    #append a + to recognize it's an analysis enum
+
+			#now, write options
+			for optionname,optionvalue in options.iteritems():
+
+				if not optionvalue:
 					#this option has only one argument
-					string="%s%s%s"%(string," -",option[0])
-				elif len(option)==2:
+					fid.write("-%s\n" % optionname)
+				else:
 					#option with value. value can be string or scalar
-					if isinstance(option[1],float):
-						string="%s%s%s%s%s"%(string," -",option[0]," ","%g"%(option[1]))
-					elif isinstance(option[1],str):
-						string="%s%s%s%s%s"%(string," -",option[0]," ",option[1])
-					elif isinstance(option[1],int):
-						string="%s%s%s%s%s"%(string," -",option[0]," ","%i"%(option[1]))
+					if   isinstance(optionvalue,(bool,int,long,float)):
+						fid.write("-%s %g\n" % (optionname,optionvalue))
+					elif isinstance(optionvalue,(str,unicode)):
+						fid.write("-%s %s\n" % (optionname,optionvalue))
 					else:
-						raise RuntimeError("%s%s%s"%("PetscString error: option #","%i"%(i)," is not well formatted"))
-				else:
-					raise RuntimeError("%s%s%s"%("PetscString error: option #","%i"%(i)," is not well formatted"))
+						raise TypeError("PetscFile error: option '%s' is not well formatted." % optionname)
 
-			string2="%s\n%s"%(string2,"   %s -> '%s'"%(analysis,string))
-		return string2
-	#}}}
+		fid.close()
+	# }}}
+
Index: /issm/trunk/src/m/classes/steadystate.m
===================================================================
--- /issm/trunk/src/m/classes/steadystate.m	(revision 13394)
+++ /issm/trunk/src/m/classes/steadystate.m	(revision 13395)
@@ -29,5 +29,5 @@
 
 			%Early return
-			if solution~=SteadystateSolutionEnum, return; end;
+			if solution~=SteadystateSolutionEnum(), return; end;
 
 			if md.timestepping.time_step~=0,
Index: /issm/trunk/src/m/classes/steadystate.py
===================================================================
--- /issm/trunk/src/m/classes/steadystate.py	(revision 13394)
+++ /issm/trunk/src/m/classes/steadystate.py	(revision 13395)
@@ -1,6 +1,17 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class steadystate:
+class steadystate(object):
+	"""
+	STEADYSTATE class definition
+
+	   Usage:
+	      steadystate=steadystate();
+	"""
+
 	#properties
 	def __init__(self):
@@ -14,23 +25,44 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   steadystate solution parameters:'
-		string="%s\n%s"%(string,fielddisplay(obj,'reltol','relative tolerance criterion'))
-		string="%s\n%s"%(string,fielddisplay(obj,'maxiter','maximum number of iterations'))
-		string="%s\n%s"%(string,fielddisplay(obj,'requested_outputs','additional requested outputs'))
+		string="%s\n%s"%(string,fielddisplay(self,'reltol','relative tolerance criterion'))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of iterations'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional requested outputs'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#maximum of steady state iterations
-		obj.maxiter=100
+		self.maxiter=100
 
 		#Relative tolerance for the steadystate convertgence
-		obj.reltol=0.01
+		self.reltol=0.01
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not solution==SteadystateSolutionEnum():
+			return md
+
+		if not md.timestepping.time_step==0:
+			md.checkmessage("for a steadystate computation, timestepping.time_step must be zero.")
+
+		if numpy.isnan(md.diagnostic.reltol):
+			md.checkmessage("for a steadystate computation, diagnostic.reltol (relative convergence criterion) must be defined!")
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','reltol','format','Double')
+		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
+		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3)
+	# }}}
+
Index: /issm/trunk/src/m/classes/surfaceforcings.m
===================================================================
--- /issm/trunk/src/m/classes/surfaceforcings.m	(revision 13394)
+++ /issm/trunk/src/m/classes/surfaceforcings.m	(revision 13395)
@@ -10,5 +10,6 @@
 		ispdd = 0;
 		issmbgradients = 0;
-	   hc = NaN;
+		isdelta18o = 0;
+		hc = NaN;
 		smb_pos_max = NaN;
 		smb_pos_min = NaN;
@@ -18,4 +19,9 @@
 		b_neg = NaN;
 		monthlytemperatures = NaN;
+		delta18o = NaN;
+		delta18o_surface = NaN;
+		temperatures_presentday = NaN;
+		temperatures_lgm = NaN;
+		precipitations_presentday = NaN;
 	end
 	methods
@@ -33,26 +39,36 @@
 		  obj.ispdd=0;
 		  obj.issmbgradients=0;
+		  obj.isdelta18o=0;
 
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			if ismember(PrognosticAnalysisEnum,analyses),
-				md = checkfield(md,'surfaceforcings.ispdd','numel',1,'values',[0 1]);
-				checkfield(md,'surfaceforcings.issmbgradients','numel',1,'values',[0 1]);
+			if ismember(PrognosticAnalysisEnum(),analyses),
+				md = checkfield(md,'surfaceforcings.ispdd','numel',[1],'values',[0 1]);
+				md = checkfield(md,'surfaceforcings.issmbgradients','numel',[1],'values',[0 1]);
 				if(obj.ispdd)
-					md = checkfield(md,'surfaceforcings.monthlytemperatures','forcing',1,'NaN',1);
+					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);
+					md = checkfield(md,'surfaceforcings.hc','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.smb_pos_max','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.smb_pos_min','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.a_pos','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.b_pos','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.a_neg','forcing',1,'NaN',1);
+					md = 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),
+			if ismember(BalancethicknessAnalysisEnum(),analyses),
 				md = checkfield(md,'surfaceforcings.mass_balance','size',[md.mesh.numberofvertices 1],'NaN',1);
 			end
@@ -61,8 +77,14 @@
 			disp(sprintf('   surface forcings parameters:'));
 
-			fielddisplay(obj,'precipitation','surface precipitation [m/yr water eq]');
 			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,'monthlytemperatures','monthly surface temperatures required if pdd is activated');
+			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,'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');
@@ -79,6 +101,16 @@
 			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,
-				WriteData(fid,'object',obj,'fieldname','monthlytemperatures','format','DoubleMat','mattype',1);
+				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');
Index: /issm/trunk/src/m/classes/surfaceforcings.py
===================================================================
--- /issm/trunk/src/m/classes/surfaceforcings.py	(revision 13394)
+++ /issm/trunk/src/m/classes/surfaceforcings.py	(revision 13395)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class surfaceforcings:
+class surfaceforcings(object):
+	"""
+	SURFACEFORCING Class definition
+
+	   Usage:
+	      surfaceforcings=surfaceforcings();
+	"""
+
 	#properties
 	def __init__(self):
@@ -8,4 +18,20 @@
 		self.precipitation = float('NaN')
 		self.mass_balance  = float('NaN')
+		self.ispdd = 0
+		self.issmbgradients = 0
+		self.isdelta18o = 0
+		self.hc = float('NaN')
+		self.smb_pos_max = float('NaN')
+		self.smb_pos_min = float('NaN')
+		self.a_pos = float('NaN')
+		self.b_pos = float('NaN')
+		self.a_neg = float('NaN')
+		self.b_neg = float('NaN')
+		self.monthlytemperatures = float('NaN')
+		self.delta18o = float('NaN')
+		self.delta18o_surface = float('NaN')
+		self.temperatures_presentday = float('NaN')
+		self.temperatures_lgm = float('NaN')
+		self.precipitations_presentday = float('NaN')
 
 		#set defaults
@@ -13,17 +39,101 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   surface forcings parameters:"
 
-		string="%s\n\n%s"%(string,fielddisplay(obj,'precipitation','surface precipitation [m/yr water eq]'))
-		string="%s\n%s"%(string,fielddisplay(obj,'mass_balance','surface mass balance [m/yr ice eq]'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'precipitation','surface precipitation [m/yr water eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'mass_balance','surface mass balance [m/yr ice eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'ispdd','is pdd activated (0 or 1, default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'isdelta18o','is temperature and precipitation delta18o parametrisation activated (0 or 1, default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'monthlytemperatures','monthly surface temperatures [Kelvin], required if pdd is activated and delta18o not activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'precipitation','surface precipitation [m/yr water eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [Kelvin], required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'temperatures_lgm','monthly LGM surface temperatures [Kelvin], required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'delta18o','delta18o, required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'delta18o_surface','surface elevation of the delta18o site, required if pdd is activated and delta18o activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'issmbgradients','is smb gradients method activated (0 or 1, default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'hc',' elevation of intersection between accumulation and ablation regime required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'smb_pos_max',' maximum value of positive smb required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'smb_pos_min',' minimum value of positive smb required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'a_pos',' intercept of hs - smb regression line for accumulation regime required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'b_pos',' slope of hs - smb regression line for accumulation regime required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'a_neg',' intercept of hs - smb regression line for ablation regime required if smb gradients is activated'))
+		string="%s\n%s"%(string,fielddisplay(self,'b_neg',' slope of hs - smb regression line for ablation regime required if smb gradients is activated'))
 
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
-		return obj
+		  
+		#pdd method not used in default mode
+		self.ispdd=0
+		self.issmbgradients=0
+		self.isdelta18o=0
+
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		if PrognosticAnalysisEnum() in analyses:
+			md = checkfield(md,'surfaceforcings.ispdd','numel',[1],'values',[0,1])
+			md = checkfield(md,'surfaceforcings.issmbgradients','numel',[1],'values',[0,1])
+			if   self.ispdd:
+				if not self.isdelta18o:
+					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)
+			elif self.issmbgradients:
+				md = checkfield(md,'surfaceforcings.hc','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.smb_pos_max','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.smb_pos_min','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.a_pos','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.b_pos','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.a_neg','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.b_neg','forcing',1,'NaN',1)
+			else:
+				md = checkfield(md,'surfaceforcings.mass_balance','forcing',1,'NaN',1)
+
+		if BalancethicknessAnalysisEnum() in analyses:
+			md = checkfield(md,'surfaceforcings.mass_balance','size',[md.mesh.numberofvertices],'NaN',1)
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','precipitation','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','mass_balance','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','ispdd','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isdelta18o','format','Boolean')
+
+		if self.ispdd:
+			if self.isdelta18o:
+				WriteData(fid,'object',self,'fieldname','temperatures_presentday','format','DoubleMat','mattype',1)
+				WriteData(fid,'object',self,'fieldname','temperatures_lgm','format','DoubleMat','mattype',1)
+				WriteData(fid,'object',self,'fieldname','precipitations_presentday','format','DoubleMat','mattype',1)
+				WriteData(fid,'object',self,'fieldname','delta18o_surface','format','DoubleMat','mattype',1)
+				WriteData(fid,'object',self,'fieldname','delta18o','format','DoubleMat','mattype',1)
+			else:
+				WriteData(fid,'object',self,'fieldname','monthlytemperatures','format','DoubleMat','mattype',1)
+				WriteData(fid,'object',self,'fieldname','precipitation','format','DoubleMat','mattype',1)
+
+		WriteData(fid,'object',self,'fieldname','issmbgradients','format','Boolean')
+
+		if self.issmbgradients:
+			WriteData(fid,'object',self,'fieldname','hc','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','smb_pos_max','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','smb_pos_min','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','a_pos','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','b_pos','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','a_neg','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','b_neg','format','DoubleMat','mattype',1)
+	# }}}
+
Index: /issm/trunk/src/m/classes/thermal.m
===================================================================
--- /issm/trunk/src/m/classes/thermal.m	(revision 13394)
+++ /issm/trunk/src/m/classes/thermal.m	(revision 13395)
@@ -43,11 +43,11 @@
 
 			%Early return
-			if (~ismember(ThermalAnalysisEnum,analyses) & ~ismember(EnthalpyAnalysisEnum,analyses)) | (solution==TransientSolutionEnum & md.transient.isthermal==0), return; end
+			if (~ismember(ThermalAnalysisEnum(),analyses) & ~ismember(EnthalpyAnalysisEnum(),analyses)) | (solution==TransientSolutionEnum() & md.transient.isthermal==0), return; end
 
-			md = checkfield(md,'thermal.stabilization','numel',1,'values',[0 1 2]);
+			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]);
+			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/trunk/src/m/classes/thermal.py
===================================================================
--- /issm/trunk/src/m/classes/thermal.py	(revision 13394)
+++ /issm/trunk/src/m/classes/thermal.py	(revision 13395)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class thermal:
+class thermal(object):
+	"""
+	THERMAL class definition
+
+	   Usage:
+	      thermal=thermal();
+	"""
+
 	#properties
 	def __init__(self):
@@ -18,35 +28,60 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   Thermal solution parameters:'
-		string="%s\n\n%s"%(string,fielddisplay(obj,'spctemperature','temperature constraints (NaN means no constraint)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'stabilization','0->no, 1->artificial_diffusivity, 2->SUPG'))
-		string="%s\n%s"%(string,fielddisplay(obj,'maxiter','maximum number of non linear iterations'))
-		string="%s\n%s"%(string,fielddisplay(obj,'penalty_lock','stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'penalty_threshold','threshold to declare convergence of thermal solution (default is 0)'))
-		string="%s\n%s"%(string,fielddisplay(obj,'isenthalpy','use an enthalpy formulation to include temperate ice (default is 0)'))
+		string="%s\n\n%s"%(string,fielddisplay(self,'spctemperature','temperature constraints (NaN means no constraint)'))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0->no, 1->artificial_diffusivity, 2->SUPG'))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of non linear iterations'))
+		string="%s\n%s"%(string,fielddisplay(self,'penalty_lock','stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization)'))
+		string="%s\n%s"%(string,fielddisplay(self,'penalty_threshold','threshold to declare convergence of thermal solution (default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'isenthalpy','use an enthalpy formulation to include temperate ice (default is 0)'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#Number of unstable constraints acceptable
-		obj.penalty_threshold=0
+		self.penalty_threshold=0
 
 		#Type of stabilization used
-		obj.stabilization=1
+		self.stabilization=1
 
 		#Maximum number of iterations
-		obj.maxiter=100
+		self.maxiter=100
 
 		#factor used to compute the values of the penalties: kappa=max(stiffness matrix)*10^penalty_factor
-		obj.penalty_factor=3
+		self.penalty_factor=3
 
 		#Should we use cold ice (default) or enthalpy formulation
-		obj.isenthalpy=0
+		self.isenthalpy=0
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if (ThermalAnalysisEnum() not in analyses and EnthalpyAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum() and not md.transient.isthermal):
+			return md
+
+		md = checkfield(md,'thermal.stabilization','numel',[1],'values',[0,1,2])
+		md = checkfield(md,'thermal.spctemperature','forcing',1)
+		if EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy and 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])
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spctemperature','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','penalty_threshold','format','Integer')
+		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
+		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
+		WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer')
+		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
+		WriteData(fid,'object',self,'fieldname','isenthalpy','format','Boolean')
+	# }}}
+
Index: /issm/trunk/src/m/classes/timestepping.m
===================================================================
--- /issm/trunk/src/m/classes/timestepping.m	(revision 13394)
+++ /issm/trunk/src/m/classes/timestepping.m	(revision 13395)
@@ -35,9 +35,9 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			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);
+			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,
 				md = checkmessage(md,'timestepping.final_time should be larger than timestepping.start_time');
Index: /issm/trunk/src/m/classes/timestepping.py
===================================================================
--- /issm/trunk/src/m/classes/timestepping.py	(revision 13394)
+++ /issm/trunk/src/m/classes/timestepping.py	(revision 13395)
@@ -1,11 +1,22 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class timestepping:
+class timestepping(object):
+	"""
+	TIMESTEPPING Class definition
+
+	   Usage:
+	      timestepping=timestepping();
+	"""
+
 	#properties
 	def __init__(self):
 		# {{{ Properties
+		self.start_time      = 0
+		self.final_time      = 0
 		self.time_step       = 0
-		self.final_time      = 0
 		self.time_adapt      = 0
 		self.cfl_coefficient = 0
@@ -15,27 +26,50 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string="   timestepping parameters:"
-		string="%s\n\n%s"%(string,fielddisplay(obj,"time_step","length of time steps [yrs]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"final_time","final time to stop the simulation [yrs]"))
-		string="%s\n%s"%(string,fielddisplay(obj,"time_adapt","use cfl condition to define time step ? (0 or 1) "))
-		string="%s\n%s"%(string,fielddisplay(obj,"cfl_coefficient","coefficient applied to cfl condition"))
+		string="%s\n\n%s"%(string,fielddisplay(self,"start_time","simulation starting time [yrs]"))
+		string="%s\n%s"%(string,fielddisplay(self,"final_time","final time to stop the simulation [yrs]"))
+		string="%s\n%s"%(string,fielddisplay(self,"time_step","length of time steps [yrs]"))
+		string="%s\n%s"%(string,fielddisplay(self,"time_adapt","use cfl condition to define time step ? (0 or 1) "))
+		string="%s\n%s"%(string,fielddisplay(self,"cfl_coefficient","coefficient applied to cfl condition"))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#time between 2 time steps
-		obj.time_step=1/2
+		self.time_step=1/2
 
 		#final time
-		obj.final_time=10*obj.time_step
+		self.final_time=10*self.time_step
 
 		#time adaptation? 
-		obj.time_adapt=0
-		obj.cfl_coefficient=.5
+		self.time_adapt=0
+		self.cfl_coefficient=.5
 
-		return obj
+		return self
 	#}}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		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 self.final_time-self.start_time<0:
+			md.checkmessage("timestepping.final_time should be larger than timestepping.start_time")
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','start_time','format','Double')
+		WriteData(fid,'object',self,'fieldname','final_time','format','Double')
+		WriteData(fid,'object',self,'fieldname','time_step','format','Double')
+		WriteData(fid,'object',self,'fieldname','time_adapt','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','cfl_coefficient','format','Double')
+	# }}}
+
Index: /issm/trunk/src/m/classes/transient.m
===================================================================
--- /issm/trunk/src/m/classes/transient.m	(revision 13394)
+++ /issm/trunk/src/m/classes/transient.m	(revision 13395)
@@ -33,10 +33,11 @@
 
 			%Early return
-			if solution~=TransientSolutionEnum, return; end
+			if solution~=TransientSolutionEnum(), return; end
 
-			md = checkfield(md,'transient.isprognostic','numel',1,'values',[0 1]);
-			md = checkfield(md,'transient.isdiagnostic','numel',1,'values',[0 1]);
-			md = checkfield(md,'transient.isthermal','numel',1,'values',[0 1]);
-			md = 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/trunk/src/m/classes/transient.py
===================================================================
--- /issm/trunk/src/m/classes/transient.py	(revision 13394)
+++ /issm/trunk/src/m/classes/transient.py	(revision 13395)
@@ -1,6 +1,16 @@
 #module imports
 from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
 
-class transient:
+class transient(object):
+	"""
+	TRANSIENT class definition
+
+	   Usage:
+	      transient=transient();
+	"""
+
 	#properties
 	def __init__(self):
@@ -16,25 +26,49 @@
 
 		#}}}
-	def __repr__(obj):
+	def __repr__(self):
 		# {{{ Display
 		string='   transient solution parameters:'
-		string="%s\n%s"%(string,fielddisplay(obj,'isprognostic','indicates if a prognostic solution is used in the transient'))
-		string="%s\n%s"%(string,fielddisplay(obj,'isthermal','indicates if a thermal solution is used in the transient'))
-		string="%s\n%s"%(string,fielddisplay(obj,'isdiagnostic','indicates if a diagnostic solution is used in the transient'))
-		string="%s\n%s"%(string,fielddisplay(obj,'isgroundingline','indicates if a groundingline migration is used in the transient'))
-		string="%s\n%s"%(string,fielddisplay(obj,'requested_outputs','list of additional outputs requested'))
+		string="%s\n%s"%(string,fielddisplay(self,'isprognostic','indicates if a prognostic solution is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'isthermal','indicates if a thermal solution is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'isdiagnostic','indicates if a diagnostic solution is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'isgroundingline','indicates if a groundingline migration is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','list of additional outputs requested'))
 		return string
 		#}}}
 		
-	def setdefaultparameters(obj):
+	def setdefaultparameters(self):
 		# {{{setdefaultparameters
 		
 		#full analysis: Diagnostic, Prognostic and Thermal but no groundingline migration for now
-		obj.isprognostic=1
-		obj.isdiagnostic=1
-		obj.isthermal=1
-		obj.isgroundingline=0
+		self.isprognostic=1
+		self.isdiagnostic=1
+		self.isthermal=1
+		self.isgroundingline=0
 
-		return obj
+		return self
 	#}}}
 
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if not solution==TransientSolutionEnum():
+			return md
+
+		md = checkfield(md,'transient.isprognostic','numel',[1],'values',[0,1])
+		md = checkfield(md,'transient.isdiagnostic','numel',[1],'values',[0,1])
+		md = checkfield(md,'transient.isthermal','numel',[1],'values',[0,1])
+		md = checkfield(md,'transient.isgroundingline','numel',[1],'values',[0,1])
+		md = checkfield(md,'transient.requested_outputs','size',[float('NaN')])
+
+
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','isprognostic','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isdiagnostic','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isthermal','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','isgroundingline','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3)
+	# }}}
+
Index: /issm/trunk/src/m/classes/verbose.m
===================================================================
--- /issm/trunk/src/m/classes/verbose.m	(revision 13394)
+++ /issm/trunk/src/m/classes/verbose.m	(revision 13395)
@@ -42,5 +42,5 @@
 				case 1,
 					binary=varargin{1};
-					if ischar(binary),
+					if     ischar(binary),
 						if strcmpi(binary,'all'),
 							binary=2^11-1; %all ones
@@ -51,4 +51,6 @@
 							verbose=BinaryToVerbose(verbose,binary);
 						end
+					elseif isnumeric(binary),
+						verbose=BinaryToVerbose(verbose,binary);
 					end 
 				otherwise,
@@ -88,11 +90,11 @@
 
 		%BEGINBIN2VERB
-		if bitand(binary,1), verbose.mprocessor=true; else verbose.mprocessor=false; end
-		if bitand(binary,2), verbose.module=true; else verbose.module=false; end
-		if bitand(binary,4), verbose.solution=true; else verbose.solution=false; end
-		if bitand(binary,8), verbose.solver=true; else verbose.solver=false; end
-		if bitand(binary,16), verbose.convergence=true; else verbose.convergence=false; end
-		if bitand(binary,32), verbose.control=true; else verbose.control=false; end
-		if bitand(binary,64), verbose.qmu=true; else verbose.qmu=false; end
+		verbose.mprocessor =logical(bitand(binary, 1));
+		verbose.module     =logical(bitand(binary, 2));
+		verbose.solution   =logical(bitand(binary, 4));
+		verbose.solver     =logical(bitand(binary, 8));
+		verbose.convergence=logical(bitand(binary,16));
+		verbose.control    =logical(bitand(binary,32));
+		verbose.qmu        =logical(bitand(binary,64));
 		%ENDBIN2VERB
 
@@ -118,5 +120,5 @@
 		%}}}
 		function marshall(obj,fid) % {{{
-			WriteData(fid,'data',VerboseToBinary(obj),'enum',VerboseEnum,'format','Integer');
+			WriteData(fid,'data',VerboseToBinary(obj),'enum',VerboseEnum(),'format','Integer');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/verbose.py
===================================================================
--- /issm/trunk/src/m/classes/verbose.py	(revision 13394)
+++ /issm/trunk/src/m/classes/verbose.py	(revision 13395)
@@ -1,9 +1,32 @@
-#module imports
-from fielddisplay import fielddisplay
+from pairoptions import *
+from MatlabFuncs import *
+from EnumDefinitions import *
+from WriteData import *
 
-class verbose:
-	#properties
-	def __init__(self):
-		# {{{ Properties
+class verbose(object):
+	"""
+	VERBOSE class definition
+
+	   Available verbosity levels:
+	      mprocessor  : model processing 
+	      module      : modules
+	      solution    : solution sequence
+	      solver      : solver info (extensive)
+	      convergence : convergence criteria
+	      control     : control method
+	      qmu         : sensitivity analysis
+
+	   Usage:
+	      verbose=verbose();
+	      verbose=verbose(3);
+	      verbose=verbose('001100');
+	      verbose=verbose('module',True,'solver',False);
+
+	WARNING: some parts of this file are Synchronized with src/c/shared/Numerics/Verbosity.h
+	         Do not modify these sections. See src/c/shared/Numerics/README for more info
+	"""
+
+	def __init__(self,*args):    # {{{
+		#BEGINFIELDS
 		self.mprocessor  = False
 		self.module      = False
@@ -13,15 +36,94 @@
 		self.control     = False
 		self.qmu         = False
-		#}}}
-	def __repr__(obj):
-		# {{{ Display
-		string="%s%s%s\n\n"%("class '",obj.__class__.__name__,"'=")
-		string="%s%s\n"%(string,"   %15s : %s"%("mprocessor",obj.mprocessor))
-		string="%s%s\n"%(string,"   %15s : %s"%("module",obj.module))
-		string="%s%s\n"%(string,"   %15s : %s"%("solution",obj.solution))
-		string="%s%s\n"%(string,"   %15s : %s"%("solver",obj.solver))
-		string="%s%s\n"%(string,"   %15s : %s"%("convergence",obj.convergence))
-		string="%s%s\n"%(string,"   %15s : %s"%("control",obj.control))
-		string="%s%s\n"%(string,"   %15s : %s"%("qmu",obj.qmu))
-		return string
-		#}}}
+		#ENDFIELDS
+
+		if not len(args):
+			#Don't do anything
+			pass
+
+		elif len(args) == 1:
+			binary=args[0]
+			if   isinstance(binary,(str,unicode)):
+				if strcmpi(binary,'all'):
+					binary=2**11-1    #all ones
+					self.BinaryToVerbose(binary)
+					self.solver=False    #Do not use by default
+				else:
+					binary=int(binary,2)
+					self.BinaryToVerbose(binary)
+			elif isinstance(binary,(int,long,float)):
+				self.BinaryToVerbose(int(binary))
+
+		else:
+			#Use options to initialize object
+			self=pairoptions(*args).AssignObjectFields(self)
+
+			#Cast to logicals
+			listproperties=vars(self)
+			for [fieldname,fieldvalue] in listproperties.iteritems():
+				if isinstance(fieldvalue,bool) or isinstance(fieldvalue,(int,long,float)):
+					setattr(self,fieldname,bool(fieldvalue))
+				else:
+					raise TypeError("verbose supported field values are logicals only (True or False)")
+	# }}}
+
+	def VerboseToBinary(self):    # {{{
+
+		#BEGINVERB2BIN
+		binary=0
+		if self.mprocessor:
+			binary=binary |  1
+		if self.module:
+			binary=binary |  2
+		if self.solution:
+			binary=binary |  4
+		if self.solver:
+			binary=binary |  8
+		if self.convergence:
+			binary=binary | 16
+		if self.control:
+			binary=binary | 32
+		if self.qmu:
+			binary=binary | 64
+		#ENDVERB2BIN
+
+		return binary
+	# }}}
+
+	def BinaryToVerbose(self,binary):    # {{{
+
+		#BEGINBIN2VERB
+		self.mprocessor =bool(binary &  1)
+		self.module     =bool(binary &  2)
+		self.solution   =bool(binary &  4)
+		self.solver     =bool(binary &  8)
+		self.convergence=bool(binary & 16)
+		self.control    =bool(binary & 32)
+		self.qmu        =bool(binary & 64)
+		#ENDBIN2VERB
+	# }}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		return md
+	# }}}
+
+	def __repr__(self):    # {{{
+			
+		#BEGINDISP
+		s ="class '%s'  = \n" % type(self)
+		s+="   %15s : %s\n" % ('mprocessor',self.mprocessor)
+		s+="   %15s : %s\n" % ('module',self.module)
+		s+="   %15s : %s\n" % ('solution',self.solution)
+		s+="   %15s : %s\n" % ('solver',self.solver)
+		s+="   %15s : %s\n" % ('convergence',self.convergence)
+		s+="   %15s : %s\n" % ('control',self.control)
+		s+="   %15s : %s\n" % ('qmu',self.qmu)
+		#ENDDISP
+
+		return s
+	# }}}
+
+	def marshall(self,fid):    # {{{
+			WriteData(fid,'data',self.VerboseToBinary(),'enum',VerboseEnum(),'format','Integer')
+	# }}}
+
Index: /issm/trunk/src/m/consistency/QueueRequirements.m
===================================================================
--- /issm/trunk/src/m/consistency/QueueRequirements.m	(revision 13395)
+++ /issm/trunk/src/m/consistency/QueueRequirements.m	(revision 13395)
@@ -0,0 +1,35 @@
+function QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,queue,np,time)
+%QUEUEREQUIREMENTS - queue requirements in time, number of cpus, by name of queue.
+%
+%   Usage: 
+%      QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,np,time)
+
+%Ok, go through requirements for current queue:
+index=ismemberi(queue,available_queues);
+if  ~index,
+	%ok, either we a generic cluster, with 'none' queue, or we could not find the queue reqruirements
+	if strcmpi(available_queues{1},'none'),
+		%reset index to 1, so we can fish the requirements
+		index=1;
+	else
+		string=available_queues{1};
+		for i=2:length(available_queues),
+			string=[string ' ' available_queues{i}];
+		end
+		error(['QueueRequirements error message: availables queues are ' string]);
+	end
+end
+
+%check on time requirements
+rtime=queue_requirements_time(index);
+if time<=0,
+	error('QueueRequirements: time should be a positive number');
+end
+if time>rtime,
+	error(['QueueRequirements: time should be < ' num2str(rtime) ' for queue: ' queue]);
+end
+
+%check on np requirements
+if np<=0,
+	error('QueueRequirements: np should be a positive number');
+end
Index: /issm/trunk/src/m/consistency/checkfield.m
===================================================================
--- /issm/trunk/src/m/consistency/checkfield.m	(revision 13395)
+++ /issm/trunk/src/m/consistency/checkfield.m	(revision 13395)
@@ -0,0 +1,195 @@
+function md = checkfield(md,fieldname,varargin)
+%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(varargin{:});
+
+%get field from model
+eval(['field=md.' fieldname ';']);
+
+%check empty
+if exist(options,'empty')
+	if isempty(field),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' is empty']));
+	end
+end
+
+%Check size
+if exist(options,'size')
+	fieldsize=getfieldvalue(options,'size');
+	if isnan(fieldsize(1)),
+		if (size(field,2)~=fieldsize(2)),
+			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)),
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' should have ' num2str(fieldsize(1)) ' lines']));
+		end
+	else
+		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
+	end
+end
+
+%Check numel
+if exist(options,'numel')
+	fieldnumel=getfieldvalue(options,'numel');
+	if ~ismember(numel(field),fieldnumel),
+		if length(fieldnumel)==1
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' sprintf('%g ',fieldnumel) ]));
+		elseif length(fieldnumel)==2
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' num2str(fieldnumel(1)) ' or ' num2str(fieldnumel(2)) ]));
+		else
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' size should be ' sprintf('%g, ',fieldnumel(1:end-1)) ' or ' num2str(fieldnumel(end)) ]));
+		end
+	end
+end
+
+%check NaN
+if getfieldvalue(options,'NaN',0);
+	field2=reshape(field,prod(size(field)),1);
+	if any(isnan(field2)),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['NaN values found in field ''' fieldname '''']));
+	end
+end
+
+%check cell
+if getfieldvalue(options,'cell',0);
+	if ~iscell(field),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should be a cell']));
+	end
+end
+
+%check values
+if exist(options,'values')
+	fieldvalues=getfieldvalue(options,'values');
+	if iscell(fieldvalues), %strings
+		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
+		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
+	end
+end
+
+%check greater
+if exist(options,'>=')
+	lowerbound=getfieldvalue(options,'>=');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2<lowerbound),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values above ' num2str(lowerbound(1,1))]));
+	end
+end
+if exist(options,'>')
+	lowerbound=getfieldvalue(options,'>');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2<=lowerbound),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values above ' num2str(lowerbound(1,1))]));
+	end
+end
+
+%check smaller
+if exist(options,'<=')
+	upperbound=getfieldvalue(options,'<=');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2>upperbound),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values below ' num2str(upperbound(1,1))]));
+	end
+end
+if exist(options,'<')
+	upperbound=getfieldvalue(options,'<');
+	field2=reshape(field,prod(size(field)),1);
+	if any(field2>=upperbound),
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have values below ' num2str(upperbound(1,1))]));
+	end
+end
+
+%check file
+if getfieldvalue(options,'file',0),
+	if ~exist(field,'file')
+		md = checkmessage(md,['file provided in ''' fieldname ''': ''' field ''' does not exist']);
+	end
+end
+
+%Check forcings (size and times)
+if getfieldvalue(options,'forcing',0),
+	if size(field,1)==md.mesh.numberofvertices,
+		if ~size(field,2)==1,
+			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,:))),
+			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)),
+			md = checkmessage(md,getfieldvalue(options,'message',...
+				['field ''' fieldname ''' columns must not contain duplicate timesteps']));
+		end
+	else
+		md = checkmessage(md,getfieldvalue(options,'message',...
+			['field ''' fieldname ''' should have md.mesh.numberofvertices or md.mesh.numberofvertices+1 lines']));
+	end
+end
Index: /issm/trunk/src/m/consistency/checkfield.py
===================================================================
--- /issm/trunk/src/m/consistency/checkfield.py	(revision 13395)
+++ /issm/trunk/src/m/consistency/checkfield.py	(revision 13395)
@@ -0,0 +1,160 @@
+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)
+	exec("field=md.%s" % fieldname)
+	if isinstance(field,(bool,int,long,float)):
+		field=numpy.array([field])
+
+	#check empty
+	if options.exist('empty'):
+		if not field:
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' is empty" % fieldname))
+
+	#Check size
+	if options.exist('size'):
+		fieldsize=options.getfieldvalue('size')
+		if   len(fieldsize) == 1:
+			if   numpy.isnan(fieldsize[0]):
+				pass
+			elif not numpy.size(field,0)==fieldsize[0]:
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' size should be %d" % (fieldname,fieldsize[0])))
+		elif len(fieldsize) == 2:
+			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 options.exist('numel'):
+		fieldnumel=options.getfieldvalue('numel')
+		if numpy.size(field) not 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 numpy.any(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 options.exist('values'):
+		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 options.exist('>='):
+		lowerbound=options.getfieldvalue('>=')
+		if numpy.any(field<lowerbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values above %d" % (fieldname,lowerbound)))
+	if options.exist('>'):
+		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 options.exist('<='):
+		upperbound=options.getfieldvalue('<=')
+		if numpy.any(field>upperbound):
+			md = md.checkmessage(options.getfieldvalue('message',\
+				"field '%s' should have values below %d" % (fieldname,upperbound)))
+	if options.exist('<'):
+		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 len(numpy.shape(field))>1 and 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 all(field[-1,:]==numpy.sort(field[-1,:])):
+				md = md.checkmessage(options.getfieldvalue('message',\
+					"field '%s' columns should be sorted chronologically" % fieldname))
+			if 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: /issm/trunk/src/m/consistency/ismodelselfconsistent.m
===================================================================
--- /issm/trunk/src/m/consistency/ismodelselfconsistent.m	(revision 13395)
+++ /issm/trunk/src/m/consistency/ismodelselfconsistent.m	(revision 13395)
@@ -0,0 +1,101 @@
+function 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 field, check that it is a class, and call checkconsistency
+fields=properties('model');
+for i=1:length(fields),
+	field=fields{i};
+
+	%Some properties do not need to be checked
+	if ismember(field,{'results' 'debug' 'radaroverlay'}),
+		continue;
+	end
+
+	%Check that current field is an object
+	if ~isobject(md.(field))
+		md=checkmessage(md,['field ''' char(field) ''' is not an object']);
+	end
+
+	%Check consistency of the object
+	if verLessThan('matlab', '7.6')
+		md=checkconsistency(md.(field),md,solution,analyses);
+	else
+		md=md.(field).checkconsistency(md,solution,analyses);
+	end
+end
+
+%error message if mode is not consistent
+if md.private.isconsistent==false,
+	error('Model not consistent, see messages above');
+end
+end
+
+function [analyses,numanalyses]=AnalysisConfiguration(solutiontype), % {{{
+%ANALYSISCONFIGURATION - return type of analyses, number of analyses 
+%
+%   Usage:
+%      [analyses, numanalyses]=AnalysisConfiguration(solutiontype);
+
+
+
+switch solutiontype,
+
+	case DiagnosticSolutionEnum(),
+		numanalyses=5;
+		analyses=[DiagnosticHorizAnalysisEnum();DiagnosticVertAnalysisEnum();DiagnosticHutterAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum()];
+
+	case SteadystateSolutionEnum(),
+		numanalyses=7; 
+		analyses=[DiagnosticHorizAnalysisEnum();DiagnosticVertAnalysisEnum();DiagnosticHutterAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum()];
+
+	case ThermalSolutionEnum(),
+		numanalyses=2; 
+		analyses=[ThermalAnalysisEnum();MeltingAnalysisEnum()];
+
+	case EnthalpySolutionEnum(),
+		numanalyses=1; 
+		analyses=[EnthalpyAnalysisEnum()];
+
+	case PrognosticSolutionEnum(),
+		numanalyses=1; 
+		analyses=[PrognosticAnalysisEnum()];
+
+	case BalancethicknessSolutionEnum(),
+		numanalyses=1; 
+		analyses=[BalancethicknessAnalysisEnum()];
+
+	case SurfaceSlopeSolutionEnum(),
+		numanalyses=1; 
+		analyses=[SurfaceSlopeAnalysisEnum()];
+
+	case BedSlopeSolutionEnum(),
+		numanalyses=1; 
+		analyses=[BedSlopeAnalysisEnum()];
+
+	case TransientSolutionEnum(),
+		numanalyses=9; 
+		analyses=[DiagnosticHorizAnalysisEnum();DiagnosticVertAnalysisEnum();DiagnosticHutterAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum();EnthalpyAnalysisEnum();PrognosticAnalysisEnum()];
+
+	case FlaimSolutionEnum(),
+		numanalyses=1; 
+		analyses=[FlaimAnalysisEnum()];
+
+	case HydrologySolutionEnum(),
+		numanalyses=3; 
+		analyses=[BedSlopeAnalysisEnum();SurfaceSlopeAnalysisEnum();HydrologyAnalysisEnum()];
+
+	otherwise
+		error('%s%s%s',' solution type: ',EnumToString(solutiontype),' not supported yet!');
+
+	end
+end % }}}
Index: /issm/trunk/src/m/consistency/ismodelselfconsistent.py
===================================================================
--- /issm/trunk/src/m/consistency/ismodelselfconsistent.py	(revision 13395)
+++ /issm/trunk/src/m/consistency/ismodelselfconsistent.py	(revision 13395)
@@ -0,0 +1,96 @@
+from EnumDefinitions import *
+from EnumToString import EnumToString
+
+def AnalysisConfiguration(solutiontype): #{{{
+	"""
+	ANALYSISCONFIGURATION - return type of analyses, number of analyses 
+
+		Usage:
+			[analyses, numanalyses]=AnalysisConfiguration(solutiontype);
+	"""
+
+	if   solutiontype == DiagnosticSolutionEnum():
+		numanalyses=5
+		analyses=[DiagnosticHorizAnalysisEnum(),DiagnosticVertAnalysisEnum(),DiagnosticHutterAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum()]
+
+	elif solutiontype == SteadystateSolutionEnum():
+		numanalyses=7 
+		analyses=[DiagnosticHorizAnalysisEnum(),DiagnosticVertAnalysisEnum(),DiagnosticHutterAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]
+
+	elif solutiontype == ThermalSolutionEnum():
+		numanalyses=2 
+		analyses=[ThermalAnalysisEnum(),MeltingAnalysisEnum()]
+
+	elif solutiontype == EnthalpySolutionEnum():
+		numanalyses=1 
+		analyses=[EnthalpyAnalysisEnum()]
+
+	elif solutiontype == PrognosticSolutionEnum():
+		numanalyses=1 
+		analyses=[PrognosticAnalysisEnum()]
+
+	elif solutiontype == BalancethicknessSolutionEnum():
+		numanalyses=1 
+		analyses=[BalancethicknessAnalysisEnum()]
+
+	elif solutiontype == SurfaceSlopeSolutionEnum():
+		numanalyses=1 
+		analyses=[SurfaceSlopeAnalysisEnum()]
+
+	elif solutiontype == BedSlopeSolutionEnum():
+		numanalyses=1 
+		analyses=[BedSlopeAnalysisEnum()]
+
+	elif solutiontype == TransientSolutionEnum():
+		numanalyses=9 
+		analyses=[DiagnosticHorizAnalysisEnum(),DiagnosticVertAnalysisEnum(),DiagnosticHutterAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum(),EnthalpyAnalysisEnum(),PrognosticAnalysisEnum()]
+
+	elif solutiontype == FlaimSolutionEnum():
+		numanalyses=1 
+		analyses=[FlaimAnalysisEnum()]
+
+	elif solutiontype == HydrologySolutionEnum():
+		numanalyses=3 
+		analyses=[BedSlopeAnalysisEnum(),SurfaceSlopeAnalysisEnum(),HydrologyAnalysisEnum()]
+
+	else:
+		raise TypeError("solution type: '%s' not supported yet!" % EnumToString(solutiontype)[0])
+
+	return analyses,numanalyses
+#}}}
+
+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(md)
+#	for field in fields.iterkeys():
+	for field in md.properties():
+
+		#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("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/trunk/src/m/contrib/bamg/BamgCall.m
===================================================================
--- /issm/trunk/src/m/contrib/bamg/BamgCall.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/bamg/BamgCall.m	(revision 13395)
@@ -0,0 +1,84 @@
+function md=BamgCall(md,field,hmin,hmax,gradation,epsilon),
+%BAMGCALL - call bam
+%
+%   build a metric using the Hessian of the given field
+%   call Bamg and the output mesh is plugged onto the model
+%   -hmin = minimum edge length (m)
+%   -hmax = maximum edge length (m)
+%   -gradation = maximum edge length gradation between 2 elements
+%   -epsilon = average error on each element (m/yr)
+%
+%   Usage:
+%      md=BamgCall(md,field,hmin,hmax,gradation,epsilon);
+%
+%   Example:
+%      md=BamgCall(md,md.inversion.vel_obs,1500,10^8,1.3,0.9);
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%Compute Hessian
+t1=clock; fprintf('%s','      computing Hessian...');
+hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,field,'node');
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%Compute metric
+t1=clock; fprintf('%s','      computing metric...');
+if length(md.nodeonwater)==md.mesh.numberofvertices,
+	pos=find(md.nodeonwater);
+else
+	pos=[];
+end
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+fid=fopen('carre0.met','w');
+fprintf(fid,'%i %i\n',md.mesh.numberofvertices,3);
+fprintf(fid,'%i %i %i\n',metric');
+fclose(fid);
+
+fid=fopen('carre0.mesh','w');
+
+%initialiation
+fprintf(fid,'%s %i\n','MeshVersionFormatted',0);
+
+%dimension
+fprintf(fid,'\n%s\n%i\n','Dimension',2);
+
+%Vertices
+fprintf(fid,'\n%s\n%i\n\n','Vertices',md.mesh.numberofvertices);
+fprintf(fid,'%8g %8g %i\n',[md.mesh.x md.mesh.y ones(md.mesh.numberofvertices,1)]');
+
+%Triangles
+fprintf(fid,'\n\n%s\n%i\n\n','Triangles',md.mesh.numberofelements);
+fprintf(fid,'%i %i %i %i\n',[md.mesh.elements ones(md.mesh.numberofelements,1)]');
+numberofelements1=md.mesh.numberofelements;
+
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call bamg
+fprintf('%s\n','      call Bamg...');
+system(['bamg -ratio ' num2str(gradation) ' -splitpbedge -nbv 1000000 -M carre0.met -b carre0.mesh -o carre1.mesh']);
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+A=meshread('carre1.mesh');
+md.mesh.x=A.x;
+md.mesh.y=A.y;
+md.z=zeros(A.nods,1);
+md.mesh.elements=A.index;
+md.mesh.numberofvertices=A.nods;
+md.mesh.numberofelements=A.nels;
+numberofelements2=md.mesh.numberofelements;
+t2=clock;fprintf('%s\n\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%display number of elements
+fprintf('\n%s %i','      inital number of elements:',numberofelements1);
+fprintf('\n%s %i\n\n','      new    number of elements:',numberofelements2);
+
+%clean up:
+system('rm carre0.mesh carre0.met carre1.mesh carre1.mesh.gmsh');
Index: /issm/trunk/src/m/contrib/bamg/BamgCallFromMetric.m
===================================================================
--- /issm/trunk/src/m/contrib/bamg/BamgCallFromMetric.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/bamg/BamgCallFromMetric.m	(revision 13395)
@@ -0,0 +1,65 @@
+function md=BamgCallFromMetric(md,metric,gradation),
+%BAMGCALL - call bam
+%
+%   call Bamg and the output mesh is plugged onto the model
+%   -gradation = maximum edge length gradation between 2 elements
+%
+%   Usage:
+%      md=BamgCallFromMetric(md,metric,gradation);
+%
+%   Example:
+%      md=BamgCall(md,metric,1500,10^8,1.3,0.9);
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+fid=fopen('carre0.met','w');
+fprintf(fid,'%i %i\n',md.mesh.numberofvertices,3);
+fprintf(fid,'%i %i %i\n',metric');
+fclose(fid);
+
+fid=fopen('carre0.mesh','w');
+
+%initialiation
+fprintf(fid,'%s %i\n','MeshVersionFormatted',0);
+
+%dimension
+fprintf(fid,'\n%s\n%i\n','Dimension',2);
+
+%Vertices
+fprintf(fid,'\n%s\n%i\n\n','Vertices',md.mesh.numberofvertices);
+fprintf(fid,'%8g %8g %i\n',[md.mesh.x md.mesh.y ones(md.mesh.numberofvertices,1)]');
+
+%Triangles
+fprintf(fid,'\n\n%s\n%i\n\n','Triangles',md.mesh.numberofelements);
+fprintf(fid,'%i %i %i %i\n',[md.mesh.elements ones(md.mesh.numberofelements,1)]');
+numberofelements1=md.mesh.numberofelements;
+
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call bamg
+fprintf('%s\n','      call Bamg...');
+system(['bamg -ratio ' num2str(gradation) ' -splitpbedge -nbv 1000000 -M carre0.met -b carre0.mesh -o carre1.mesh']);
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+A=meshread('carre1.mesh');
+md.mesh.x=A.x;
+md.mesh.y=A.y;
+md.z=zeros(A.nods,1);
+md.mesh.elements=A.index;
+md.mesh.numberofvertices=A.nods;
+md.mesh.numberofelements=A.nels;
+numberofelements2=md.mesh.numberofelements;
+t2=clock;fprintf('%s\n\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%display number of elements
+fprintf('\n%s %i','      inital number of elements:',numberofelements1);
+fprintf('\n%s %i\n\n','      new    number of elements:',numberofelements2);
+
+%clean up:
+system('rm carre0.mesh carre0.met carre1.mesh carre1.mesh.gmsh');
Index: /issm/trunk/src/m/contrib/bamg/YamsCall.m
===================================================================
--- /issm/trunk/src/m/contrib/bamg/YamsCall.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/bamg/YamsCall.m	(revision 13395)
@@ -0,0 +1,104 @@
+function md=YamsCall(md,field,hmin,hmax,gradation,epsilon),
+%YAMSCALL - call yams
+%
+%   build a metric using the Hessian of the given field
+%   call Yams and the output mesh is plugged onto the model
+%   -hmin = minimum edge length (m)
+%   -hmax = maximum edge length (m)
+%   -gradation = maximum edge length gradation between 2 elements
+%   -epsilon = average error on each element (m/yr)
+%
+%   Usage:
+%      md=YamsCall(md,field,hmin,hmax,gradation,epsilon);
+%
+%   Example:
+%      md=YamsCall(md,md.inversion.vel_obs,1500,10^8,1.3,0.9);
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%Compute Hessian
+t1=clock; fprintf('%s','      computing Hessian...');
+hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,field,'node');
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%Compute metric
+t1=clock; fprintf('%s','      computing metric...');
+if length(md.mask.vertexonwater)==md.mesh.numberofvertices,
+	pos=find(md.mask.vertexonwater);
+else
+	pos=[];
+end
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%write files
+t1=clock; fprintf('%s','      writing initial mesh files...');
+save -ascii carre0.met  metric
+
+fid=fopen('carre0.mesh','w');
+
+%initialiation
+fprintf(fid,'\n%s\n%i\n','MeshVersionFormatted',1);
+
+%dimension
+fprintf(fid,'\n%s\n%i\n','Dimension',2);
+
+%Vertices
+fprintf(fid,'\n%s\n%i\n\n','Vertices',md.mesh.numberofvertices);
+fprintf(fid,'%8g %8g %i\n',[md.mesh.x md.mesh.y zeros(md.mesh.numberofvertices,1)]');
+
+%Triangles
+fprintf(fid,'\n\n%s\n%i\n\n','Triangles',md.mesh.numberofelements);
+fprintf(fid,'%i %i %i %i\n',[md.mesh.elements zeros(md.mesh.numberofelements,1)]');
+numberofelements1=md.mesh.numberofelements;
+	
+%Deal with rifts
+if ~isnan(md.rifts.riftstruct),
+	
+	%we have the list of triangles that make up the rift. keep those triangles around during refinement.
+	triangles=[];
+	for i=1:size(md.rifts.riftstruct,1),
+		triangles=[triangles md.rifts(i).segments(:,3)'];
+	end
+
+	fprintf(fid,'\n\n%s\n%i\n\n','RequiredTriangles',length(triangles));
+	fprintf(fid,'%i\n',triangles);
+end
+
+%close
+fclose(fid);
+t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%call yams
+fprintf('%s\n','      call Yams...');
+if ispc()
+	%windows
+	system(['yams2-win -O 1 -v -0 -ecp -hgrad ' num2str(gradation)  ' carre0 carre1']);
+elseif ismac
+	%Macosx
+	system(['yams2-osx -O 1 -v -0 -ecp -hgrad ' num2str(gradation)  ' carre0 carre1']);
+else
+	%Linux
+	system(['yams2-linux -O 1 -v -0 -ecp -hgrad ' num2str(gradation)  ' carre0 carre1']);
+end
+
+%plug new mesh
+t1=clock; fprintf('\n%s','      reading final mesh files...');
+Tria=load('carre1.tria');
+Coor=load('carre1.coor');
+md.mesh.x=Coor(:,1);
+md.mesh.y=Coor(:,2);
+md.mesh.z=zeros(size(Coor,1),1);
+md.mesh.elements=Tria;
+md.mesh.numberofvertices=size(Coor,1);
+md.mesh.numberofelements=size(Tria,1);
+numberofelements2=md.mesh.numberofelements;
+t2=clock;fprintf('%s\n\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
+
+%display number of elements
+fprintf('\n%s %i','      inital number of elements:',numberofelements1);
+fprintf('\n%s %i\n\n','      new    number of elements:',numberofelements2);
+
+%clean up:
+system('rm carre0.mesh carre0.met carre1.tria carre1.coor carre1.meshb');
Index: /issm/trunk/src/m/contrib/bamg/meshread.m
===================================================================
--- /issm/trunk/src/m/contrib/bamg/meshread.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/bamg/meshread.m	(revision 13395)
@@ -0,0 +1,41 @@
+function Struct=meshread(filename);
+
+%some checks
+if ~exist(filename),
+	error(['meshread error message: file ' filename ' not found!']);
+end
+
+fid=fopen(filename,'r');
+
+while (~feof(fid)),
+
+	A=fscanf(fid,'%s',1);
+
+	if strcmp(A,'MeshVersionFormatted');
+		Struct.Version=fscanf(fid,'%s',1);
+
+	elseif strcmp(A,'Dimension'),
+		Struct.Dimension=fscanf(fid,'%i',1);
+
+	elseif strcmp(A,'Vertices'),
+		Struct.nods=fscanf(fid,'%i',1);
+		A=fscanf(fid,'%f %f %f',[3 Struct.nods]);
+		Struct.x=A(1,:)';
+		Struct.y=A(2,:)';
+
+	elseif strcmp(A,'Triangles'),
+		Struct.nels=fscanf(fid,'%i',1);
+		A=fscanf(fid,'%i %i %i',[4 Struct.nels]);
+		Struct.index=A(1:3,:)';
+
+	elseif strcmp(A,'Quadrilaterals'),
+		Struct.nels=fscanf(fid,'%i',1);
+		A=fscanf(fid,'%i %i %i %i',[5 Struct.nels]);
+		Struct.index=A(1:4,:)';
+	else
+		%do nothing
+
+	end
+end
+
+fclose(fid);
Index: /issm/trunk/src/m/contrib/bamg/yams.m
===================================================================
--- /issm/trunk/src/m/contrib/bamg/yams.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/bamg/yams.m	(revision 13395)
@@ -0,0 +1,171 @@
+function md=yams(md,varargin);
+%MESHYAMS - Build model of Antarctica by refining according to observed velocity error estimator
+%
+%   Usage:
+%      md=yams(md,varargin);
+%      where varargin is a lit of paired arguments. 
+%      arguments can be: 'domainoutline': Argus file containing the outline of the domain to be meshed
+%      arguments can be: 'velocities': matlab file containing the velocities [m/yr]
+%      optional arguments: 'groundeddomain': Argus file containing the outline of the grounded ice
+%                          this option is used to minimize the metric on water (no refinement)
+%      optional arguments: 'resolution': initial mesh resolution [m]
+%      optional arguments: 'nsteps': number of steps of mesh adaptation
+%      optional arguments: 'epsilon': average interpolation error wished [m/yr]
+%      optional arguments: 'hmin': minimum edge length
+%      optional arguments: 'hmanx': maximum edge
+%      optional arguments: 'riftoutline': if rifts are present, specifies rift outline file.
+%      
+%
+%   Examples:
+%      md=yams(md,'domainoutline','Domain.exp','velocities','vel.mat');
+%      md=yams(md,'domainoutline','Domain.exp','velocities','vel.mat','groundeddomain','ground.exp');
+%      md=yams(md,'domainoutline','Domain.exp','velocities','vel.mat','groundeddomain','ground.exp','nsteps',6,'epsilon',2,'hmin',500,'hmax',30000);
+
+%recover options
+options=pairoptions(varargin{:});
+options=deleteduplicates(options,1);
+
+%recover some fields
+disp('MeshYams Options:')
+domainoutline=getfieldvalue(options,'domainoutline');
+disp(sprintf('   %-15s: ''%s''','DomainOutline',domainoutline));
+riftoutline=getfieldvalue(options,'riftoutline','N/A');
+disp(sprintf('   %-15s: ''%s''','riftoutline',riftoutline));
+groundeddomain=getfieldvalue(options,'groundeddomain','N/A');
+disp(sprintf('   %-15s: ''%s''','GroundedDomain',groundeddomain));
+velocities=getfieldvalue(options,'velocities');
+disp(sprintf('   %-15s: ''%s''','Velocities',velocities));
+resolution=getfieldvalue(options,'resolution',5000);
+disp(sprintf('   %-15s: %f','Resolution',resolution));
+nsteps=getfieldvalue(options,'nsteps',6);
+disp(sprintf('   %-15s: %i','nsteps',nsteps));
+gradation=getfieldvalue(options,'gradation',2*ones(nsteps,1));
+disp(sprintf('   %-15s: %g','gradation',gradation(1)));
+epsilon=getfieldvalue(options,'epsilon',3);
+disp(sprintf('   %-15s: %f','epsilon',epsilon));
+hmin=getfieldvalue(options,'hmin',500);
+disp(sprintf('   %-15s: %f','hmin',hmin));
+hmax=getfieldvalue(options,'hmax',150*10^3);
+disp(sprintf('   %-15s: %f\n','hmax',hmax));
+
+%mesh with initial resolution
+disp('Initial mesh generation...');
+if strcmpi(riftoutline,'N/A');
+	md=setmesh(md,domainoutline,resolution);
+else
+	md=setmesh(md,domainoutline,riftoutline,resolution);
+	md=meshprocessrifts(md,domainoutline);
+end
+disp(['Initial mesh, number of elements: ' num2str(md.mesh.numberofelements)]);
+
+%load velocities 
+disp('loading velocities...');
+Names=VelFindVarNames(velocities);
+Vel=load(velocities);
+
+%start mesh adaptation
+for i=1:nsteps,
+	disp(['Iteration #' num2str(i) '/' num2str(nsteps)]);
+
+	%interpolate velocities onto mesh
+	disp('   interpolating velocities...');
+	if strcmpi(Names.interp,'node'),
+		vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+		vy_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+	else
+		vx_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+		vy_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+	end
+	field=sqrt(vx_obs.^2+vy_obs.^2);
+
+	%set mask.vertexonwater  field
+	if ~strcmp(groundeddomain,'N/A'),
+		nodeground=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,groundeddomain,'node',2);
+		md.mask.vertexonwater=ones(md.mesh.numberofvertices,1);
+		md.mask.vertexonwater(find(nodeground))=0;
+	else
+		md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+	end
+
+	%adapt according to velocities
+	disp('   adapting...');
+	md=YamsCall(md,field,hmin,hmax,gradation(i),epsilon);
+
+	%if we have rifts, we just messed them up, we need to recreate the segments that constitute those 
+	%rifts, because the segments are used in YamsCall to freeze the rifts elements during refinement.
+	if md.rifts.numrifts, 
+		md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+		md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+		md.mesh.segments=findsegments(md);
+		md=yamsrecreateriftsegments(md);
+	end
+
+end
+	
+disp(['Final mesh, number of elements: ' num2str(md.mesh.numberofelements)]);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%recreate segments
+md.mesh.segments=findsegments(md);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+
+%Fill in rest of fields:
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+if ~strcmp(groundeddomain,'N/A'),
+	nodeground=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,groundeddomain,'node',2);
+	md.mask.vertexonwater=ones(md.mesh.numberofvertices,1);
+	md.mask.vertexonwater(find(nodeground))=0;
+else
+	md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+end
+if strcmpi(Names.interp,'node'),
+	md.inversion.vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+	md.inversion.vy_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+else
+	md.inversion.vx_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
+	md.inversion.vy_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,0);
+end
+md.inversion.vel_obs=sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+
+%deal with rifts 
+if md.rifts.numrifts,
+	%first, recreate rift segments
+	md=meshyamsrecreateriftsegments(md);
+
+	%using the segments, recreate the penaltypairs
+	for j=1:md.rifts.numrifts,
+		rift=md.rifts.riftstruct(j);
+
+		%build normals and lengths of segments:
+		lengths=sqrt((md.mesh.x(rift.segments(:,1))-md.mesh.x(rift.segments(:,2))).^2 + (md.mesh.y(rift.segments(:,1))-md.mesh.y(rift.segments(:,2))).^2 );
+		normalsx=cos(atan2((md.mesh.x(rift.segments(:,1))-md.mesh.x(rift.segments(:,2))) , (md.mesh.y(rift.segments(:,2))-md.mesh.y(rift.segments(:,1)))));
+		normalsy=sin(atan2((md.mesh.x(rift.segments(:,1))-md.mesh.x(rift.segments(:,2))) , (md.mesh.y(rift.segments(:,2))-md.mesh.y(rift.segments(:,1)))));
+
+		%ok, build penaltypairs: 
+		numpenaltypairs=length(rift.segments)/2-1;
+		rift.penaltypairs=zeros(numpenaltypairs,7);
+
+		for i=1:numpenaltypairs,
+			rift.penaltypairs(i,1)=rift.segments(i,2);
+			rift.penaltypairs(i,2)=rift.segments(end-i,2);
+			rift.penaltypairs(i,3)=rift.segments(i,3);
+			rift.penaltypairs(i,4)=rift.segments(end-i,3);
+			rift.penaltypairs(i,5)=normalsx(i)+normalsx(i+1);
+			rift.penaltypairs(i,6)=normalsy(i)+normalsy(i+1);
+			rift.penaltypairs(i,7)=(lengths(i)+lengths(i+1))/2;
+		end
+		%renormalize norms: 
+		norms=sqrt(rift.penaltypairs(:,5).^2+rift.penaltypairs(:,6).^2);
+		rift.penaltypairs(:,5)=rift.penaltypairs(:,5)./norms;
+		rift.penaltypairs(:,6)=rift.penaltypairs(:,6)./norms;
+
+		md.rifts.riftstruct(j)=rift;
+	end
+end
Index: /issm/trunk/src/m/contrib/ecco/MeltingGroundingLines.m
===================================================================
--- /issm/trunk/src/m/contrib/ecco/MeltingGroundingLines.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/ecco/MeltingGroundingLines.m	(revision 13395)
@@ -0,0 +1,26 @@
+function md=MeltingGroundingLines(md,distance,value)
+%MELTINGGROUNDINGLINES - set melting near grounding lines to a constant value
+%
+%   Usage:
+%      md=MeltingGroundingLines(md,distance,value)
+%
+
+%get nodes on ice sheet and on ice shelf
+pos_shelf=find(~md.mask.vertexongroundedice);
+pos_GL=intersect(unique(md.mesh.elements(find(md.mask.elementongroundedice),:)),unique(md.mesh.elements(find(md.mask.elementonfloatingice),:)));
+
+for i=1:length(pos_shelf)
+
+	if (mod(i,100)==0),
+		fprintf('\b\b\b\b\b\b\b%5.2f%s',i/length(pos_shelf)*100,' %');
+	end
+
+	%search the node on ice sheet the closest to i
+	[d posd]=min(sqrt((md.mesh.x(pos_shelf(i))-md.mesh.x(pos_GL)).^2+(md.mesh.y(pos_shelf(i))-md.mesh.y(pos_GL)).^2));
+
+	if d<distance,
+
+		md.melting(pos_shelf(i))=value;
+
+	end
+end
Index: /issm/trunk/src/m/contrib/ecco/PropagateFlagsUntilDistance.m
===================================================================
--- /issm/trunk/src/m/contrib/ecco/PropagateFlagsUntilDistance.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/ecco/PropagateFlagsUntilDistance.m	(revision 13395)
@@ -0,0 +1,60 @@
+function new_flags=PropagateFlagsUntilDistance(md,flags,distance)
+%PROPAGATEFLAGSUNTILDISTANCE
+%
+% Usage: 
+%              flags=PropagateFlagsUntilDistance(md,flags,distance)
+%
+%
+
+new_flags=flags;
+
+%make 3d work in 2d: 
+if md.mesh.dimension==3,
+	md.mesh.x=md.mesh.x2d;
+	md.mesh.y=md.mesh.y2d;
+	md.mesh.elements=md.mesh.elements2d;
+end
+
+%find elements that are at the border of flags: 
+flag_elements=find(flags);
+conn=md.mesh.elementconnectivity(flag_elements,:);
+pos=find(conn);conn(pos)=~flags(conn(pos));
+sum_conn=sum(conn,2);
+border_elements=flag_elements(find(sum_conn>=1));
+
+%average x and y over elements: 
+x_elem=md.mesh.x(md.mesh.elements)*[1;1;1]/3;
+y_elem=md.mesh.y(md.mesh.elements)*[1;1;1]/3;
+
+while 1,
+
+	%keep copy of new_flags for this loop: 
+	new_flags_bak=new_flags;
+
+	%extend new flags by connectivity
+	pos=find(new_flags);
+
+	connected_elements=md.mesh.elementconnectivity(pos,:);
+	connected_elements=connected_elements(find(connected_elements));
+	new_flags(connected_elements)=1;
+
+	%get new elements: 
+	new_elements=find(new_flags & ~new_flags_bak);
+	if ~length(new_elements),
+		%we are done!
+		break;
+	end
+
+	%check which of these new elements are more than distance away from the border elements
+	for i=1:length(new_elements),
+		dist=sqrt(     (x_elem(border_elements)-x_elem(new_elements(i))).^2 + (y_elem(border_elements)-y_elem(new_elements(i))).^2)-distance;
+		if ~any(dist<0)
+			%none of the border elements are within distance, this element is outside out area of interest.
+			%ensure this element never gets found again in the connectivity.
+			pos=find(md.mesh.elementconnectivity==new_elements(i));
+			md.mesh.elementconnectivity(pos)=0;
+			%exclude this new element from the new_flags!
+			new_flags(new_elements(i))=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/contrib/ecco/ecco32issm.m
===================================================================
--- /issm/trunk/src/m/contrib/ecco/ecco32issm.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/ecco/ecco32issm.m	(revision 13395)
@@ -0,0 +1,8 @@
+function nodefield=ecco32issm(field,transition,xecco3,yecco3)
+
+	xecco3linear=xecco3(:); yecco3linear=yecco3(:); %linearize
+	nodefieldlinear=zeros(length(xecco3linear),1);
+	nodefieldlinear(transition(:,1))=field(transition(:,2));
+	nodefield=xecco3;
+	nodefield(:)=nodefieldlinear;
+	%nodefield=nodefield'; %not sure we need that
Index: /issm/trunk/src/m/contrib/ecco/issm2ecco3.m
===================================================================
--- /issm/trunk/src/m/contrib/ecco/issm2ecco3.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/ecco/issm2ecco3.m	(revision 13395)
@@ -0,0 +1,8 @@
+function nodefield=issm2ecco3(field,transition,xecco3,yecco3)
+
+	xecco3linear=xecco3(:); yecco3linear=yecco3(:); %linearize
+	nodefieldlinear=zeros(length(xecco3linear),1);
+	nodefieldlinear(transition(:,1))=field(transition(:,2));
+	nodefield=xecco3;
+	nodefield(:)=nodefieldlinear;
+	%nodefield=nodefield'; %not sure we need that
Index: /issm/trunk/src/m/contrib/gslib/gamv.m
===================================================================
--- /issm/trunk/src/m/contrib/gslib/gamv.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/gslib/gamv.m	(revision 13395)
@@ -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/trunk/src/m/contrib/gslib/gslib.m
===================================================================
--- /issm/trunk/src/m/contrib/gslib/gslib.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/gslib/gslib.m	(revision 13395)
@@ -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/trunk/src/m/contrib/gslib/pkriging.m
===================================================================
--- /issm/trunk/src/m/contrib/gslib/pkriging.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/gslib/pkriging.m	(revision 13395)
@@ -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/trunk/src/m/contrib/gslib/varmap.m
===================================================================
--- /issm/trunk/src/m/contrib/gslib/varmap.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/gslib/varmap.m	(revision 13395)
@@ -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/trunk/src/m/contrib/hack/sia.m
===================================================================
--- /issm/trunk/src/m/contrib/hack/sia.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/hack/sia.m	(revision 13395)
@@ -0,0 +1,26 @@
+function [velx,vely,vel]=sia(md)
+%BALVEL - computation of Shallow Ice velocities
+%
+%   This routine uses the model of Hutter to compute the velocities
+%   of a 2d model using the surface slope
+%
+%   Usage:
+%      [velx,vely,vel]=sia(md)
+
+if md.mesh.dimension~=2,
+	error('Only 2d meshes are allowed to compute velocity balances');
+end
+
+%Get slope
+[sx,sy,s]=slope(md);
+
+%Average thickness and B over all elements.
+summer=[1;1;1];
+hel=md.geometry.thickness(md.mesh.elements)*summer/3;
+Bel=md.B(md.mesh.elements)*summer/3;
+
+Ael=Bel.^(-3);
+
+velx=-2*(md.materials.rho_ice*md.constants.g)^3*s.^2.*sx.*Ael/4.*hel.^4;
+vely=-2*(md.materials.rho_ice*md.constants.g)^3*s.^2.*sy.*Ael/4.*hel.^4;
+vel=sqrt(velx.^2+vely.^2);
Index: /issm/trunk/src/m/contrib/hack/thicknessevolution.m
===================================================================
--- /issm/trunk/src/m/contrib/hack/thicknessevolution.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/hack/thicknessevolution.m	(revision 13395)
@@ -0,0 +1,28 @@
+function dhdt=thicknessevolution(md)
+%THICKNESSEVOLUTION - compute the new thickness of a model after ∆t
+%
+%   This routine compute the new thickness of a model after a time step
+%   according to the following formula:
+%   dh/dt=-div(Hu)
+%
+%   Usage:
+%      dhdt=thicknessevolution(md)
+
+if (length(md.initialization.vx)~=md.mesh.numberofvertices)|(length(md.initialization.vy)~=md.mesh.numberofvertices)
+	error(['thicknessevolution error message: vx and vy should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+
+%load some variables 
+H=md.geometry.thickness;
+vx=md.initialization.vx;
+vy=md.initialization.vy;
+index=md.mesh.elements;
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(md.mesh.elements,md.mesh.x,md.mesh.y); 
+
+%compute dhdt=div(Hu)
+summation=1/3*ones(3,1);
+dhdt=(vx(index)*summation).*sum( H(index).*alpha,2) + (vy(index)*summation).*sum(H(index).*beta,2) ...
+	+ ( H(index)*summation).*sum(vx(index).*alpha,2) + ( H(index)*summation).*sum(vy(index).*beta,2);
+dhdt=-dhdt;
Index: /issm/trunk/src/m/contrib/hack/tres.m
===================================================================
--- /issm/trunk/src/m/contrib/hack/tres.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/hack/tres.m	(revision 13395)
@@ -0,0 +1,121 @@
+function md=tres(md,string)
+%TRES - transfer results results to corresponding model fields. 
+%
+%    Usage: md=tres(md,string)
+%
+%    Example: md=tres(md,'diagnostic');
+
+%check number of arguments
+
+if strcmpi(string,'diagnostic'),
+	if md.mesh.dimension==2,
+		md.initialization.vx=md.results.DiagnosticSolution.Vx;
+		md.initialization.vy=md.results.DiagnosticSolution.Vy;
+	else 
+		md.initialization.vx=md.results.DiagnosticSolution.Vx;
+		md.initialization.vy=md.results.DiagnosticSolution.Vy;
+		md.initialization.vz=md.results.DiagnosticSolution.Vz;
+	end
+	md.initialization.vel=md.results.DiagnosticSolution.Vel;
+
+	if isfield(md.results.DiagnosticSolution,'Pressure'),
+		md.initialization.pressure=md.results.DiagnosticSolution.Pressure;
+	end
+	if md.rifts.numrifts,
+		if isfield(md.results.DiagnosticSolution,'riftproperties'),
+			md.rifts.riftproperties=md.results.DiagnosticSolution.riftproperties;
+		end
+	end
+	if md.inversion.iscontrol==1,
+		for control_parameters=md.inversion.control_parameters
+			%Will need to be updated... good luck ;)
+			md.(EnumToModelField(control_parameters))=md.results.DiagnosticSolution.(EnumToString(control_parameters));
+		end
+	end
+
+elseif strcmpi(string,'dakota'),
+	md.qmu.results=md.results.dakota;
+
+elseif strcmpi(string,'flaim'),
+	md.flaim.solution=md.results.FlaimSolution.solution;
+	md.flaim.quality =md.results.FlaimSolution.quality;
+
+elseif strcmpi(string,'transient'),
+	results=md.results.TransientSolution;
+	results2.Vel=NaN;
+	count=1;
+	for i=1:length(results),
+		if ~isempty(md.results.TransientSolution(i).Vel),
+			results2(count).Vel=md.results.TransientSolution(i).Vel;
+			results2(count).Surface=md.results.TransientSolution(i).Surface;
+			results2(count).Thickness=md.results.TransientSolution(i).Thickness;
+			results2(count).Bed=md.results.TransientSolution(i).Bed;
+			results2(count).Vx=md.results.TransientSolution(i).Vx;
+			results2(count).Vy=md.results.TransientSolution(i).Vy;
+			results2(count).time=md.results.TransientSolution(i).time;
+			results2(count).step=md.results.TransientSolution(i).step;
+			if ~strcmpi(md.groundingline.migration,'None'),
+				results2(count).ElementOnIceShelf=md.results.TransientSolution(i).ElementOnIceShelf;
+			end
+			count=count+1;
+		end
+	end
+	md.results.TransientSolution=results2;
+	clear results,results2;
+elseif strcmpi(string,'steadystate'),
+	md.initialization.vx=md.results.SteadystateSolution.Vx;
+	md.initialization.vy=md.results.SteadystateSolution.Vy;
+	if isfield(md.results.SteadystateSolution,'Vz'),
+		md.initialization.vz=md.results.SteadystateSolution.Vz;
+	end
+
+	md.initialization.vel=md.results.SteadystateSolution.Vel;
+	md.initialization.pressure=md.results.SteadystateSolution.Pressure;
+	md.initialization.temperature=md.results.SteadystateSolution.Temperature;
+	md.basalforcings.melting_rate=md.results.SteadystateSolution.BasalforcingsMeltingRate;
+
+	if md.inversion.iscontrol==1,
+		for control_parameters=md.inversion.control_parameters
+			md.(EnumToModelField(control_parameters))=md.results.SteadystateSolution.(EnumToString(control_parameters));
+		end
+	end
+
+elseif strcmpi(string,'thermal'),
+	md.initialization.temperature=md.results.ThermalSolution.Temperature;
+	md.basalforcings.melting_rate=md.results.ThermalSolution.BasalMeltingRate;
+elseif strcmpi(string,'hydrology'),
+	md.initialization.watercolumn=md.results.HydrologySolution.Watercolumn;
+
+else 
+	error(['tres error message: analysis ' string ' not supported yet!']);
+end
+end 
+function string=EnumToModelField(enum) % {{{
+	%ENUMTOMODELFIELD - output string of model field associated to enum
+	%
+	%   Usage:
+	%      string=EnumToModelField(enum)
+
+	disp('Warning: EnumToModelField is deprecated, it cannot work with new model definition. This function will be removed in the future');
+
+	switch enum,
+
+		case ThicknessEnum(), string='thickness'; return
+		case FrictionCoefficientEnum(), string='drag_coefficient'; return
+		case MaterialsRheologyBEnum(), string='rheology_B'; return
+		case MaterialsRheologyBbarEnum(), string='rheology_B'; return
+		case MaterialsRheologyZEnum(), string='rheology_Z'; return
+		case MaterialsRheologyZbarEnum(), string='rheology_Z'; return
+		case BalancethicknessThickeningRateEnum(), string='dhdt'; return
+		case VxEnum(), string='vx'; return
+		case InversionVxObsEnum(), string='vx_obs'; return
+		case VyEnum(), string='vy'; return
+		case InversionVyObsEnum(), string='vy_obs'; return
+		case BasalforcingsMeltingRateEnum(), string='basal_melting_rate'; return
+		case SurfaceforcingsAccumulationRateEnum(), string='surface_accumulation_rate'; return
+		case SurfaceforcingsAblationRateEnum(), string='surface_ablation_rate'; return
+		case SurfaceforcingsMassBalanceEnum(), string='surface_mass_balance'; return
+		otherwise, error(['Enum ' num2str(enum)  ' not found associated to any model field']);
+
+		end
+	end % }}}
Index: /issm/trunk/src/m/contrib/hydrology/effectivepressure.m
===================================================================
--- /issm/trunk/src/m/contrib/hydrology/effectivepressure.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/hydrology/effectivepressure.m	(revision 13395)
@@ -0,0 +1,12 @@
+function Neff=effectivepressure(md)
+%EFFECTIVEPRESSURE - compute effective pressure
+%
+%   Usage:
+%      Neff=effectivepressure(md)
+%
+%   Example:
+%      Neff=effectivepressure(md)
+
+Neff=md.materials.rho_ice*md.constants.g*md.geometry.thickness+md.materials.rho_ice*md.constants.g*md.geometry.bed;
+pos=find(Neff<0);
+Neff(pos)=0;
Index: /issm/trunk/src/m/contrib/massbalance/contourmassbalance.m
===================================================================
--- /issm/trunk/src/m/contrib/massbalance/contourmassbalance.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/massbalance/contourmassbalance.m	(revision 13395)
@@ -0,0 +1,45 @@
+function dhdt=contourmassbalance(md,file)
+%CONTOURMASSBALANCE - compute the mass balance on a contour
+%
+%   Usage:
+%      dhdt=contourmassbalance(md,file)
+
+%some checks
+if nargin~=2,
+	help contourmassbalance
+	error('contourmassbalance error message: bad usage');
+end
+if ((length(md.initialization.vx)~=md.mesh.numberofvertices)|(length(md.initialization.vy)~=md.mesh.numberofvertices))
+	error(['thicknessevolution error message: vx and vy should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+if ~exist(file),
+	error(['thicknessevolution error message: file ' file ' not found']);
+end
+
+%Get segments enveloping contour
+segments=contourenvelope(md,file);
+%md.diagnostic.icefront=segments; plotmodel(md,'data','pressureload','expdisp',file);
+
+%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));
+
+%conputing Mass flux
+x=md.mesh.x;
+y=md.mesh.y;
+vx=mean(md.initialization.vx(segments(:,1:end-1)),2);
+vy=mean(md.initialization.vy(segments(:,1:end-1)),2);
+H=mean(md.geometry.thickness(segments(:,1:end-1)),2);
+nx=cos(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+ny=sin(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+L=sqrt((x(segments(:,1))-x(segments(:,2))).^2+(y(segments(:,2))-y(segments(:,1))).^2);
+flux = - md.materials.rho_ice*sum(L.*H.*(vx.*nx+vy.*ny)); %outflux is negative!
+disp(['mass outflux on ' file ' = ' num2str(-flux/10^9) ' Gt/yr']);
+areas=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+dhdt=flux/(sum(areas(find(elemin)))*md.materials.rho_ice);
+disp(['dhdt on ' file ' (Flux  method) = ' num2str(dhdt) ' m/yr']);
+
+dhdt=thicknessevolution(md);
+in=find(elemin);
+dhdt=sum(dhdt(in).*areas(in))/sum(areas(in));
+disp(['dhdt on ' file ' (divHV method) = ' num2str(dhdt) ' m/yr']);
Index: /issm/trunk/src/m/contrib/massbalance/divergence.m
===================================================================
--- /issm/trunk/src/m/contrib/massbalance/divergence.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/massbalance/divergence.m	(revision 13395)
@@ -0,0 +1,27 @@
+function div=divergence(md,a,b)
+%DIVERGENCE - divergence of [a;b] vector, using model's triangulation.
+%
+%   Usage:
+%      div=divergence(md,a,b)
+
+if (md.mesh.dimension==2),
+	numberofelements=md.mesh.numberofelements;
+	numberofnodes=md.mesh.numberofvertices;
+	index=md.mesh.elements;
+	x=md.mesh.x; y=md.mesh.y; z=md.mesh.z;
+else
+	numberofelements=md.mesh.numberofelements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	index=md.mesh.elements2d;
+	x=md.mesh.x2d; y=md.mesh.y2d;
+end
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+
+summation=[1;1;1];
+dx=(a(index).*alpha)*summation;
+dy=(b(index).*beta)*summation;
+
+div=dx+dy;
+div=averaging(md,div,1);
Index: /issm/trunk/src/m/contrib/massbalance/outflow.m
===================================================================
--- /issm/trunk/src/m/contrib/massbalance/outflow.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/massbalance/outflow.m	(revision 13395)
@@ -0,0 +1,18 @@
+function flag=outflow(md);
+%OUTFLOW - flag nodes on outflux boundary
+%
+%   Usage:
+%      flag=outflow(md);
+
+A=md.mesh.segments(:,1);
+B=md.mesh.segments(:,2);
+Nx=-(md.mesh.y(A)-md.mesh.y(B));
+Ny=  md.mesh.x(A)-md.mesh.x(B);
+Vx=(md.initialization.vx(A)+md.initialization.vx(B))/2;
+Vy=(md.initialization.vy(A)+md.initialization.vy(B))/2;
+
+%dot product
+VdotN=Vx.*Nx+Vy.*Ny;
+
+flag=zeros(md.mesh.numberofvertices,1);
+flag(A(find(VdotN>0)))=1;
Index: /issm/trunk/src/m/contrib/oasis/carter.m
===================================================================
--- /issm/trunk/src/m/contrib/oasis/carter.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/oasis/carter.m	(revision 13395)
@@ -0,0 +1,28 @@
+function attenuation=carter(temperature)
+%CARTER - attenuation as a function of temperature
+%
+%   TWO WAY - Attenuation (in dB/m) as a function of temperature (K)
+%   From Carter at al. 2007 (Radar-based subglacial lake classification in Antarctica)
+%   Figure 4
+%
+%   Usage:
+%      attenuation=carter(temperature)
+
+if(temperature<0)
+	error('input temperature should be in Kelvin (positive)');
+end
+T=temperature-273.15;
+
+Temp=[-50 -45 -40 -35 -30 -25 -20 -15 -10 -5 0]';
+A=[0.0015 0.002 0.003 0.0042 0.0055 0.0083 0.012 0.0175 0.026 0.038 0.055]';
+
+%Now, do a cubic fit between Temp and B: 
+[cfun,gof,output]=fit(Temp,A,'cubicspline');
+%breaks=cfun.p.breaks;
+%coeff=cfun.p.coefs;
+
+%Calculate attenuation
+attenuation=cfun(T);
+
+%Make it a 2 way attenuation
+attenuation=2*attenuation;
Index: /issm/trunk/src/m/contrib/uci/expremovestraightsegments.m
===================================================================
--- /issm/trunk/src/m/contrib/uci/expremovestraightsegments.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/uci/expremovestraightsegments.m	(revision 13395)
@@ -0,0 +1,31 @@
+function expremovestraightsegments(newfilename,filename,cutoff)
+%EXPREMOVESTRAIGHTSEGMENTS:  remove straight segments connecting contours.
+%
+% Usage: expremovestraightsegments('argus.exp',100); 
+%
+%
+
+a=expread(filename,1);
+newcontours=a(1);
+
+for i=1:length(a),
+	contour=a(i);
+	
+	s=sqrt(contour.x.^2+contour.y.^2);
+	d=diff(s);
+	
+	pos=find(abs(d)>cutoff);
+	pos=[0;pos;length(contour.x)];
+
+	for j=1:length(pos)-1,
+
+		newcontour=contour;
+		newcontour.x=contour.x(pos(j)+1:pos(j+1));
+		newcontour.y=contour.y(pos(j)+1:pos(j+1));
+		newcontour.nods=length(newcontour.x);
+		newcontours(end+1)=newcontour;
+	end
+end
+newcontours=newcontours(2:end);
+
+expwrite(newcontours,newfilename);
Index: /issm/trunk/src/m/contrib/uci/expsplit.m
===================================================================
--- /issm/trunk/src/m/contrib/uci/expsplit.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/uci/expsplit.m	(revision 13395)
@@ -0,0 +1,31 @@
+function expsplit(domainoutline)
+%EXPSPLIT - split exp file into sub-contours
+%
+%   This routine reads in a domain outline file (Argus format) and plots all the contours 
+%   This will create as many files there are contours in the domain, each file will be postfix with _i
+%   where i is the contour name. 
+%
+%   Usage:
+%      expsplit(domainoutline)
+%
+%   Example:
+%      expsplit('Domain.exp');
+%
+%   See also EXPMASTER, EXPDOC
+
+%check nargin
+if ~nargin | nargin>1
+	help expsplit
+	error('expsplit error message: bad usage');
+end
+
+[path,root,ext]=fileparts(domainoutline);
+
+%Read file: 
+domains=expread(domainoutline,1);
+
+%split and write contours: 
+for i=1:length(domains),
+	subdomain=domains(i);
+	expwrite(subdomain,[root '_' num2str(i)  ext]);
+end
Index: /issm/trunk/src/m/contrib/uci/pargenerate.m
===================================================================
--- /issm/trunk/src/m/contrib/uci/pargenerate.m	(revision 13395)
+++ /issm/trunk/src/m/contrib/uci/pargenerate.m	(revision 13395)
@@ -0,0 +1,45 @@
+function pargenerate(filename,xm,ym,data,varargin)
+%PARGENERATE - generate parameter file for images ala Rignot
+%
+%   Usage: 
+%      pargenerate(filename,data,xm,ym,options);
+%
+%   Supported options:
+%      - title: dataset title
+%      - latitude: standard latitude (degree)
+%      - meridian: meridian (degree)
+%      - format: binary format
+
+%process options
+options=pairoptions(varargin{:});
+Title=getfieldvalue(options,'title','N/A');
+latitude=getfieldvalue(options,'latitude','N/A');
+meridian=getfieldvalue(options,'meridian','N/A');
+format=getfieldvalue(options,'format','single');
+
+%Get data info
+[nlines ncols]=size(data);
+xmin=min(xm);
+ymax=max(ym);
+postx=abs(xm(2)-xm(1));
+posty=abs(ym(2)-ym(1));
+
+%Open header file and get machine type
+fid=fopen(filename,'wt');
+[filename, permission, machineformat, encoding] = fopen(fid);
+
+%write header file
+fprintf(fid,'%s\n','ISSM gridded dataset parameter file');
+fprintf(fid,'%s%s\n','title: ',Title);
+fprintf(fid,'%s  \n','DEM_projection: PS');
+fprintf(fid,'%s%s\n','data_format: ',format);
+fprintf(fid,'%s%s\n','endian:      ',machineformat);
+fprintf(fid,'%s%d\n','width:  ',ncols);
+fprintf(fid,'%s%d\n','nlines: ',nlines);
+fprintf(fid,'%s%g%s\n','PS_secant_lat:    ',latitude,'   decimal degrees');
+fprintf(fid,'%s%g%s\n','PS_meridian_long: ',meridian,'   decimal degrees');
+fprintf(fid,'%s%-15.10g\n','PS_corner_north:  ',ymax);
+fprintf(fid,'%s%-15.10g\n','PS_corner_east:   ',xmin);
+fprintf(fid,'%s%g%s\n','PS_post_north:    ',postx,' m');
+fprintf(fid,'%s%g%s\n','PS_post_east:     ',posty,' m');
+fclose(fid);
Index: /issm/trunk/src/m/enum/AdolcParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AdolcParamEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/AdolcParamEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=AdolcParamEnum()
+%ADOLCPARAMENUM - Enum of AdolcParam
+%
+%   WARNING: DO NOT 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=AdolcParamEnum()
+
+macro=StringToEnum('AdolcParam');
Index: /issm/trunk/src/m/enum/AutodiffDependentsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffDependentsEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/AutodiffDependentsEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=AutodiffDependentsEnum()
+%AUTODIFFDEPENDENTSENUM - Enum of AutodiffDependents
+%
+%   WARNING: DO NOT 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=AutodiffDependentsEnum()
+
+macro=StringToEnum('AutodiffDependents');
Index: sm/trunk/src/m/enum/AutodiffForwardEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffForwardEnum.m	(revision 13394)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=AutodiffForwardEnum()
-%AUTODIFFFORWARDENUM - Enum of AutodiffForward
-%
-%   WARNING: DO NOT 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=AutodiffForwardEnum()
-
-macro=StringToEnum('AutodiffForward');
Index: /issm/trunk/src/m/enum/AutodiffFosForwardOutputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffFosForwardOutputEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/AutodiffFosForwardOutputEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=AutodiffFosForwardOutputEnum()
+%AUTODIFFFOSFORWARDOUTPUTENUM - Enum of AutodiffFosForwardOutput
+%
+%   WARNING: DO NOT 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=AutodiffFosForwardOutputEnum()
+
+macro=StringToEnum('AutodiffFosForwardOutput');
Index: /issm/trunk/src/m/enum/AutodiffIndependentsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffIndependentsEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/AutodiffIndependentsEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=AutodiffIndependentsEnum()
+%AUTODIFFINDEPENDENTSENUM - Enum of AutodiffIndependents
+%
+%   WARNING: DO NOT 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=AutodiffIndependentsEnum()
+
+macro=StringToEnum('AutodiffIndependents');
Index: /issm/trunk/src/m/enum/AutodiffJacobianEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffJacobianEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/AutodiffJacobianEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=AutodiffJacobianEnum()
+%AUTODIFFJACOBIANENUM - Enum of AutodiffJacobian
+%
+%   WARNING: DO NOT 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=AutodiffJacobianEnum()
+
+macro=StringToEnum('AutodiffJacobian');
Index: /issm/trunk/src/m/enum/AutodiffNumDependentsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffNumDependentsEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/AutodiffNumDependentsEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=AutodiffNumDependentsEnum()
+%AUTODIFFNUMDEPENDENTSENUM - Enum of AutodiffNumDependents
+%
+%   WARNING: DO NOT 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=AutodiffNumDependentsEnum()
+
+macro=StringToEnum('AutodiffNumDependents');
Index: /issm/trunk/src/m/enum/AutodiffNumIndependentsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffNumIndependentsEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/AutodiffNumIndependentsEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=AutodiffNumIndependentsEnum()
+%AUTODIFFNUMINDEPENDENTSENUM - Enum of AutodiffNumIndependents
+%
+%   WARNING: DO NOT 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=AutodiffNumIndependentsEnum()
+
+macro=StringToEnum('AutodiffNumIndependents');
Index: sm/trunk/src/m/enum/AutodiffReverseEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffReverseEnum.m	(revision 13394)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=AutodiffReverseEnum()
-%AUTODIFFREVERSEENUM - Enum of AutodiffReverse
-%
-%   WARNING: DO NOT 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=AutodiffReverseEnum()
-
-macro=StringToEnum('AutodiffReverse');
Index: /issm/trunk/src/m/enum/AutodiffXpEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffXpEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/AutodiffXpEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=AutodiffXpEnum()
+%AUTODIFFXPENUM - Enum of AutodiffXp
+%
+%   WARNING: DO NOT 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=AutodiffXpEnum()
+
+macro=StringToEnum('AutodiffXp');
Index: /issm/trunk/src/m/enum/EnumDefinitions.py
===================================================================
--- /issm/trunk/src/m/enum/EnumDefinitions.py	(revision 13394)
+++ /issm/trunk/src/m/enum/EnumDefinitions.py	(revision 13395)
@@ -1,2 +1,4 @@
+from StringToEnum import StringToEnum
+
 """
 
@@ -7,14 +9,4 @@
 """
 
-def AutodiffForwardEnum():
-	"""
-	AUTODIFFFORWARDENUM - Enum of AutodiffForward
-
-	   Usage:
-	      macro=AutodiffForwardEnum()
-	"""
-
-	return StringToEnum('AutodiffForward')
-
 def AutodiffIsautodiffEnum():
 	"""
@@ -25,15 +17,75 @@
 	"""
 
-	return StringToEnum('AutodiffIsautodiff')
-
-def AutodiffReverseEnum():
-	"""
-	AUTODIFFREVERSEENUM - Enum of AutodiffReverse
-
-	   Usage:
-	      macro=AutodiffReverseEnum()
-	"""
-
-	return StringToEnum('AutodiffReverse')
+	return StringToEnum('AutodiffIsautodiff')[0]
+
+def AutodiffDependentsEnum():
+	"""
+	AUTODIFFDEPENDENTSENUM - Enum of AutodiffDependents
+
+	   Usage:
+	      macro=AutodiffDependentsEnum()
+	"""
+
+	return StringToEnum('AutodiffDependents')[0]
+
+def AutodiffNumDependentsEnum():
+	"""
+	AUTODIFFNUMDEPENDENTSENUM - Enum of AutodiffNumDependents
+
+	   Usage:
+	      macro=AutodiffNumDependentsEnum()
+	"""
+
+	return StringToEnum('AutodiffNumDependents')[0]
+
+def AutodiffIndependentsEnum():
+	"""
+	AUTODIFFINDEPENDENTSENUM - Enum of AutodiffIndependents
+
+	   Usage:
+	      macro=AutodiffIndependentsEnum()
+	"""
+
+	return StringToEnum('AutodiffIndependents')[0]
+
+def AutodiffNumIndependentsEnum():
+	"""
+	AUTODIFFNUMINDEPENDENTSENUM - Enum of AutodiffNumIndependents
+
+	   Usage:
+	      macro=AutodiffNumIndependentsEnum()
+	"""
+
+	return StringToEnum('AutodiffNumIndependents')[0]
+
+def AutodiffJacobianEnum():
+	"""
+	AUTODIFFJACOBIANENUM - Enum of AutodiffJacobian
+
+	   Usage:
+	      macro=AutodiffJacobianEnum()
+	"""
+
+	return StringToEnum('AutodiffJacobian')[0]
+
+def AutodiffXpEnum():
+	"""
+	AUTODIFFXPENUM - Enum of AutodiffXp
+
+	   Usage:
+	      macro=AutodiffXpEnum()
+	"""
+
+	return StringToEnum('AutodiffXp')[0]
+
+def AutodiffFosForwardOutputEnum():
+	"""
+	AUTODIFFFOSFORWARDOUTPUTENUM - Enum of AutodiffFosForwardOutput
+
+	   Usage:
+	      macro=AutodiffFosForwardOutputEnum()
+	"""
+
+	return StringToEnum('AutodiffFosForwardOutput')[0]
 
 def BalancethicknessSpcthicknessEnum():
@@ -45,5 +97,5 @@
 	"""
 
-	return StringToEnum('BalancethicknessSpcthickness')
+	return StringToEnum('BalancethicknessSpcthickness')[0]
 
 def BalancethicknessStabilizationEnum():
@@ -55,5 +107,5 @@
 	"""
 
-	return StringToEnum('BalancethicknessStabilization')
+	return StringToEnum('BalancethicknessStabilization')[0]
 
 def BalancethicknessThickeningRateEnum():
@@ -65,5 +117,5 @@
 	"""
 
-	return StringToEnum('BalancethicknessThickeningRate')
+	return StringToEnum('BalancethicknessThickeningRate')[0]
 
 def BasalforcingsGeothermalfluxEnum():
@@ -75,5 +127,5 @@
 	"""
 
-	return StringToEnum('BasalforcingsGeothermalflux')
+	return StringToEnum('BasalforcingsGeothermalflux')[0]
 
 def BasalforcingsMeltingRateCorrectionEnum():
@@ -85,5 +137,5 @@
 	"""
 
-	return StringToEnum('BasalforcingsMeltingRateCorrection')
+	return StringToEnum('BasalforcingsMeltingRateCorrection')[0]
 
 def BasalforcingsMeltingRateEnum():
@@ -95,5 +147,5 @@
 	"""
 
-	return StringToEnum('BasalforcingsMeltingRate')
+	return StringToEnum('BasalforcingsMeltingRate')[0]
 
 def BathymetryEnum():
@@ -105,5 +157,5 @@
 	"""
 
-	return StringToEnum('Bathymetry')
+	return StringToEnum('Bathymetry')[0]
 
 def BedEnum():
@@ -115,5 +167,5 @@
 	"""
 
-	return StringToEnum('Bed')
+	return StringToEnum('Bed')[0]
 
 def ConstantsGEnum():
@@ -125,5 +177,5 @@
 	"""
 
-	return StringToEnum('ConstantsG')
+	return StringToEnum('ConstantsG')[0]
 
 def ConstantsReferencetemperatureEnum():
@@ -135,5 +187,5 @@
 	"""
 
-	return StringToEnum('ConstantsReferencetemperature')
+	return StringToEnum('ConstantsReferencetemperature')[0]
 
 def ConstantsYtsEnum():
@@ -145,5 +197,5 @@
 	"""
 
-	return StringToEnum('ConstantsYts')
+	return StringToEnum('ConstantsYts')[0]
 
 def DiagnosticAbstolEnum():
@@ -155,5 +207,5 @@
 	"""
 
-	return StringToEnum('DiagnosticAbstol')
+	return StringToEnum('DiagnosticAbstol')[0]
 
 def DiagnosticIcefrontEnum():
@@ -165,5 +217,5 @@
 	"""
 
-	return StringToEnum('DiagnosticIcefront')
+	return StringToEnum('DiagnosticIcefront')[0]
 
 def DiagnosticIsnewtonEnum():
@@ -175,5 +227,5 @@
 	"""
 
-	return StringToEnum('DiagnosticIsnewton')
+	return StringToEnum('DiagnosticIsnewton')[0]
 
 def DiagnosticMaxiterEnum():
@@ -185,5 +237,5 @@
 	"""
 
-	return StringToEnum('DiagnosticMaxiter')
+	return StringToEnum('DiagnosticMaxiter')[0]
 
 def DiagnosticNumRequestedOutputsEnum():
@@ -195,5 +247,5 @@
 	"""
 
-	return StringToEnum('DiagnosticNumRequestedOutputs')
+	return StringToEnum('DiagnosticNumRequestedOutputs')[0]
 
 def DiagnosticPenaltyFactorEnum():
@@ -205,5 +257,5 @@
 	"""
 
-	return StringToEnum('DiagnosticPenaltyFactor')
+	return StringToEnum('DiagnosticPenaltyFactor')[0]
 
 def DiagnosticReferentialEnum():
@@ -215,5 +267,5 @@
 	"""
 
-	return StringToEnum('DiagnosticReferential')
+	return StringToEnum('DiagnosticReferential')[0]
 
 def DiagnosticReltolEnum():
@@ -225,5 +277,5 @@
 	"""
 
-	return StringToEnum('DiagnosticReltol')
+	return StringToEnum('DiagnosticReltol')[0]
 
 def DiagnosticRequestedOutputsEnum():
@@ -235,5 +287,5 @@
 	"""
 
-	return StringToEnum('DiagnosticRequestedOutputs')
+	return StringToEnum('DiagnosticRequestedOutputs')[0]
 
 def DiagnosticRestolEnum():
@@ -245,5 +297,5 @@
 	"""
 
-	return StringToEnum('DiagnosticRestol')
+	return StringToEnum('DiagnosticRestol')[0]
 
 def DiagnosticRiftPenaltyLockEnum():
@@ -255,5 +307,5 @@
 	"""
 
-	return StringToEnum('DiagnosticRiftPenaltyLock')
+	return StringToEnum('DiagnosticRiftPenaltyLock')[0]
 
 def DiagnosticRiftPenaltyThresholdEnum():
@@ -265,5 +317,5 @@
 	"""
 
-	return StringToEnum('DiagnosticRiftPenaltyThreshold')
+	return StringToEnum('DiagnosticRiftPenaltyThreshold')[0]
 
 def DiagnosticShelfDampeningEnum():
@@ -275,5 +327,5 @@
 	"""
 
-	return StringToEnum('DiagnosticShelfDampening')
+	return StringToEnum('DiagnosticShelfDampening')[0]
 
 def DiagnosticSpcvxEnum():
@@ -285,5 +337,5 @@
 	"""
 
-	return StringToEnum('DiagnosticSpcvx')
+	return StringToEnum('DiagnosticSpcvx')[0]
 
 def DiagnosticSpcvyEnum():
@@ -295,5 +347,5 @@
 	"""
 
-	return StringToEnum('DiagnosticSpcvy')
+	return StringToEnum('DiagnosticSpcvy')[0]
 
 def DiagnosticSpcvzEnum():
@@ -305,5 +357,5 @@
 	"""
 
-	return StringToEnum('DiagnosticSpcvz')
+	return StringToEnum('DiagnosticSpcvz')[0]
 
 def DiagnosticStokesreconditioningEnum():
@@ -315,5 +367,5 @@
 	"""
 
-	return StringToEnum('DiagnosticStokesreconditioning')
+	return StringToEnum('DiagnosticStokesreconditioning')[0]
 
 def DiagnosticVertexPairingEnum():
@@ -325,5 +377,5 @@
 	"""
 
-	return StringToEnum('DiagnosticVertexPairing')
+	return StringToEnum('DiagnosticVertexPairing')[0]
 
 def DiagnosticViscosityOvershootEnum():
@@ -335,5 +387,5 @@
 	"""
 
-	return StringToEnum('DiagnosticViscosityOvershoot')
+	return StringToEnum('DiagnosticViscosityOvershoot')[0]
 
 def FlowequationBordermacayealEnum():
@@ -345,5 +397,5 @@
 	"""
 
-	return StringToEnum('FlowequationBordermacayeal')
+	return StringToEnum('FlowequationBordermacayeal')[0]
 
 def FlowequationBorderpattynEnum():
@@ -355,5 +407,5 @@
 	"""
 
-	return StringToEnum('FlowequationBorderpattyn')
+	return StringToEnum('FlowequationBorderpattyn')[0]
 
 def FlowequationBorderstokesEnum():
@@ -365,5 +417,5 @@
 	"""
 
-	return StringToEnum('FlowequationBorderstokes')
+	return StringToEnum('FlowequationBorderstokes')[0]
 
 def FlowequationElementEquationEnum():
@@ -375,5 +427,5 @@
 	"""
 
-	return StringToEnum('FlowequationElementEquation')
+	return StringToEnum('FlowequationElementEquation')[0]
 
 def FlowequationIshutterEnum():
@@ -385,5 +437,15 @@
 	"""
 
-	return StringToEnum('FlowequationIshutter')
+	return StringToEnum('FlowequationIshutter')[0]
+
+def FlowequationIsl1l2Enum():
+	"""
+	FLOWEQUATIONISL1L2ENUM - Enum of FlowequationIsl1l2
+
+	   Usage:
+	      macro=FlowequationIsl1l2Enum()
+	"""
+
+	return StringToEnum('FlowequationIsl1l2')[0]
 
 def FlowequationIsmacayealpattynEnum():
@@ -395,5 +457,5 @@
 	"""
 
-	return StringToEnum('FlowequationIsmacayealpattyn')
+	return StringToEnum('FlowequationIsmacayealpattyn')[0]
 
 def FlowequationIsstokesEnum():
@@ -405,5 +467,5 @@
 	"""
 
-	return StringToEnum('FlowequationIsstokes')
+	return StringToEnum('FlowequationIsstokes')[0]
 
 def FlowequationVertexEquationEnum():
@@ -415,5 +477,5 @@
 	"""
 
-	return StringToEnum('FlowequationVertexEquation')
+	return StringToEnum('FlowequationVertexEquation')[0]
 
 def FrictionCoefficientEnum():
@@ -425,5 +487,5 @@
 	"""
 
-	return StringToEnum('FrictionCoefficient')
+	return StringToEnum('FrictionCoefficient')[0]
 
 def FrictionPEnum():
@@ -435,5 +497,5 @@
 	"""
 
-	return StringToEnum('FrictionP')
+	return StringToEnum('FrictionP')[0]
 
 def FrictionQEnum():
@@ -445,5 +507,5 @@
 	"""
 
-	return StringToEnum('FrictionQ')
+	return StringToEnum('FrictionQ')[0]
 
 def GeometryHydrostaticRatioEnum():
@@ -455,5 +517,5 @@
 	"""
 
-	return StringToEnum('GeometryHydrostaticRatio')
+	return StringToEnum('GeometryHydrostaticRatio')[0]
 
 def HydrologyCREnum():
@@ -465,5 +527,5 @@
 	"""
 
-	return StringToEnum('HydrologyCR')
+	return StringToEnum('HydrologyCR')[0]
 
 def HydrologyKnEnum():
@@ -475,5 +537,5 @@
 	"""
 
-	return StringToEnum('HydrologyKn')
+	return StringToEnum('HydrologyKn')[0]
 
 def HydrologyNEnum():
@@ -485,5 +547,5 @@
 	"""
 
-	return StringToEnum('HydrologyN')
+	return StringToEnum('HydrologyN')[0]
 
 def HydrologyPEnum():
@@ -495,5 +557,5 @@
 	"""
 
-	return StringToEnum('HydrologyP')
+	return StringToEnum('HydrologyP')[0]
 
 def HydrologyQEnum():
@@ -505,5 +567,5 @@
 	"""
 
-	return StringToEnum('HydrologyQ')
+	return StringToEnum('HydrologyQ')[0]
 
 def HydrologySpcwatercolumnEnum():
@@ -515,5 +577,5 @@
 	"""
 
-	return StringToEnum('HydrologySpcwatercolumn')
+	return StringToEnum('HydrologySpcwatercolumn')[0]
 
 def HydrologyStabilizationEnum():
@@ -525,5 +587,5 @@
 	"""
 
-	return StringToEnum('HydrologyStabilization')
+	return StringToEnum('HydrologyStabilization')[0]
 
 def InversionControlParametersEnum():
@@ -535,5 +597,5 @@
 	"""
 
-	return StringToEnum('InversionControlParameters')
+	return StringToEnum('InversionControlParameters')[0]
 
 def InversionCostFunctionEnum():
@@ -545,5 +607,5 @@
 	"""
 
-	return StringToEnum('InversionCostFunction')
+	return StringToEnum('InversionCostFunction')[0]
 
 def InversionCostFunctionThresholdEnum():
@@ -555,5 +617,5 @@
 	"""
 
-	return StringToEnum('InversionCostFunctionThreshold')
+	return StringToEnum('InversionCostFunctionThreshold')[0]
 
 def InversionCostFunctionsCoefficientsEnum():
@@ -565,5 +627,5 @@
 	"""
 
-	return StringToEnum('InversionCostFunctionsCoefficients')
+	return StringToEnum('InversionCostFunctionsCoefficients')[0]
 
 def InversionCostFunctionsEnum():
@@ -575,5 +637,5 @@
 	"""
 
-	return StringToEnum('InversionCostFunctions')
+	return StringToEnum('InversionCostFunctions')[0]
 
 def InversionGradientOnlyEnum():
@@ -585,5 +647,5 @@
 	"""
 
-	return StringToEnum('InversionGradientOnly')
+	return StringToEnum('InversionGradientOnly')[0]
 
 def InversionGradientScalingEnum():
@@ -595,5 +657,5 @@
 	"""
 
-	return StringToEnum('InversionGradientScaling')
+	return StringToEnum('InversionGradientScaling')[0]
 
 def InversionIscontrolEnum():
@@ -605,5 +667,5 @@
 	"""
 
-	return StringToEnum('InversionIscontrol')
+	return StringToEnum('InversionIscontrol')[0]
 
 def InversionTaoEnum():
@@ -615,5 +677,5 @@
 	"""
 
-	return StringToEnum('InversionTao')
+	return StringToEnum('InversionTao')[0]
 
 def InversionIncompleteAdjointEnum():
@@ -625,5 +687,5 @@
 	"""
 
-	return StringToEnum('InversionIncompleteAdjoint')
+	return StringToEnum('InversionIncompleteAdjoint')[0]
 
 def InversionMaxParametersEnum():
@@ -635,5 +697,5 @@
 	"""
 
-	return StringToEnum('InversionMaxParameters')
+	return StringToEnum('InversionMaxParameters')[0]
 
 def InversionMaxiterPerStepEnum():
@@ -645,5 +707,5 @@
 	"""
 
-	return StringToEnum('InversionMaxiterPerStep')
+	return StringToEnum('InversionMaxiterPerStep')[0]
 
 def InversionMinParametersEnum():
@@ -655,5 +717,5 @@
 	"""
 
-	return StringToEnum('InversionMinParameters')
+	return StringToEnum('InversionMinParameters')[0]
 
 def InversionNstepsEnum():
@@ -665,5 +727,5 @@
 	"""
 
-	return StringToEnum('InversionNsteps')
+	return StringToEnum('InversionNsteps')[0]
 
 def InversionNumControlParametersEnum():
@@ -675,5 +737,5 @@
 	"""
 
-	return StringToEnum('InversionNumControlParameters')
+	return StringToEnum('InversionNumControlParameters')[0]
 
 def InversionNumCostFunctionsEnum():
@@ -685,5 +747,5 @@
 	"""
 
-	return StringToEnum('InversionNumCostFunctions')
+	return StringToEnum('InversionNumCostFunctions')[0]
 
 def InversionStepThresholdEnum():
@@ -695,5 +757,5 @@
 	"""
 
-	return StringToEnum('InversionStepThreshold')
+	return StringToEnum('InversionStepThreshold')[0]
 
 def InversionThicknessObsEnum():
@@ -705,5 +767,5 @@
 	"""
 
-	return StringToEnum('InversionThicknessObs')
+	return StringToEnum('InversionThicknessObs')[0]
 
 def InversionVelObsEnum():
@@ -715,5 +777,5 @@
 	"""
 
-	return StringToEnum('InversionVelObs')
+	return StringToEnum('InversionVelObs')[0]
 
 def InversionVxObsEnum():
@@ -725,5 +787,5 @@
 	"""
 
-	return StringToEnum('InversionVxObs')
+	return StringToEnum('InversionVxObs')[0]
 
 def InversionVyObsEnum():
@@ -735,5 +797,5 @@
 	"""
 
-	return StringToEnum('InversionVyObs')
+	return StringToEnum('InversionVyObs')[0]
 
 def InversionVzObsEnum():
@@ -745,5 +807,5 @@
 	"""
 
-	return StringToEnum('InversionVzObs')
+	return StringToEnum('InversionVzObs')[0]
 
 def MaskElementonfloatingiceEnum():
@@ -755,5 +817,5 @@
 	"""
 
-	return StringToEnum('MaskElementonfloatingice')
+	return StringToEnum('MaskElementonfloatingice')[0]
 
 def MaskElementongroundediceEnum():
@@ -765,5 +827,5 @@
 	"""
 
-	return StringToEnum('MaskElementongroundedice')
+	return StringToEnum('MaskElementongroundedice')[0]
 
 def MaskElementonwaterEnum():
@@ -775,5 +837,5 @@
 	"""
 
-	return StringToEnum('MaskElementonwater')
+	return StringToEnum('MaskElementonwater')[0]
 
 def MaskVertexonfloatingiceEnum():
@@ -785,5 +847,5 @@
 	"""
 
-	return StringToEnum('MaskVertexonfloatingice')
+	return StringToEnum('MaskVertexonfloatingice')[0]
 
 def MaskVertexongroundediceEnum():
@@ -795,5 +857,5 @@
 	"""
 
-	return StringToEnum('MaskVertexongroundedice')
+	return StringToEnum('MaskVertexongroundedice')[0]
 
 def MaskVertexonwaterEnum():
@@ -805,5 +867,5 @@
 	"""
 
-	return StringToEnum('MaskVertexonwater')
+	return StringToEnum('MaskVertexonwater')[0]
 
 def MaterialsBetaEnum():
@@ -815,5 +877,5 @@
 	"""
 
-	return StringToEnum('MaterialsBeta')
+	return StringToEnum('MaterialsBeta')[0]
 
 def MaterialsHeatcapacityEnum():
@@ -825,5 +887,5 @@
 	"""
 
-	return StringToEnum('MaterialsHeatcapacity')
+	return StringToEnum('MaterialsHeatcapacity')[0]
 
 def MaterialsLatentheatEnum():
@@ -835,5 +897,5 @@
 	"""
 
-	return StringToEnum('MaterialsLatentheat')
+	return StringToEnum('MaterialsLatentheat')[0]
 
 def MaterialsMeltingpointEnum():
@@ -845,5 +907,5 @@
 	"""
 
-	return StringToEnum('MaterialsMeltingpoint')
+	return StringToEnum('MaterialsMeltingpoint')[0]
 
 def MaterialsMixedLayerCapacityEnum():
@@ -855,5 +917,5 @@
 	"""
 
-	return StringToEnum('MaterialsMixedLayerCapacity')
+	return StringToEnum('MaterialsMixedLayerCapacity')[0]
 
 def MaterialsRheologyBEnum():
@@ -865,5 +927,5 @@
 	"""
 
-	return StringToEnum('MaterialsRheologyB')
+	return StringToEnum('MaterialsRheologyB')[0]
 
 def MaterialsRheologyBbarEnum():
@@ -875,5 +937,5 @@
 	"""
 
-	return StringToEnum('MaterialsRheologyBbar')
+	return StringToEnum('MaterialsRheologyBbar')[0]
 
 def MaterialsRheologyLawEnum():
@@ -885,5 +947,5 @@
 	"""
 
-	return StringToEnum('MaterialsRheologyLaw')
+	return StringToEnum('MaterialsRheologyLaw')[0]
 
 def MaterialsRheologyNEnum():
@@ -895,5 +957,25 @@
 	"""
 
-	return StringToEnum('MaterialsRheologyN')
+	return StringToEnum('MaterialsRheologyN')[0]
+
+def MaterialsRheologyZEnum():
+	"""
+	MATERIALSRHEOLOGYZENUM - Enum of MaterialsRheologyZ
+
+	   Usage:
+	      macro=MaterialsRheologyZEnum()
+	"""
+
+	return StringToEnum('MaterialsRheologyZ')[0]
+
+def MaterialsRheologyZbarEnum():
+	"""
+	MATERIALSRHEOLOGYZBARENUM - Enum of MaterialsRheologyZbar
+
+	   Usage:
+	      macro=MaterialsRheologyZbarEnum()
+	"""
+
+	return StringToEnum('MaterialsRheologyZbar')[0]
 
 def MaterialsRhoIceEnum():
@@ -905,5 +987,5 @@
 	"""
 
-	return StringToEnum('MaterialsRhoIce')
+	return StringToEnum('MaterialsRhoIce')[0]
 
 def MaterialsRhoWaterEnum():
@@ -915,5 +997,5 @@
 	"""
 
-	return StringToEnum('MaterialsRhoWater')
+	return StringToEnum('MaterialsRhoWater')[0]
 
 def MaterialsRhoFreshwaterEnum():
@@ -925,5 +1007,5 @@
 	"""
 
-	return StringToEnum('MaterialsRhoFreshwater')
+	return StringToEnum('MaterialsRhoFreshwater')[0]
 
 def MaterialsMuWaterEnum():
@@ -935,5 +1017,5 @@
 	"""
 
-	return StringToEnum('MaterialsMuWater')
+	return StringToEnum('MaterialsMuWater')[0]
 
 def MaterialsThermalExchangeVelocityEnum():
@@ -945,5 +1027,5 @@
 	"""
 
-	return StringToEnum('MaterialsThermalExchangeVelocity')
+	return StringToEnum('MaterialsThermalExchangeVelocity')[0]
 
 def MaterialsThermalconductivityEnum():
@@ -955,5 +1037,5 @@
 	"""
 
-	return StringToEnum('MaterialsThermalconductivity')
+	return StringToEnum('MaterialsThermalconductivity')[0]
 
 def MeshAverageVertexConnectivityEnum():
@@ -965,5 +1047,5 @@
 	"""
 
-	return StringToEnum('MeshAverageVertexConnectivity')
+	return StringToEnum('MeshAverageVertexConnectivity')[0]
 
 def MeshDimensionEnum():
@@ -975,5 +1057,5 @@
 	"""
 
-	return StringToEnum('MeshDimension')
+	return StringToEnum('MeshDimension')[0]
 
 def MeshEdgesEnum():
@@ -985,5 +1067,5 @@
 	"""
 
-	return StringToEnum('MeshEdges')
+	return StringToEnum('MeshEdges')[0]
 
 def MeshElementconnectivityEnum():
@@ -995,5 +1077,5 @@
 	"""
 
-	return StringToEnum('MeshElementconnectivity')
+	return StringToEnum('MeshElementconnectivity')[0]
 
 def MeshElementonbedEnum():
@@ -1005,5 +1087,5 @@
 	"""
 
-	return StringToEnum('MeshElementonbed')
+	return StringToEnum('MeshElementonbed')[0]
 
 def MeshElementonsurfaceEnum():
@@ -1015,5 +1097,5 @@
 	"""
 
-	return StringToEnum('MeshElementonsurface')
+	return StringToEnum('MeshElementonsurface')[0]
 
 def MeshElements2dEnum():
@@ -1025,5 +1107,5 @@
 	"""
 
-	return StringToEnum('MeshElements2d')
+	return StringToEnum('MeshElements2d')[0]
 
 def MeshElementsEnum():
@@ -1035,5 +1117,5 @@
 	"""
 
-	return StringToEnum('MeshElements')
+	return StringToEnum('MeshElements')[0]
 
 def MeshLowerelementsEnum():
@@ -1045,5 +1127,5 @@
 	"""
 
-	return StringToEnum('MeshLowerelements')
+	return StringToEnum('MeshLowerelements')[0]
 
 def MeshNumberofedgesEnum():
@@ -1055,5 +1137,5 @@
 	"""
 
-	return StringToEnum('MeshNumberofedges')
+	return StringToEnum('MeshNumberofedges')[0]
 
 def MeshNumberofelements2dEnum():
@@ -1065,5 +1147,5 @@
 	"""
 
-	return StringToEnum('MeshNumberofelements2d')
+	return StringToEnum('MeshNumberofelements2d')[0]
 
 def MeshNumberofelementsEnum():
@@ -1075,5 +1157,5 @@
 	"""
 
-	return StringToEnum('MeshNumberofelements')
+	return StringToEnum('MeshNumberofelements')[0]
 
 def MeshNumberoflayersEnum():
@@ -1085,5 +1167,5 @@
 	"""
 
-	return StringToEnum('MeshNumberoflayers')
+	return StringToEnum('MeshNumberoflayers')[0]
 
 def MeshNumberofvertices2dEnum():
@@ -1095,5 +1177,5 @@
 	"""
 
-	return StringToEnum('MeshNumberofvertices2d')
+	return StringToEnum('MeshNumberofvertices2d')[0]
 
 def MeshNumberofverticesEnum():
@@ -1105,5 +1187,5 @@
 	"""
 
-	return StringToEnum('MeshNumberofvertices')
+	return StringToEnum('MeshNumberofvertices')[0]
 
 def MeshUpperelementsEnum():
@@ -1115,5 +1197,5 @@
 	"""
 
-	return StringToEnum('MeshUpperelements')
+	return StringToEnum('MeshUpperelements')[0]
 
 def MeshVertexonbedEnum():
@@ -1125,5 +1207,5 @@
 	"""
 
-	return StringToEnum('MeshVertexonbed')
+	return StringToEnum('MeshVertexonbed')[0]
 
 def MeshVertexonsurfaceEnum():
@@ -1135,5 +1217,5 @@
 	"""
 
-	return StringToEnum('MeshVertexonsurface')
+	return StringToEnum('MeshVertexonsurface')[0]
 
 def MeshXEnum():
@@ -1145,5 +1227,5 @@
 	"""
 
-	return StringToEnum('MeshX')
+	return StringToEnum('MeshX')[0]
 
 def MeshYEnum():
@@ -1155,5 +1237,5 @@
 	"""
 
-	return StringToEnum('MeshY')
+	return StringToEnum('MeshY')[0]
 
 def MeshZEnum():
@@ -1165,5 +1247,5 @@
 	"""
 
-	return StringToEnum('MeshZ')
+	return StringToEnum('MeshZ')[0]
 
 def MiscellaneousNameEnum():
@@ -1175,5 +1257,5 @@
 	"""
 
-	return StringToEnum('MiscellaneousName')
+	return StringToEnum('MiscellaneousName')[0]
 
 def PrognosticHydrostaticAdjustmentEnum():
@@ -1185,5 +1267,5 @@
 	"""
 
-	return StringToEnum('PrognosticHydrostaticAdjustment')
+	return StringToEnum('PrognosticHydrostaticAdjustment')[0]
 
 def PrognosticMinThicknessEnum():
@@ -1195,5 +1277,5 @@
 	"""
 
-	return StringToEnum('PrognosticMinThickness')
+	return StringToEnum('PrognosticMinThickness')[0]
 
 def PrognosticPenaltyFactorEnum():
@@ -1205,5 +1287,5 @@
 	"""
 
-	return StringToEnum('PrognosticPenaltyFactor')
+	return StringToEnum('PrognosticPenaltyFactor')[0]
 
 def PrognosticSpcthicknessEnum():
@@ -1215,5 +1297,5 @@
 	"""
 
-	return StringToEnum('PrognosticSpcthickness')
+	return StringToEnum('PrognosticSpcthickness')[0]
 
 def PrognosticStabilizationEnum():
@@ -1225,5 +1307,5 @@
 	"""
 
-	return StringToEnum('PrognosticStabilization')
+	return StringToEnum('PrognosticStabilization')[0]
 
 def PrognosticVertexPairingEnum():
@@ -1235,5 +1317,5 @@
 	"""
 
-	return StringToEnum('PrognosticVertexPairing')
+	return StringToEnum('PrognosticVertexPairing')[0]
 
 def QmuIsdakotaEnum():
@@ -1245,5 +1327,5 @@
 	"""
 
-	return StringToEnum('QmuIsdakota')
+	return StringToEnum('QmuIsdakota')[0]
 
 def QmuMassFluxSegmentsEnum():
@@ -1255,5 +1337,5 @@
 	"""
 
-	return StringToEnum('QmuMassFluxSegments')
+	return StringToEnum('QmuMassFluxSegments')[0]
 
 def QmuNumberofpartitionsEnum():
@@ -1265,5 +1347,5 @@
 	"""
 
-	return StringToEnum('QmuNumberofpartitions')
+	return StringToEnum('QmuNumberofpartitions')[0]
 
 def QmuNumberofresponsesEnum():
@@ -1275,5 +1357,5 @@
 	"""
 
-	return StringToEnum('QmuNumberofresponses')
+	return StringToEnum('QmuNumberofresponses')[0]
 
 def QmuPartitionEnum():
@@ -1285,5 +1367,5 @@
 	"""
 
-	return StringToEnum('QmuPartition')
+	return StringToEnum('QmuPartition')[0]
 
 def QmuResponsedescriptorsEnum():
@@ -1295,5 +1377,5 @@
 	"""
 
-	return StringToEnum('QmuResponsedescriptors')
+	return StringToEnum('QmuResponsedescriptors')[0]
 
 def QmuVariabledescriptorsEnum():
@@ -1305,5 +1387,5 @@
 	"""
 
-	return StringToEnum('QmuVariabledescriptors')
+	return StringToEnum('QmuVariabledescriptors')[0]
 
 def RiftsNumriftsEnum():
@@ -1315,5 +1397,5 @@
 	"""
 
-	return StringToEnum('RiftsNumrifts')
+	return StringToEnum('RiftsNumrifts')[0]
 
 def RiftsRiftstructEnum():
@@ -1325,5 +1407,5 @@
 	"""
 
-	return StringToEnum('RiftsRiftstruct')
+	return StringToEnum('RiftsRiftstruct')[0]
 
 def SettingsIoGatherEnum():
@@ -1335,5 +1417,5 @@
 	"""
 
-	return StringToEnum('SettingsIoGather')
+	return StringToEnum('SettingsIoGather')[0]
 
 def SettingsLowmemEnum():
@@ -1345,5 +1427,5 @@
 	"""
 
-	return StringToEnum('SettingsLowmem')
+	return StringToEnum('SettingsLowmem')[0]
 
 def SettingsOutputFrequencyEnum():
@@ -1355,5 +1437,5 @@
 	"""
 
-	return StringToEnum('SettingsOutputFrequency')
+	return StringToEnum('SettingsOutputFrequency')[0]
 
 def SettingsResultsAsPatchesEnum():
@@ -1365,5 +1447,5 @@
 	"""
 
-	return StringToEnum('SettingsResultsAsPatches')
+	return StringToEnum('SettingsResultsAsPatches')[0]
 
 def SettingsWaitonlockEnum():
@@ -1375,5 +1457,65 @@
 	"""
 
-	return StringToEnum('SettingsWaitonlock')
+	return StringToEnum('SettingsWaitonlock')[0]
+
+def SurfaceforcingsDelta18oEnum():
+	"""
+	SURFACEFORCINGSDELTA18OENUM - Enum of SurfaceforcingsDelta18o
+
+	   Usage:
+	      macro=SurfaceforcingsDelta18oEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsDelta18o')[0]
+
+def SurfaceforcingsDelta18oSurfaceEnum():
+	"""
+	SURFACEFORCINGSDELTA18OSURFACEENUM - Enum of SurfaceforcingsDelta18oSurface
+
+	   Usage:
+	      macro=SurfaceforcingsDelta18oSurfaceEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsDelta18oSurface')[0]
+
+def SurfaceforcingsIsdelta18oEnum():
+	"""
+	SURFACEFORCINGSISDELTA18OENUM - Enum of SurfaceforcingsIsdelta18o
+
+	   Usage:
+	      macro=SurfaceforcingsIsdelta18oEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsIsdelta18o')[0]
+
+def SurfaceforcingsPrecipitationsPresentdayEnum():
+	"""
+	SURFACEFORCINGSPRECIPITATIONSPRESENTDAYENUM - Enum of SurfaceforcingsPrecipitationsPresentday
+
+	   Usage:
+	      macro=SurfaceforcingsPrecipitationsPresentdayEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsPrecipitationsPresentday')[0]
+
+def SurfaceforcingsTemperaturesPresentdayEnum():
+	"""
+	SURFACEFORCINGSTEMPERATURESPRESENTDAYENUM - Enum of SurfaceforcingsTemperaturesPresentday
+
+	   Usage:
+	      macro=SurfaceforcingsTemperaturesPresentdayEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsTemperaturesPresentday')[0]
+
+def SurfaceforcingsTemperaturesLgmEnum():
+	"""
+	SURFACEFORCINGSTEMPERATURESLGMENUM - Enum of SurfaceforcingsTemperaturesLgm
+
+	   Usage:
+	      macro=SurfaceforcingsTemperaturesLgmEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsTemperaturesLgm')[0]
 
 def DebugProfilingEnum():
@@ -1385,5 +1527,5 @@
 	"""
 
-	return StringToEnum('DebugProfiling')
+	return StringToEnum('DebugProfiling')[0]
 
 def ProfilingCurrentMemEnum():
@@ -1395,5 +1537,5 @@
 	"""
 
-	return StringToEnum('ProfilingCurrentMem')
+	return StringToEnum('ProfilingCurrentMem')[0]
 
 def ProfilingCurrentFlopsEnum():
@@ -1405,5 +1547,5 @@
 	"""
 
-	return StringToEnum('ProfilingCurrentFlops')
+	return StringToEnum('ProfilingCurrentFlops')[0]
 
 def ProfilingSolutionTimeEnum():
@@ -1415,5 +1557,5 @@
 	"""
 
-	return StringToEnum('ProfilingSolutionTime')
+	return StringToEnum('ProfilingSolutionTime')[0]
 
 def MaxIterationConvergenceFlagEnum():
@@ -1425,5 +1567,5 @@
 	"""
 
-	return StringToEnum('MaxIterationConvergenceFlag')
+	return StringToEnum('MaxIterationConvergenceFlag')[0]
 
 def SteadystateMaxiterEnum():
@@ -1435,5 +1577,5 @@
 	"""
 
-	return StringToEnum('SteadystateMaxiter')
+	return StringToEnum('SteadystateMaxiter')[0]
 
 def SteadystateNumRequestedOutputsEnum():
@@ -1445,5 +1587,5 @@
 	"""
 
-	return StringToEnum('SteadystateNumRequestedOutputs')
+	return StringToEnum('SteadystateNumRequestedOutputs')[0]
 
 def SteadystateReltolEnum():
@@ -1455,5 +1597,5 @@
 	"""
 
-	return StringToEnum('SteadystateReltol')
+	return StringToEnum('SteadystateReltol')[0]
 
 def SteadystateRequestedOutputsEnum():
@@ -1465,5 +1607,5 @@
 	"""
 
-	return StringToEnum('SteadystateRequestedOutputs')
+	return StringToEnum('SteadystateRequestedOutputs')[0]
 
 def SurfaceEnum():
@@ -1475,5 +1617,5 @@
 	"""
 
-	return StringToEnum('Surface')
+	return StringToEnum('Surface')[0]
 
 def SurfaceforcingsPrecipitationEnum():
@@ -1485,5 +1627,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsPrecipitation')
+	return StringToEnum('SurfaceforcingsPrecipitation')[0]
 
 def SurfaceforcingsMassBalanceEnum():
@@ -1495,5 +1637,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsMassBalance')
+	return StringToEnum('SurfaceforcingsMassBalance')[0]
 
 def SurfaceforcingsIspddEnum():
@@ -1505,5 +1647,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsIspdd')
+	return StringToEnum('SurfaceforcingsIspdd')[0]
 
 def SurfaceforcingsIssmbgradientsEnum():
@@ -1515,5 +1657,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsIssmbgradients')
+	return StringToEnum('SurfaceforcingsIssmbgradients')[0]
 
 def SurfaceforcingsMonthlytemperaturesEnum():
@@ -1525,5 +1667,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsMonthlytemperatures')
+	return StringToEnum('SurfaceforcingsMonthlytemperatures')[0]
 
 def SurfaceforcingsHcEnum():
@@ -1535,5 +1677,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsHc')
+	return StringToEnum('SurfaceforcingsHc')[0]
 
 def SurfaceforcingsSmbPosMaxEnum():
@@ -1545,5 +1687,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsSmbPosMax')
+	return StringToEnum('SurfaceforcingsSmbPosMax')[0]
 
 def SurfaceforcingsSmbPosMinEnum():
@@ -1555,5 +1697,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsSmbPosMin')
+	return StringToEnum('SurfaceforcingsSmbPosMin')[0]
 
 def SurfaceforcingsAPosEnum():
@@ -1565,5 +1707,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsAPos')
+	return StringToEnum('SurfaceforcingsAPos')[0]
 
 def SurfaceforcingsBPosEnum():
@@ -1575,5 +1717,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsBPos')
+	return StringToEnum('SurfaceforcingsBPos')[0]
 
 def SurfaceforcingsANegEnum():
@@ -1585,5 +1727,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsANeg')
+	return StringToEnum('SurfaceforcingsANeg')[0]
 
 def SurfaceforcingsBNegEnum():
@@ -1595,5 +1737,5 @@
 	"""
 
-	return StringToEnum('SurfaceforcingsBNeg')
+	return StringToEnum('SurfaceforcingsBNeg')[0]
 
 def ThermalMaxiterEnum():
@@ -1605,5 +1747,5 @@
 	"""
 
-	return StringToEnum('ThermalMaxiter')
+	return StringToEnum('ThermalMaxiter')[0]
 
 def ThermalPenaltyFactorEnum():
@@ -1615,5 +1757,5 @@
 	"""
 
-	return StringToEnum('ThermalPenaltyFactor')
+	return StringToEnum('ThermalPenaltyFactor')[0]
 
 def ThermalPenaltyLockEnum():
@@ -1625,5 +1767,5 @@
 	"""
 
-	return StringToEnum('ThermalPenaltyLock')
+	return StringToEnum('ThermalPenaltyLock')[0]
 
 def ThermalPenaltyThresholdEnum():
@@ -1635,5 +1777,5 @@
 	"""
 
-	return StringToEnum('ThermalPenaltyThreshold')
+	return StringToEnum('ThermalPenaltyThreshold')[0]
 
 def ThermalSpctemperatureEnum():
@@ -1645,5 +1787,5 @@
 	"""
 
-	return StringToEnum('ThermalSpctemperature')
+	return StringToEnum('ThermalSpctemperature')[0]
 
 def ThermalStabilizationEnum():
@@ -1655,5 +1797,5 @@
 	"""
 
-	return StringToEnum('ThermalStabilization')
+	return StringToEnum('ThermalStabilization')[0]
 
 def ThermalIsenthalpyEnum():
@@ -1665,5 +1807,5 @@
 	"""
 
-	return StringToEnum('ThermalIsenthalpy')
+	return StringToEnum('ThermalIsenthalpy')[0]
 
 def ThicknessEnum():
@@ -1675,5 +1817,5 @@
 	"""
 
-	return StringToEnum('Thickness')
+	return StringToEnum('Thickness')[0]
 
 def TimesteppingStartTimeEnum():
@@ -1685,5 +1827,5 @@
 	"""
 
-	return StringToEnum('TimesteppingStartTime')
+	return StringToEnum('TimesteppingStartTime')[0]
 
 def TimesteppingFinalTimeEnum():
@@ -1695,5 +1837,5 @@
 	"""
 
-	return StringToEnum('TimesteppingFinalTime')
+	return StringToEnum('TimesteppingFinalTime')[0]
 
 def TimesteppingCflCoefficientEnum():
@@ -1705,5 +1847,5 @@
 	"""
 
-	return StringToEnum('TimesteppingCflCoefficient')
+	return StringToEnum('TimesteppingCflCoefficient')[0]
 
 def TimesteppingTimeAdaptEnum():
@@ -1715,5 +1857,5 @@
 	"""
 
-	return StringToEnum('TimesteppingTimeAdapt')
+	return StringToEnum('TimesteppingTimeAdapt')[0]
 
 def TimesteppingTimeStepEnum():
@@ -1725,5 +1867,5 @@
 	"""
 
-	return StringToEnum('TimesteppingTimeStep')
+	return StringToEnum('TimesteppingTimeStep')[0]
 
 def TransientIsdiagnosticEnum():
@@ -1735,5 +1877,5 @@
 	"""
 
-	return StringToEnum('TransientIsdiagnostic')
+	return StringToEnum('TransientIsdiagnostic')[0]
 
 def TransientIsgroundinglineEnum():
@@ -1745,5 +1887,5 @@
 	"""
 
-	return StringToEnum('TransientIsgroundingline')
+	return StringToEnum('TransientIsgroundingline')[0]
 
 def TransientIsprognosticEnum():
@@ -1755,5 +1897,5 @@
 	"""
 
-	return StringToEnum('TransientIsprognostic')
+	return StringToEnum('TransientIsprognostic')[0]
 
 def TransientIsthermalEnum():
@@ -1765,5 +1907,5 @@
 	"""
 
-	return StringToEnum('TransientIsthermal')
+	return StringToEnum('TransientIsthermal')[0]
 
 def TransientNumRequestedOutputsEnum():
@@ -1775,5 +1917,5 @@
 	"""
 
-	return StringToEnum('TransientNumRequestedOutputs')
+	return StringToEnum('TransientNumRequestedOutputs')[0]
 
 def TransientRequestedOutputsEnum():
@@ -1785,5 +1927,5 @@
 	"""
 
-	return StringToEnum('TransientRequestedOutputs')
+	return StringToEnum('TransientRequestedOutputs')[0]
 
 def SolutionTypeEnum():
@@ -1795,5 +1937,5 @@
 	"""
 
-	return StringToEnum('SolutionType')
+	return StringToEnum('SolutionType')[0]
 
 def AnalysisTypeEnum():
@@ -1805,5 +1947,5 @@
 	"""
 
-	return StringToEnum('AnalysisType')
+	return StringToEnum('AnalysisType')[0]
 
 def ConfigurationTypeEnum():
@@ -1815,5 +1957,5 @@
 	"""
 
-	return StringToEnum('ConfigurationType')
+	return StringToEnum('ConfigurationType')[0]
 
 def AdjointBalancethicknessAnalysisEnum():
@@ -1825,5 +1967,5 @@
 	"""
 
-	return StringToEnum('AdjointBalancethicknessAnalysis')
+	return StringToEnum('AdjointBalancethicknessAnalysis')[0]
 
 def AdjointHorizAnalysisEnum():
@@ -1835,5 +1977,5 @@
 	"""
 
-	return StringToEnum('AdjointHorizAnalysis')
+	return StringToEnum('AdjointHorizAnalysis')[0]
 
 def AdjointSolutionEnum():
@@ -1845,5 +1987,5 @@
 	"""
 
-	return StringToEnum('AdjointSolution')
+	return StringToEnum('AdjointSolution')[0]
 
 def AnalysisCounterEnum():
@@ -1855,5 +1997,5 @@
 	"""
 
-	return StringToEnum('AnalysisCounter')
+	return StringToEnum('AnalysisCounter')[0]
 
 def BalancethicknessAnalysisEnum():
@@ -1865,5 +2007,5 @@
 	"""
 
-	return StringToEnum('BalancethicknessAnalysis')
+	return StringToEnum('BalancethicknessAnalysis')[0]
 
 def BalancethicknessSolutionEnum():
@@ -1875,5 +2017,5 @@
 	"""
 
-	return StringToEnum('BalancethicknessSolution')
+	return StringToEnum('BalancethicknessSolution')[0]
 
 def BedSlopeAnalysisEnum():
@@ -1885,5 +2027,5 @@
 	"""
 
-	return StringToEnum('BedSlopeAnalysis')
+	return StringToEnum('BedSlopeAnalysis')[0]
 
 def BedSlopeSolutionEnum():
@@ -1895,5 +2037,5 @@
 	"""
 
-	return StringToEnum('BedSlopeSolution')
+	return StringToEnum('BedSlopeSolution')[0]
 
 def BedSlopeXAnalysisEnum():
@@ -1905,5 +2047,5 @@
 	"""
 
-	return StringToEnum('BedSlopeXAnalysis')
+	return StringToEnum('BedSlopeXAnalysis')[0]
 
 def BedSlopeYAnalysisEnum():
@@ -1915,5 +2057,5 @@
 	"""
 
-	return StringToEnum('BedSlopeYAnalysis')
+	return StringToEnum('BedSlopeYAnalysis')[0]
 
 def DiagnosticHorizAnalysisEnum():
@@ -1925,5 +2067,5 @@
 	"""
 
-	return StringToEnum('DiagnosticHorizAnalysis')
+	return StringToEnum('DiagnosticHorizAnalysis')[0]
 
 def DiagnosticHutterAnalysisEnum():
@@ -1935,5 +2077,5 @@
 	"""
 
-	return StringToEnum('DiagnosticHutterAnalysis')
+	return StringToEnum('DiagnosticHutterAnalysis')[0]
 
 def DiagnosticSolutionEnum():
@@ -1945,5 +2087,5 @@
 	"""
 
-	return StringToEnum('DiagnosticSolution')
+	return StringToEnum('DiagnosticSolution')[0]
 
 def DiagnosticVertAnalysisEnum():
@@ -1955,5 +2097,5 @@
 	"""
 
-	return StringToEnum('DiagnosticVertAnalysis')
+	return StringToEnum('DiagnosticVertAnalysis')[0]
 
 def EnthalpyAnalysisEnum():
@@ -1965,5 +2107,5 @@
 	"""
 
-	return StringToEnum('EnthalpyAnalysis')
+	return StringToEnum('EnthalpyAnalysis')[0]
 
 def EnthalpySolutionEnum():
@@ -1975,5 +2117,5 @@
 	"""
 
-	return StringToEnum('EnthalpySolution')
+	return StringToEnum('EnthalpySolution')[0]
 
 def FlaimAnalysisEnum():
@@ -1985,5 +2127,5 @@
 	"""
 
-	return StringToEnum('FlaimAnalysis')
+	return StringToEnum('FlaimAnalysis')[0]
 
 def FlaimSolutionEnum():
@@ -1995,5 +2137,5 @@
 	"""
 
-	return StringToEnum('FlaimSolution')
+	return StringToEnum('FlaimSolution')[0]
 
 def HydrologyAnalysisEnum():
@@ -2005,5 +2147,5 @@
 	"""
 
-	return StringToEnum('HydrologyAnalysis')
+	return StringToEnum('HydrologyAnalysis')[0]
 
 def HydrologySolutionEnum():
@@ -2015,5 +2157,5 @@
 	"""
 
-	return StringToEnum('HydrologySolution')
+	return StringToEnum('HydrologySolution')[0]
 
 def MeltingAnalysisEnum():
@@ -2025,5 +2167,5 @@
 	"""
 
-	return StringToEnum('MeltingAnalysis')
+	return StringToEnum('MeltingAnalysis')[0]
 
 def NoneAnalysisEnum():
@@ -2035,5 +2177,5 @@
 	"""
 
-	return StringToEnum('NoneAnalysis')
+	return StringToEnum('NoneAnalysis')[0]
 
 def PrognosticAnalysisEnum():
@@ -2045,5 +2187,5 @@
 	"""
 
-	return StringToEnum('PrognosticAnalysis')
+	return StringToEnum('PrognosticAnalysis')[0]
 
 def PrognosticSolutionEnum():
@@ -2055,5 +2197,5 @@
 	"""
 
-	return StringToEnum('PrognosticSolution')
+	return StringToEnum('PrognosticSolution')[0]
 
 def SteadystateSolutionEnum():
@@ -2065,5 +2207,5 @@
 	"""
 
-	return StringToEnum('SteadystateSolution')
+	return StringToEnum('SteadystateSolution')[0]
 
 def SurfaceSlopeAnalysisEnum():
@@ -2075,5 +2217,5 @@
 	"""
 
-	return StringToEnum('SurfaceSlopeAnalysis')
+	return StringToEnum('SurfaceSlopeAnalysis')[0]
 
 def SurfaceSlopeSolutionEnum():
@@ -2085,5 +2227,5 @@
 	"""
 
-	return StringToEnum('SurfaceSlopeSolution')
+	return StringToEnum('SurfaceSlopeSolution')[0]
 
 def SurfaceSlopeXAnalysisEnum():
@@ -2095,5 +2237,5 @@
 	"""
 
-	return StringToEnum('SurfaceSlopeXAnalysis')
+	return StringToEnum('SurfaceSlopeXAnalysis')[0]
 
 def SurfaceSlopeYAnalysisEnum():
@@ -2105,5 +2247,5 @@
 	"""
 
-	return StringToEnum('SurfaceSlopeYAnalysis')
+	return StringToEnum('SurfaceSlopeYAnalysis')[0]
 
 def ThermalAnalysisEnum():
@@ -2115,5 +2257,5 @@
 	"""
 
-	return StringToEnum('ThermalAnalysis')
+	return StringToEnum('ThermalAnalysis')[0]
 
 def ThermalSolutionEnum():
@@ -2125,5 +2267,5 @@
 	"""
 
-	return StringToEnum('ThermalSolution')
+	return StringToEnum('ThermalSolution')[0]
 
 def TransientSolutionEnum():
@@ -2135,5 +2277,5 @@
 	"""
 
-	return StringToEnum('TransientSolution')
+	return StringToEnum('TransientSolution')[0]
 
 def ApproximationEnum():
@@ -2145,5 +2287,15 @@
 	"""
 
-	return StringToEnum('Approximation')
+	return StringToEnum('Approximation')[0]
+
+def NoneApproximationEnum():
+	"""
+	NONEAPPROXIMATIONENUM - Enum of NoneApproximation
+
+	   Usage:
+	      macro=NoneApproximationEnum()
+	"""
+
+	return StringToEnum('NoneApproximation')[0]
 
 def HutterApproximationEnum():
@@ -2155,5 +2307,5 @@
 	"""
 
-	return StringToEnum('HutterApproximation')
+	return StringToEnum('HutterApproximation')[0]
 
 def MacAyealApproximationEnum():
@@ -2165,5 +2317,5 @@
 	"""
 
-	return StringToEnum('MacAyealApproximation')
+	return StringToEnum('MacAyealApproximation')[0]
 
 def MacAyealPattynApproximationEnum():
@@ -2175,5 +2327,5 @@
 	"""
 
-	return StringToEnum('MacAyealPattynApproximation')
+	return StringToEnum('MacAyealPattynApproximation')[0]
 
 def MacAyealStokesApproximationEnum():
@@ -2185,15 +2337,15 @@
 	"""
 
-	return StringToEnum('MacAyealStokesApproximation')
-
-def NoneApproximationEnum():
-	"""
-	NONEAPPROXIMATIONENUM - Enum of NoneApproximation
-
-	   Usage:
-	      macro=NoneApproximationEnum()
-	"""
-
-	return StringToEnum('NoneApproximation')
+	return StringToEnum('MacAyealStokesApproximation')[0]
+
+def L1L2ApproximationEnum():
+	"""
+	L1L2APPROXIMATIONENUM - Enum of L1L2Approximation
+
+	   Usage:
+	      macro=L1L2ApproximationEnum()
+	"""
+
+	return StringToEnum('L1L2Approximation')[0]
 
 def PattynApproximationEnum():
@@ -2205,5 +2357,5 @@
 	"""
 
-	return StringToEnum('PattynApproximation')
+	return StringToEnum('PattynApproximation')[0]
 
 def PattynStokesApproximationEnum():
@@ -2215,5 +2367,5 @@
 	"""
 
-	return StringToEnum('PattynStokesApproximation')
+	return StringToEnum('PattynStokesApproximation')[0]
 
 def StokesApproximationEnum():
@@ -2225,5 +2377,5 @@
 	"""
 
-	return StringToEnum('StokesApproximation')
+	return StringToEnum('StokesApproximation')[0]
 
 def ConstraintsEnum():
@@ -2235,5 +2387,5 @@
 	"""
 
-	return StringToEnum('Constraints')
+	return StringToEnum('Constraints')[0]
 
 def LoadsEnum():
@@ -2245,5 +2397,5 @@
 	"""
 
-	return StringToEnum('Loads')
+	return StringToEnum('Loads')[0]
 
 def MaterialsEnum():
@@ -2255,5 +2407,5 @@
 	"""
 
-	return StringToEnum('Materials')
+	return StringToEnum('Materials')[0]
 
 def NodesEnum():
@@ -2265,5 +2417,5 @@
 	"""
 
-	return StringToEnum('Nodes')
+	return StringToEnum('Nodes')[0]
 
 def ParametersEnum():
@@ -2275,5 +2427,5 @@
 	"""
 
-	return StringToEnum('Parameters')
+	return StringToEnum('Parameters')[0]
 
 def VerticesEnum():
@@ -2285,5 +2437,5 @@
 	"""
 
-	return StringToEnum('Vertices')
+	return StringToEnum('Vertices')[0]
 
 def ResultsEnum():
@@ -2295,5 +2447,25 @@
 	"""
 
-	return StringToEnum('Results')
+	return StringToEnum('Results')[0]
+
+def GenericParamEnum():
+	"""
+	GENERICPARAMENUM - Enum of GenericParam
+
+	   Usage:
+	      macro=GenericParamEnum()
+	"""
+
+	return StringToEnum('GenericParam')[0]
+
+def AdolcParamEnum():
+	"""
+	ADOLCPARAMENUM - Enum of AdolcParam
+
+	   Usage:
+	      macro=AdolcParamEnum()
+	"""
+
+	return StringToEnum('AdolcParam')[0]
 
 def BoolInputEnum():
@@ -2305,5 +2477,5 @@
 	"""
 
-	return StringToEnum('BoolInput')
+	return StringToEnum('BoolInput')[0]
 
 def BoolParamEnum():
@@ -2315,5 +2487,5 @@
 	"""
 
-	return StringToEnum('BoolParam')
+	return StringToEnum('BoolParam')[0]
 
 def ContourEnum():
@@ -2325,5 +2497,5 @@
 	"""
 
-	return StringToEnum('Contour')
+	return StringToEnum('Contour')[0]
 
 def ControlInputEnum():
@@ -2335,5 +2507,5 @@
 	"""
 
-	return StringToEnum('ControlInput')
+	return StringToEnum('ControlInput')[0]
 
 def DatasetInputEnum():
@@ -2345,5 +2517,5 @@
 	"""
 
-	return StringToEnum('DatasetInput')
+	return StringToEnum('DatasetInput')[0]
 
 def DofIndexingEnum():
@@ -2355,5 +2527,5 @@
 	"""
 
-	return StringToEnum('DofIndexing')
+	return StringToEnum('DofIndexing')[0]
 
 def DoubleInputEnum():
@@ -2365,5 +2537,5 @@
 	"""
 
-	return StringToEnum('DoubleInput')
+	return StringToEnum('DoubleInput')[0]
 
 def DoubleMatArrayParamEnum():
@@ -2375,5 +2547,5 @@
 	"""
 
-	return StringToEnum('DoubleMatArrayParam')
+	return StringToEnum('DoubleMatArrayParam')[0]
 
 def DoubleMatParamEnum():
@@ -2385,5 +2557,5 @@
 	"""
 
-	return StringToEnum('DoubleMatParam')
+	return StringToEnum('DoubleMatParam')[0]
 
 def DoubleParamEnum():
@@ -2395,5 +2567,5 @@
 	"""
 
-	return StringToEnum('DoubleParam')
+	return StringToEnum('DoubleParam')[0]
 
 def DoubleVecParamEnum():
@@ -2405,5 +2577,5 @@
 	"""
 
-	return StringToEnum('DoubleVecParam')
+	return StringToEnum('DoubleVecParam')[0]
 
 def ElementEnum():
@@ -2415,5 +2587,5 @@
 	"""
 
-	return StringToEnum('Element')
+	return StringToEnum('Element')[0]
 
 def ElementResultEnum():
@@ -2425,5 +2597,5 @@
 	"""
 
-	return StringToEnum('ElementResult')
+	return StringToEnum('ElementResult')[0]
 
 def ExternalResultEnum():
@@ -2435,5 +2607,5 @@
 	"""
 
-	return StringToEnum('ExternalResult')
+	return StringToEnum('ExternalResult')[0]
 
 def FileParamEnum():
@@ -2445,5 +2617,5 @@
 	"""
 
-	return StringToEnum('FileParam')
+	return StringToEnum('FileParam')[0]
 
 def HookEnum():
@@ -2455,5 +2627,5 @@
 	"""
 
-	return StringToEnum('Hook')
+	return StringToEnum('Hook')[0]
 
 def IcefrontEnum():
@@ -2465,5 +2637,5 @@
 	"""
 
-	return StringToEnum('Icefront')
+	return StringToEnum('Icefront')[0]
 
 def InputEnum():
@@ -2475,5 +2647,5 @@
 	"""
 
-	return StringToEnum('Input')
+	return StringToEnum('Input')[0]
 
 def IntInputEnum():
@@ -2485,5 +2657,5 @@
 	"""
 
-	return StringToEnum('IntInput')
+	return StringToEnum('IntInput')[0]
 
 def IntParamEnum():
@@ -2495,5 +2667,5 @@
 	"""
 
-	return StringToEnum('IntParam')
+	return StringToEnum('IntParam')[0]
 
 def IntVecParamEnum():
@@ -2505,5 +2677,15 @@
 	"""
 
-	return StringToEnum('IntVecParam')
+	return StringToEnum('IntVecParam')[0]
+
+def TransientParamEnum():
+	"""
+	TRANSIENTPARAMENUM - Enum of TransientParam
+
+	   Usage:
+	      macro=TransientParamEnum()
+	"""
+
+	return StringToEnum('TransientParam')[0]
 
 def MacAyeal2dIceFrontEnum():
@@ -2515,5 +2697,5 @@
 	"""
 
-	return StringToEnum('MacAyeal2dIceFront')
+	return StringToEnum('MacAyeal2dIceFront')[0]
 
 def MacAyeal3dIceFrontEnum():
@@ -2525,5 +2707,5 @@
 	"""
 
-	return StringToEnum('MacAyeal3dIceFront')
+	return StringToEnum('MacAyeal3dIceFront')[0]
 
 def MaticeEnum():
@@ -2535,5 +2717,15 @@
 	"""
 
-	return StringToEnum('Matice')
+	return StringToEnum('Matice')[0]
+
+def MatdamageiceEnum():
+	"""
+	MATDAMAGEICEENUM - Enum of Matdamageice
+
+	   Usage:
+	      macro=MatdamageiceEnum()
+	"""
+
+	return StringToEnum('Matdamageice')[0]
 
 def MatparEnum():
@@ -2545,5 +2737,5 @@
 	"""
 
-	return StringToEnum('Matpar')
+	return StringToEnum('Matpar')[0]
 
 def NodeEnum():
@@ -2555,5 +2747,5 @@
 	"""
 
-	return StringToEnum('Node')
+	return StringToEnum('Node')[0]
 
 def NumericalfluxEnum():
@@ -2565,5 +2757,5 @@
 	"""
 
-	return StringToEnum('Numericalflux')
+	return StringToEnum('Numericalflux')[0]
 
 def ParamEnum():
@@ -2575,5 +2767,15 @@
 	"""
 
-	return StringToEnum('Param')
+	return StringToEnum('Param')[0]
+
+def L1L2IceFrontEnum():
+	"""
+	L1L2ICEFRONTENUM - Enum of L1L2IceFront
+
+	   Usage:
+	      macro=L1L2IceFrontEnum()
+	"""
+
+	return StringToEnum('L1L2IceFront')[0]
 
 def PattynIceFrontEnum():
@@ -2585,5 +2787,5 @@
 	"""
 
-	return StringToEnum('PattynIceFront')
+	return StringToEnum('PattynIceFront')[0]
 
 def PengridEnum():
@@ -2595,5 +2797,5 @@
 	"""
 
-	return StringToEnum('Pengrid')
+	return StringToEnum('Pengrid')[0]
 
 def PenpairEnum():
@@ -2605,5 +2807,5 @@
 	"""
 
-	return StringToEnum('Penpair')
+	return StringToEnum('Penpair')[0]
 
 def PentaEnum():
@@ -2615,5 +2817,5 @@
 	"""
 
-	return StringToEnum('Penta')
+	return StringToEnum('Penta')[0]
 
 def PentaP1InputEnum():
@@ -2625,5 +2827,5 @@
 	"""
 
-	return StringToEnum('PentaP1Input')
+	return StringToEnum('PentaP1Input')[0]
 
 def MatrixParamEnum():
@@ -2635,5 +2837,5 @@
 	"""
 
-	return StringToEnum('MatrixParam')
+	return StringToEnum('MatrixParam')[0]
 
 def VectorParamEnum():
@@ -2645,5 +2847,5 @@
 	"""
 
-	return StringToEnum('VectorParam')
+	return StringToEnum('VectorParam')[0]
 
 def RiftfrontEnum():
@@ -2655,5 +2857,5 @@
 	"""
 
-	return StringToEnum('Riftfront')
+	return StringToEnum('Riftfront')[0]
 
 def SegmentEnum():
@@ -2665,5 +2867,5 @@
 	"""
 
-	return StringToEnum('Segment')
+	return StringToEnum('Segment')[0]
 
 def SegmentRiftfrontEnum():
@@ -2675,5 +2877,5 @@
 	"""
 
-	return StringToEnum('SegmentRiftfront')
+	return StringToEnum('SegmentRiftfront')[0]
 
 def SpcDynamicEnum():
@@ -2685,5 +2887,5 @@
 	"""
 
-	return StringToEnum('SpcDynamic')
+	return StringToEnum('SpcDynamic')[0]
 
 def SpcStaticEnum():
@@ -2695,5 +2897,5 @@
 	"""
 
-	return StringToEnum('SpcStatic')
+	return StringToEnum('SpcStatic')[0]
 
 def SpcTransientEnum():
@@ -2705,5 +2907,5 @@
 	"""
 
-	return StringToEnum('SpcTransient')
+	return StringToEnum('SpcTransient')[0]
 
 def StokesIceFrontEnum():
@@ -2715,5 +2917,5 @@
 	"""
 
-	return StringToEnum('StokesIceFront')
+	return StringToEnum('StokesIceFront')[0]
 
 def StringArrayParamEnum():
@@ -2725,5 +2927,5 @@
 	"""
 
-	return StringToEnum('StringArrayParam')
+	return StringToEnum('StringArrayParam')[0]
 
 def StringParamEnum():
@@ -2735,5 +2937,5 @@
 	"""
 
-	return StringToEnum('StringParam')
+	return StringToEnum('StringParam')[0]
 
 def TriaEnum():
@@ -2745,5 +2947,5 @@
 	"""
 
-	return StringToEnum('Tria')
+	return StringToEnum('Tria')[0]
 
 def TriaP1InputEnum():
@@ -2755,5 +2957,5 @@
 	"""
 
-	return StringToEnum('TriaP1Input')
+	return StringToEnum('TriaP1Input')[0]
 
 def VertexEnum():
@@ -2765,5 +2967,5 @@
 	"""
 
-	return StringToEnum('Vertex')
+	return StringToEnum('Vertex')[0]
 
 def AirEnum():
@@ -2775,5 +2977,5 @@
 	"""
 
-	return StringToEnum('Air')
+	return StringToEnum('Air')[0]
 
 def IceEnum():
@@ -2785,5 +2987,5 @@
 	"""
 
-	return StringToEnum('Ice')
+	return StringToEnum('Ice')[0]
 
 def MelangeEnum():
@@ -2795,5 +2997,5 @@
 	"""
 
-	return StringToEnum('Melange')
+	return StringToEnum('Melange')[0]
 
 def WaterEnum():
@@ -2805,5 +3007,5 @@
 	"""
 
-	return StringToEnum('Water')
+	return StringToEnum('Water')[0]
 
 def ClosedEnum():
@@ -2815,5 +3017,5 @@
 	"""
 
-	return StringToEnum('Closed')
+	return StringToEnum('Closed')[0]
 
 def FreeEnum():
@@ -2825,5 +3027,5 @@
 	"""
 
-	return StringToEnum('Free')
+	return StringToEnum('Free')[0]
 
 def OpenEnum():
@@ -2835,5 +3037,5 @@
 	"""
 
-	return StringToEnum('Open')
+	return StringToEnum('Open')[0]
 
 def AdjointpEnum():
@@ -2845,5 +3047,5 @@
 	"""
 
-	return StringToEnum('Adjointp')
+	return StringToEnum('Adjointp')[0]
 
 def AdjointxEnum():
@@ -2855,5 +3057,5 @@
 	"""
 
-	return StringToEnum('Adjointx')
+	return StringToEnum('Adjointx')[0]
 
 def AdjointyEnum():
@@ -2865,5 +3067,5 @@
 	"""
 
-	return StringToEnum('Adjointy')
+	return StringToEnum('Adjointy')[0]
 
 def AdjointzEnum():
@@ -2875,5 +3077,5 @@
 	"""
 
-	return StringToEnum('Adjointz')
+	return StringToEnum('Adjointz')[0]
 
 def BedSlopeXEnum():
@@ -2885,5 +3087,5 @@
 	"""
 
-	return StringToEnum('BedSlopeX')
+	return StringToEnum('BedSlopeX')[0]
 
 def BedSlopeYEnum():
@@ -2895,5 +3097,5 @@
 	"""
 
-	return StringToEnum('BedSlopeY')
+	return StringToEnum('BedSlopeY')[0]
 
 def BoundaryEnum():
@@ -2905,5 +3107,5 @@
 	"""
 
-	return StringToEnum('Boundary')
+	return StringToEnum('Boundary')[0]
 
 def ConstantEnum():
@@ -2915,5 +3117,5 @@
 	"""
 
-	return StringToEnum('Constant')
+	return StringToEnum('Constant')[0]
 
 def ConvergedEnum():
@@ -2925,5 +3127,5 @@
 	"""
 
-	return StringToEnum('Converged')
+	return StringToEnum('Converged')[0]
 
 def ExtToIuEnum():
@@ -2935,5 +3137,5 @@
 	"""
 
-	return StringToEnum('ExtToIu')
+	return StringToEnum('ExtToIu')[0]
 
 def FillEnum():
@@ -2945,5 +3147,5 @@
 	"""
 
-	return StringToEnum('Fill')
+	return StringToEnum('Fill')[0]
 
 def FractionIncrementEnum():
@@ -2955,5 +3157,5 @@
 	"""
 
-	return StringToEnum('FractionIncrement')
+	return StringToEnum('FractionIncrement')[0]
 
 def FrictionEnum():
@@ -2965,5 +3167,5 @@
 	"""
 
-	return StringToEnum('Friction')
+	return StringToEnum('Friction')[0]
 
 def GroundinglineMeltingRateEnum():
@@ -2975,5 +3177,5 @@
 	"""
 
-	return StringToEnum('GroundinglineMeltingRate')
+	return StringToEnum('GroundinglineMeltingRate')[0]
 
 def InternalEnum():
@@ -2985,5 +3187,5 @@
 	"""
 
-	return StringToEnum('Internal')
+	return StringToEnum('Internal')[0]
 
 def IuToExtEnum():
@@ -2995,5 +3197,5 @@
 	"""
 
-	return StringToEnum('IuToExt')
+	return StringToEnum('IuToExt')[0]
 
 def MassFluxEnum():
@@ -3005,5 +3207,5 @@
 	"""
 
-	return StringToEnum('MassFlux')
+	return StringToEnum('MassFlux')[0]
 
 def MaxPenetrationEnum():
@@ -3015,5 +3217,5 @@
 	"""
 
-	return StringToEnum('MaxPenetration')
+	return StringToEnum('MaxPenetration')[0]
 
 def MeltingOffsetEnum():
@@ -3025,5 +3227,5 @@
 	"""
 
-	return StringToEnum('MeltingOffset')
+	return StringToEnum('MeltingOffset')[0]
 
 def MisfitEnum():
@@ -3035,5 +3237,5 @@
 	"""
 
-	return StringToEnum('Misfit')
+	return StringToEnum('Misfit')[0]
 
 def NumberNodeToElementConnectivityEnum():
@@ -3045,5 +3247,5 @@
 	"""
 
-	return StringToEnum('NumberNodeToElementConnectivity')
+	return StringToEnum('NumberNodeToElementConnectivity')[0]
 
 def PressureEnum():
@@ -3055,5 +3257,5 @@
 	"""
 
-	return StringToEnum('Pressure')
+	return StringToEnum('Pressure')[0]
 
 def PressurePicardEnum():
@@ -3065,5 +3267,5 @@
 	"""
 
-	return StringToEnum('PressurePicard')
+	return StringToEnum('PressurePicard')[0]
 
 def QmuPressureEnum():
@@ -3075,5 +3277,5 @@
 	"""
 
-	return StringToEnum('QmuPressure')
+	return StringToEnum('QmuPressure')[0]
 
 def QmuVxEnum():
@@ -3085,5 +3287,5 @@
 	"""
 
-	return StringToEnum('QmuVx')
+	return StringToEnum('QmuVx')[0]
 
 def QmuVyEnum():
@@ -3095,5 +3297,5 @@
 	"""
 
-	return StringToEnum('QmuVy')
+	return StringToEnum('QmuVy')[0]
 
 def QmuVzEnum():
@@ -3105,5 +3307,5 @@
 	"""
 
-	return StringToEnum('QmuVz')
+	return StringToEnum('QmuVz')[0]
 
 def QmuThicknessEnum():
@@ -3115,5 +3317,5 @@
 	"""
 
-	return StringToEnum('QmuThickness')
+	return StringToEnum('QmuThickness')[0]
 
 def QmuBedEnum():
@@ -3125,5 +3327,5 @@
 	"""
 
-	return StringToEnum('QmuBed')
+	return StringToEnum('QmuBed')[0]
 
 def QmuSurfaceEnum():
@@ -3135,5 +3337,5 @@
 	"""
 
-	return StringToEnum('QmuSurface')
+	return StringToEnum('QmuSurface')[0]
 
 def QmuMeltingEnum():
@@ -3145,5 +3347,5 @@
 	"""
 
-	return StringToEnum('QmuMelting')
+	return StringToEnum('QmuMelting')[0]
 
 def ResetPenaltiesEnum():
@@ -3155,5 +3357,5 @@
 	"""
 
-	return StringToEnum('ResetPenalties')
+	return StringToEnum('ResetPenalties')[0]
 
 def SegmentOnIceShelfEnum():
@@ -3165,5 +3367,5 @@
 	"""
 
-	return StringToEnum('SegmentOnIceShelf')
+	return StringToEnum('SegmentOnIceShelf')[0]
 
 def SurfaceAbsVelMisfitEnum():
@@ -3175,5 +3377,5 @@
 	"""
 
-	return StringToEnum('SurfaceAbsVelMisfit')
+	return StringToEnum('SurfaceAbsVelMisfit')[0]
 
 def SurfaceAreaEnum():
@@ -3185,5 +3387,5 @@
 	"""
 
-	return StringToEnum('SurfaceArea')
+	return StringToEnum('SurfaceArea')[0]
 
 def SurfaceAverageVelMisfitEnum():
@@ -3195,5 +3397,5 @@
 	"""
 
-	return StringToEnum('SurfaceAverageVelMisfit')
+	return StringToEnum('SurfaceAverageVelMisfit')[0]
 
 def SurfaceLogVelMisfitEnum():
@@ -3205,5 +3407,5 @@
 	"""
 
-	return StringToEnum('SurfaceLogVelMisfit')
+	return StringToEnum('SurfaceLogVelMisfit')[0]
 
 def SurfaceLogVxVyMisfitEnum():
@@ -3215,5 +3417,5 @@
 	"""
 
-	return StringToEnum('SurfaceLogVxVyMisfit')
+	return StringToEnum('SurfaceLogVxVyMisfit')[0]
 
 def SurfaceRelVelMisfitEnum():
@@ -3225,5 +3427,5 @@
 	"""
 
-	return StringToEnum('SurfaceRelVelMisfit')
+	return StringToEnum('SurfaceRelVelMisfit')[0]
 
 def SurfaceSlopeXEnum():
@@ -3235,5 +3437,5 @@
 	"""
 
-	return StringToEnum('SurfaceSlopeX')
+	return StringToEnum('SurfaceSlopeX')[0]
 
 def SurfaceSlopeYEnum():
@@ -3245,5 +3447,5 @@
 	"""
 
-	return StringToEnum('SurfaceSlopeY')
+	return StringToEnum('SurfaceSlopeY')[0]
 
 def TemperatureEnum():
@@ -3255,5 +3457,5 @@
 	"""
 
-	return StringToEnum('Temperature')
+	return StringToEnum('Temperature')[0]
 
 def TemperatureOldEnum():
@@ -3265,5 +3467,5 @@
 	"""
 
-	return StringToEnum('TemperatureOld')
+	return StringToEnum('TemperatureOld')[0]
 
 def TemperaturePicardEnum():
@@ -3275,5 +3477,25 @@
 	"""
 
-	return StringToEnum('TemperaturePicard')
+	return StringToEnum('TemperaturePicard')[0]
+
+def TemperatureSurfaceEnum():
+	"""
+	TEMPERATURESURFACEENUM - Enum of TemperatureSurface
+
+	   Usage:
+	      macro=TemperatureSurfaceEnum()
+	"""
+
+	return StringToEnum('TemperatureSurface')[0]
+
+def TemperatureBasalEnum():
+	"""
+	TEMPERATUREBASALENUM - Enum of TemperatureBasal
+
+	   Usage:
+	      macro=TemperatureBasalEnum()
+	"""
+
+	return StringToEnum('TemperatureBasal')[0]
 
 def ThicknessAbsMisfitEnum():
@@ -3285,5 +3507,5 @@
 	"""
 
-	return StringToEnum('ThicknessAbsMisfit')
+	return StringToEnum('ThicknessAbsMisfit')[0]
 
 def TypeEnum():
@@ -3295,5 +3517,5 @@
 	"""
 
-	return StringToEnum('Type')
+	return StringToEnum('Type')[0]
 
 def VelEnum():
@@ -3305,5 +3527,5 @@
 	"""
 
-	return StringToEnum('Vel')
+	return StringToEnum('Vel')[0]
 
 def VelocityEnum():
@@ -3315,5 +3537,5 @@
 	"""
 
-	return StringToEnum('Velocity')
+	return StringToEnum('Velocity')[0]
 
 def VxAverageEnum():
@@ -3325,5 +3547,5 @@
 	"""
 
-	return StringToEnum('VxAverage')
+	return StringToEnum('VxAverage')[0]
 
 def VxEnum():
@@ -3335,5 +3557,5 @@
 	"""
 
-	return StringToEnum('Vx')
+	return StringToEnum('Vx')[0]
 
 def VxPicardEnum():
@@ -3345,5 +3567,5 @@
 	"""
 
-	return StringToEnum('VxPicard')
+	return StringToEnum('VxPicard')[0]
 
 def VyAverageEnum():
@@ -3355,5 +3577,5 @@
 	"""
 
-	return StringToEnum('VyAverage')
+	return StringToEnum('VyAverage')[0]
 
 def VyEnum():
@@ -3365,5 +3587,5 @@
 	"""
 
-	return StringToEnum('Vy')
+	return StringToEnum('Vy')[0]
 
 def VyPicardEnum():
@@ -3375,5 +3597,5 @@
 	"""
 
-	return StringToEnum('VyPicard')
+	return StringToEnum('VyPicard')[0]
 
 def VzEnum():
@@ -3385,5 +3607,5 @@
 	"""
 
-	return StringToEnum('Vz')
+	return StringToEnum('Vz')[0]
 
 def VzMacAyealEnum():
@@ -3395,5 +3617,5 @@
 	"""
 
-	return StringToEnum('VzMacAyeal')
+	return StringToEnum('VzMacAyeal')[0]
 
 def VzPattynEnum():
@@ -3405,5 +3627,5 @@
 	"""
 
-	return StringToEnum('VzPattyn')
+	return StringToEnum('VzPattyn')[0]
 
 def VzPicardEnum():
@@ -3415,5 +3637,5 @@
 	"""
 
-	return StringToEnum('VzPicard')
+	return StringToEnum('VzPicard')[0]
 
 def VzStokesEnum():
@@ -3425,5 +3647,5 @@
 	"""
 
-	return StringToEnum('VzStokes')
+	return StringToEnum('VzStokes')[0]
 
 def VxMeshEnum():
@@ -3435,5 +3657,5 @@
 	"""
 
-	return StringToEnum('VxMesh')
+	return StringToEnum('VxMesh')[0]
 
 def VyMeshEnum():
@@ -3445,5 +3667,5 @@
 	"""
 
-	return StringToEnum('VyMesh')
+	return StringToEnum('VyMesh')[0]
 
 def VzMeshEnum():
@@ -3455,5 +3677,5 @@
 	"""
 
-	return StringToEnum('VzMesh')
+	return StringToEnum('VzMesh')[0]
 
 def EnthalpyEnum():
@@ -3465,5 +3687,5 @@
 	"""
 
-	return StringToEnum('Enthalpy')
+	return StringToEnum('Enthalpy')[0]
 
 def EnthalpyPicardEnum():
@@ -3475,5 +3697,5 @@
 	"""
 
-	return StringToEnum('EnthalpyPicard')
+	return StringToEnum('EnthalpyPicard')[0]
 
 def ThicknessAbsGradientEnum():
@@ -3485,5 +3707,25 @@
 	"""
 
-	return StringToEnum('ThicknessAbsGradient')
+	return StringToEnum('ThicknessAbsGradient')[0]
+
+def ThicknessAlongGradientEnum():
+	"""
+	THICKNESSALONGGRADIENTENUM - Enum of ThicknessAlongGradient
+
+	   Usage:
+	      macro=ThicknessAlongGradientEnum()
+	"""
+
+	return StringToEnum('ThicknessAlongGradient')[0]
+
+def ThicknessAcrossGradientEnum():
+	"""
+	THICKNESSACROSSGRADIENTENUM - Enum of ThicknessAcrossGradient
+
+	   Usage:
+	      macro=ThicknessAcrossGradientEnum()
+	"""
+
+	return StringToEnum('ThicknessAcrossGradient')[0]
 
 def StepResponsesEnum():
@@ -3495,5 +3737,5 @@
 	"""
 
-	return StringToEnum('StepResponses')
+	return StringToEnum('StepResponses')[0]
 
 def IntMatParamEnum():
@@ -3505,5 +3747,5 @@
 	"""
 
-	return StringToEnum('IntMatParam')
+	return StringToEnum('IntMatParam')[0]
 
 def RheologyBbarAbsGradientEnum():
@@ -3515,5 +3757,5 @@
 	"""
 
-	return StringToEnum('RheologyBbarAbsGradient')
+	return StringToEnum('RheologyBbarAbsGradient')[0]
 
 def DragCoefficientAbsGradientEnum():
@@ -3525,5 +3767,5 @@
 	"""
 
-	return StringToEnum('DragCoefficientAbsGradient')
+	return StringToEnum('DragCoefficientAbsGradient')[0]
 
 def TransientInputEnum():
@@ -3535,5 +3777,5 @@
 	"""
 
-	return StringToEnum('TransientInput')
+	return StringToEnum('TransientInput')[0]
 
 def OutputfilenameEnum():
@@ -3545,5 +3787,5 @@
 	"""
 
-	return StringToEnum('Outputfilename')
+	return StringToEnum('Outputfilename')[0]
 
 def WaterfractionEnum():
@@ -3555,5 +3797,5 @@
 	"""
 
-	return StringToEnum('Waterfraction')
+	return StringToEnum('Waterfraction')[0]
 
 def WatercolumnEnum():
@@ -3565,5 +3807,5 @@
 	"""
 
-	return StringToEnum('Watercolumn')
+	return StringToEnum('Watercolumn')[0]
 
 def BasalFrictionEnum():
@@ -3575,5 +3817,5 @@
 	"""
 
-	return StringToEnum('BasalFriction')
+	return StringToEnum('BasalFriction')[0]
 
 def ViscousHeatingEnum():
@@ -3585,5 +3827,5 @@
 	"""
 
-	return StringToEnum('ViscousHeating')
+	return StringToEnum('ViscousHeating')[0]
 
 def QmuTemperatureEnum():
@@ -3595,5 +3837,5 @@
 	"""
 
-	return StringToEnum('QmuTemperature')
+	return StringToEnum('QmuTemperature')[0]
 
 def HydrologyWaterVxEnum():
@@ -3605,5 +3847,5 @@
 	"""
 
-	return StringToEnum('HydrologyWaterVx')
+	return StringToEnum('HydrologyWaterVx')[0]
 
 def HydrologyWaterVyEnum():
@@ -3615,5 +3857,5 @@
 	"""
 
-	return StringToEnum('HydrologyWaterVy')
+	return StringToEnum('HydrologyWaterVy')[0]
 
 def StressTensorEnum():
@@ -3625,5 +3867,5 @@
 	"""
 
-	return StringToEnum('StressTensor')
+	return StringToEnum('StressTensor')[0]
 
 def StressTensorxxEnum():
@@ -3635,5 +3877,5 @@
 	"""
 
-	return StringToEnum('StressTensorxx')
+	return StringToEnum('StressTensorxx')[0]
 
 def StressTensorxyEnum():
@@ -3645,5 +3887,5 @@
 	"""
 
-	return StringToEnum('StressTensorxy')
+	return StringToEnum('StressTensorxy')[0]
 
 def StressTensorxzEnum():
@@ -3655,5 +3897,5 @@
 	"""
 
-	return StringToEnum('StressTensorxz')
+	return StringToEnum('StressTensorxz')[0]
 
 def StressTensoryyEnum():
@@ -3665,5 +3907,5 @@
 	"""
 
-	return StringToEnum('StressTensoryy')
+	return StringToEnum('StressTensoryy')[0]
 
 def StressTensoryzEnum():
@@ -3675,5 +3917,5 @@
 	"""
 
-	return StringToEnum('StressTensoryz')
+	return StringToEnum('StressTensoryz')[0]
 
 def StressTensorzzEnum():
@@ -3685,5 +3927,335 @@
 	"""
 
-	return StringToEnum('StressTensorzz')
+	return StringToEnum('StressTensorzz')[0]
+
+def P0Enum():
+	"""
+	P0ENUM - Enum of P0
+
+	   Usage:
+	      macro=P0Enum()
+	"""
+
+	return StringToEnum('P0')[0]
+
+def P1Enum():
+	"""
+	P1ENUM - Enum of P1
+
+	   Usage:
+	      macro=P1Enum()
+	"""
+
+	return StringToEnum('P1')[0]
+
+def P1DGEnum():
+	"""
+	P1DGENUM - Enum of P1DG
+
+	   Usage:
+	      macro=P1DGEnum()
+	"""
+
+	return StringToEnum('P1DG')[0]
+
+def SaveResultsEnum():
+	"""
+	SAVERESULTSENUM - Enum of SaveResults
+
+	   Usage:
+	      macro=SaveResultsEnum()
+	"""
+
+	return StringToEnum('SaveResults')[0]
+
+def BoolElementResultEnum():
+	"""
+	BOOLELEMENTRESULTENUM - Enum of BoolElementResult
+
+	   Usage:
+	      macro=BoolElementResultEnum()
+	"""
+
+	return StringToEnum('BoolElementResult')[0]
+
+def BoolExternalResultEnum():
+	"""
+	BOOLEXTERNALRESULTENUM - Enum of BoolExternalResult
+
+	   Usage:
+	      macro=BoolExternalResultEnum()
+	"""
+
+	return StringToEnum('BoolExternalResult')[0]
+
+def DoubleElementResultEnum():
+	"""
+	DOUBLEELEMENTRESULTENUM - Enum of DoubleElementResult
+
+	   Usage:
+	      macro=DoubleElementResultEnum()
+	"""
+
+	return StringToEnum('DoubleElementResult')[0]
+
+def DoubleExternalResultEnum():
+	"""
+	DOUBLEEXTERNALRESULTENUM - Enum of DoubleExternalResult
+
+	   Usage:
+	      macro=DoubleExternalResultEnum()
+	"""
+
+	return StringToEnum('DoubleExternalResult')[0]
+
+def DoubleMatExternalResultEnum():
+	"""
+	DOUBLEMATEXTERNALRESULTENUM - Enum of DoubleMatExternalResult
+
+	   Usage:
+	      macro=DoubleMatExternalResultEnum()
+	"""
+
+	return StringToEnum('DoubleMatExternalResult')[0]
+
+def DoubleVecExternalResultEnum():
+	"""
+	DOUBLEVECEXTERNALRESULTENUM - Enum of DoubleVecExternalResult
+
+	   Usage:
+	      macro=DoubleVecExternalResultEnum()
+	"""
+
+	return StringToEnum('DoubleVecExternalResult')[0]
+
+def IntExternalResultEnum():
+	"""
+	INTEXTERNALRESULTENUM - Enum of IntExternalResult
+
+	   Usage:
+	      macro=IntExternalResultEnum()
+	"""
+
+	return StringToEnum('IntExternalResult')[0]
+
+def JEnum():
+	"""
+	JENUM - Enum of J
+
+	   Usage:
+	      macro=JEnum()
+	"""
+
+	return StringToEnum('J')[0]
+
+def PatchEnum():
+	"""
+	PATCHENUM - Enum of Patch
+
+	   Usage:
+	      macro=PatchEnum()
+	"""
+
+	return StringToEnum('Patch')[0]
+
+def PatchNodesEnum():
+	"""
+	PATCHNODESENUM - Enum of PatchNodes
+
+	   Usage:
+	      macro=PatchNodesEnum()
+	"""
+
+	return StringToEnum('PatchNodes')[0]
+
+def PatchVerticesEnum():
+	"""
+	PATCHVERTICESENUM - Enum of PatchVertices
+
+	   Usage:
+	      macro=PatchVerticesEnum()
+	"""
+
+	return StringToEnum('PatchVertices')[0]
+
+def PentaP1ElementResultEnum():
+	"""
+	PENTAP1ELEMENTRESULTENUM - Enum of PentaP1ElementResult
+
+	   Usage:
+	      macro=PentaP1ElementResultEnum()
+	"""
+
+	return StringToEnum('PentaP1ElementResult')[0]
+
+def PetscVecExternalResultEnum():
+	"""
+	PETSCVECEXTERNALRESULTENUM - Enum of PetscVecExternalResult
+
+	   Usage:
+	      macro=PetscVecExternalResultEnum()
+	"""
+
+	return StringToEnum('PetscVecExternalResult')[0]
+
+def StringExternalResultEnum():
+	"""
+	STRINGEXTERNALRESULTENUM - Enum of StringExternalResult
+
+	   Usage:
+	      macro=StringExternalResultEnum()
+	"""
+
+	return StringToEnum('StringExternalResult')[0]
+
+def StepEnum():
+	"""
+	STEPENUM - Enum of Step
+
+	   Usage:
+	      macro=StepEnum()
+	"""
+
+	return StringToEnum('Step')[0]
+
+def TimeEnum():
+	"""
+	TIMEENUM - Enum of Time
+
+	   Usage:
+	      macro=TimeEnum()
+	"""
+
+	return StringToEnum('Time')[0]
+
+def TriaP1ElementResultEnum():
+	"""
+	TRIAP1ELEMENTRESULTENUM - Enum of TriaP1ElementResult
+
+	   Usage:
+	      macro=TriaP1ElementResultEnum()
+	"""
+
+	return StringToEnum('TriaP1ElementResult')[0]
+
+def WaterColumnOldEnum():
+	"""
+	WATERCOLUMNOLDENUM - Enum of WaterColumnOld
+
+	   Usage:
+	      macro=WaterColumnOldEnum()
+	"""
+
+	return StringToEnum('WaterColumnOld')[0]
+
+def MinVelEnum():
+	"""
+	MINVELENUM - Enum of MinVel
+
+	   Usage:
+	      macro=MinVelEnum()
+	"""
+
+	return StringToEnum('MinVel')[0]
+
+def MaxVelEnum():
+	"""
+	MAXVELENUM - Enum of MaxVel
+
+	   Usage:
+	      macro=MaxVelEnum()
+	"""
+
+	return StringToEnum('MaxVel')[0]
+
+def MinVxEnum():
+	"""
+	MINVXENUM - Enum of MinVx
+
+	   Usage:
+	      macro=MinVxEnum()
+	"""
+
+	return StringToEnum('MinVx')[0]
+
+def MaxVxEnum():
+	"""
+	MAXVXENUM - Enum of MaxVx
+
+	   Usage:
+	      macro=MaxVxEnum()
+	"""
+
+	return StringToEnum('MaxVx')[0]
+
+def MaxAbsVxEnum():
+	"""
+	MAXABSVXENUM - Enum of MaxAbsVx
+
+	   Usage:
+	      macro=MaxAbsVxEnum()
+	"""
+
+	return StringToEnum('MaxAbsVx')[0]
+
+def MinVyEnum():
+	"""
+	MINVYENUM - Enum of MinVy
+
+	   Usage:
+	      macro=MinVyEnum()
+	"""
+
+	return StringToEnum('MinVy')[0]
+
+def MaxVyEnum():
+	"""
+	MAXVYENUM - Enum of MaxVy
+
+	   Usage:
+	      macro=MaxVyEnum()
+	"""
+
+	return StringToEnum('MaxVy')[0]
+
+def MaxAbsVyEnum():
+	"""
+	MAXABSVYENUM - Enum of MaxAbsVy
+
+	   Usage:
+	      macro=MaxAbsVyEnum()
+	"""
+
+	return StringToEnum('MaxAbsVy')[0]
+
+def MinVzEnum():
+	"""
+	MINVZENUM - Enum of MinVz
+
+	   Usage:
+	      macro=MinVzEnum()
+	"""
+
+	return StringToEnum('MinVz')[0]
+
+def MaxVzEnum():
+	"""
+	MAXVZENUM - Enum of MaxVz
+
+	   Usage:
+	      macro=MaxVzEnum()
+	"""
+
+	return StringToEnum('MaxVz')[0]
+
+def MaxAbsVzEnum():
+	"""
+	MAXABSVZENUM - Enum of MaxAbsVz
+
+	   Usage:
+	      macro=MaxAbsVzEnum()
+	"""
+
+	return StringToEnum('MaxAbsVz')[0]
 
 def IceVolumeEnum():
@@ -3695,335 +4267,15 @@
 	"""
 
-	return StringToEnum('IceVolume')
-
-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')
+	return StringToEnum('IceVolume')[0]
+
+def TotalSmbEnum():
+	"""
+	TOTALSMBENUM - Enum of TotalSmb
+
+	   Usage:
+	      macro=TotalSmbEnum()
+	"""
+
+	return StringToEnum('TotalSmb')[0]
 
 def RelativeEnum():
@@ -4035,5 +4287,5 @@
 	"""
 
-	return StringToEnum('Relative')
+	return StringToEnum('Relative')[0]
 
 def AbsoluteEnum():
@@ -4045,5 +4297,5 @@
 	"""
 
-	return StringToEnum('Absolute')
+	return StringToEnum('Absolute')[0]
 
 def IncrementalEnum():
@@ -4055,5 +4307,5 @@
 	"""
 
-	return StringToEnum('Incremental')
+	return StringToEnum('Incremental')[0]
 
 def AgressiveMigrationEnum():
@@ -4065,5 +4317,5 @@
 	"""
 
-	return StringToEnum('AgressiveMigration')
+	return StringToEnum('AgressiveMigration')[0]
 
 def NoneEnum():
@@ -4075,5 +4327,5 @@
 	"""
 
-	return StringToEnum('None')
+	return StringToEnum('None')[0]
 
 def SoftMigrationEnum():
@@ -4085,5 +4337,5 @@
 	"""
 
-	return StringToEnum('SoftMigration')
+	return StringToEnum('SoftMigration')[0]
 
 def StokesSolverEnum():
@@ -4095,5 +4347,5 @@
 	"""
 
-	return StringToEnum('StokesSolver')
+	return StringToEnum('StokesSolver')[0]
 
 def AdjointEnum():
@@ -4105,5 +4357,5 @@
 	"""
 
-	return StringToEnum('Adjoint')
+	return StringToEnum('Adjoint')[0]
 
 def ColinearEnum():
@@ -4115,5 +4367,5 @@
 	"""
 
-	return StringToEnum('Colinear')
+	return StringToEnum('Colinear')[0]
 
 def ControlSteadyEnum():
@@ -4125,5 +4377,5 @@
 	"""
 
-	return StringToEnum('ControlSteady')
+	return StringToEnum('ControlSteady')[0]
 
 def FsetEnum():
@@ -4135,5 +4387,5 @@
 	"""
 
-	return StringToEnum('Fset')
+	return StringToEnum('Fset')[0]
 
 def Gradient1Enum():
@@ -4145,5 +4397,5 @@
 	"""
 
-	return StringToEnum('Gradient1')
+	return StringToEnum('Gradient1')[0]
 
 def Gradient2Enum():
@@ -4155,5 +4407,5 @@
 	"""
 
-	return StringToEnum('Gradient2')
+	return StringToEnum('Gradient2')[0]
 
 def Gradient3Enum():
@@ -4165,5 +4417,5 @@
 	"""
 
-	return StringToEnum('Gradient3')
+	return StringToEnum('Gradient3')[0]
 
 def GradientEnum():
@@ -4175,5 +4427,5 @@
 	"""
 
-	return StringToEnum('Gradient')
+	return StringToEnum('Gradient')[0]
 
 def GroundinglineMigrationEnum():
@@ -4185,5 +4437,5 @@
 	"""
 
-	return StringToEnum('GroundinglineMigration')
+	return StringToEnum('GroundinglineMigration')[0]
 
 def GsetEnum():
@@ -4195,5 +4447,5 @@
 	"""
 
-	return StringToEnum('Gset')
+	return StringToEnum('Gset')[0]
 
 def IndexEnum():
@@ -4205,5 +4457,5 @@
 	"""
 
-	return StringToEnum('Index')
+	return StringToEnum('Index')[0]
 
 def IndexedEnum():
@@ -4215,5 +4467,5 @@
 	"""
 
-	return StringToEnum('Indexed')
+	return StringToEnum('Indexed')[0]
 
 def IntersectEnum():
@@ -4225,5 +4477,5 @@
 	"""
 
-	return StringToEnum('Intersect')
+	return StringToEnum('Intersect')[0]
 
 def NodalEnum():
@@ -4235,5 +4487,5 @@
 	"""
 
-	return StringToEnum('Nodal')
+	return StringToEnum('Nodal')[0]
 
 def OldGradientEnum():
@@ -4245,5 +4497,5 @@
 	"""
 
-	return StringToEnum('OldGradient')
+	return StringToEnum('OldGradient')[0]
 
 def OutputFilePointerEnum():
@@ -4255,5 +4507,5 @@
 	"""
 
-	return StringToEnum('OutputFilePointer')
+	return StringToEnum('OutputFilePointer')[0]
 
 def PetscOptionsAnalysesEnum():
@@ -4265,5 +4517,5 @@
 	"""
 
-	return StringToEnum('PetscOptionsAnalyses')
+	return StringToEnum('PetscOptionsAnalyses')[0]
 
 def PetscOptionsStringsEnum():
@@ -4275,5 +4527,5 @@
 	"""
 
-	return StringToEnum('PetscOptionsStrings')
+	return StringToEnum('PetscOptionsStrings')[0]
 
 def QmuErrNameEnum():
@@ -4285,5 +4537,5 @@
 	"""
 
-	return StringToEnum('QmuErrName')
+	return StringToEnum('QmuErrName')[0]
 
 def QmuInNameEnum():
@@ -4295,5 +4547,5 @@
 	"""
 
-	return StringToEnum('QmuInName')
+	return StringToEnum('QmuInName')[0]
 
 def QmuOutNameEnum():
@@ -4305,5 +4557,5 @@
 	"""
 
-	return StringToEnum('QmuOutName')
+	return StringToEnum('QmuOutName')[0]
 
 def RegularEnum():
@@ -4315,5 +4567,5 @@
 	"""
 
-	return StringToEnum('Regular')
+	return StringToEnum('Regular')[0]
 
 def ScaledEnum():
@@ -4325,5 +4577,5 @@
 	"""
 
-	return StringToEnum('Scaled')
+	return StringToEnum('Scaled')[0]
 
 def SeparateEnum():
@@ -4335,5 +4587,5 @@
 	"""
 
-	return StringToEnum('Separate')
+	return StringToEnum('Separate')[0]
 
 def SsetEnum():
@@ -4345,5 +4597,5 @@
 	"""
 
-	return StringToEnum('Sset')
+	return StringToEnum('Sset')[0]
 
 def VerboseEnum():
@@ -4355,5 +4607,5 @@
 	"""
 
-	return StringToEnum('Verbose')
+	return StringToEnum('Verbose')[0]
 
 def TriangleInterpEnum():
@@ -4365,5 +4617,5 @@
 	"""
 
-	return StringToEnum('TriangleInterp')
+	return StringToEnum('TriangleInterp')[0]
 
 def BilinearInterpEnum():
@@ -4375,5 +4627,5 @@
 	"""
 
-	return StringToEnum('BilinearInterp')
+	return StringToEnum('BilinearInterp')[0]
 
 def NearestInterpEnum():
@@ -4385,5 +4637,5 @@
 	"""
 
-	return StringToEnum('NearestInterp')
+	return StringToEnum('NearestInterp')[0]
 
 def XYEnum():
@@ -4395,5 +4647,5 @@
 	"""
 
-	return StringToEnum('XY')
+	return StringToEnum('XY')[0]
 
 def XYZPEnum():
@@ -4405,5 +4657,5 @@
 	"""
 
-	return StringToEnum('XYZP')
+	return StringToEnum('XYZP')[0]
 
 def OptionEnum():
@@ -4415,5 +4667,15 @@
 	"""
 
-	return StringToEnum('Option')
+	return StringToEnum('Option')[0]
+
+def GenericOptionEnum():
+	"""
+	GENERICOPTIONENUM - Enum of GenericOption
+
+	   Usage:
+	      macro=GenericOptionEnum()
+	"""
+
+	return StringToEnum('GenericOption')[0]
 
 def OptionCellEnum():
@@ -4425,5 +4687,5 @@
 	"""
 
-	return StringToEnum('OptionCell')
+	return StringToEnum('OptionCell')[0]
 
 def OptionCharEnum():
@@ -4435,5 +4697,5 @@
 	"""
 
-	return StringToEnum('OptionChar')
+	return StringToEnum('OptionChar')[0]
 
 def OptionStructEnum():
@@ -4445,5 +4707,5 @@
 	"""
 
-	return StringToEnum('OptionStruct')
+	return StringToEnum('OptionStruct')[0]
 
 def OptionDoubleEnum():
@@ -4455,5 +4717,5 @@
 	"""
 
-	return StringToEnum('OptionDouble')
+	return StringToEnum('OptionDouble')[0]
 
 def OptionLogicalEnum():
@@ -4465,5 +4727,5 @@
 	"""
 
-	return StringToEnum('OptionLogical')
+	return StringToEnum('OptionLogical')[0]
 
 def PatersonEnum():
@@ -4475,5 +4737,5 @@
 	"""
 
-	return StringToEnum('Paterson')
+	return StringToEnum('Paterson')[0]
 
 def ArrheniusEnum():
@@ -4485,5 +4747,5 @@
 	"""
 
-	return StringToEnum('Arrhenius')
+	return StringToEnum('Arrhenius')[0]
 
 def MaximumNumberOfEnums():
@@ -4495,4 +4757,4 @@
 	"""
 
-	return 448
-
+	return 474
+
Index: /issm/trunk/src/m/enum/FlowequationIsl1l2Enum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIsl1l2Enum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/FlowequationIsl1l2Enum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsl1l2Enum()
+%FLOWEQUATIONISL1L2ENUM - Enum of FlowequationIsl1l2
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=FlowequationIsl1l2Enum()
+
+macro=StringToEnum('FlowequationIsl1l2');
Index: /issm/trunk/src/m/enum/GenericOptionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GenericOptionEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/GenericOptionEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=GenericOptionEnum()
+%GENERICOPTIONENUM - Enum of GenericOption
+%
+%   WARNING: DO NOT 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=GenericOptionEnum()
+
+macro=StringToEnum('GenericOption');
Index: /issm/trunk/src/m/enum/GenericParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GenericParamEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/GenericParamEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=GenericParamEnum()
+%GENERICPARAMENUM - Enum of GenericParam
+%
+%   WARNING: DO NOT 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=GenericParamEnum()
+
+macro=StringToEnum('GenericParam');
Index: /issm/trunk/src/m/enum/L1L2ApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/L1L2ApproximationEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/L1L2ApproximationEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=L1L2ApproximationEnum()
+%L1L2APPROXIMATIONENUM - Enum of L1L2Approximation
+%
+%   WARNING: DO NOT 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=L1L2ApproximationEnum()
+
+macro=StringToEnum('L1L2Approximation');
Index: /issm/trunk/src/m/enum/L1L2IceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/L1L2IceFrontEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/L1L2IceFrontEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=L1L2IceFrontEnum()
+%L1L2ICEFRONTENUM - Enum of L1L2IceFront
+%
+%   WARNING: DO NOT 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=L1L2IceFrontEnum()
+
+macro=StringToEnum('L1L2IceFront');
Index: /issm/trunk/src/m/enum/MatdamageiceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MatdamageiceEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/MatdamageiceEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=MatdamageiceEnum()
+%MATDAMAGEICEENUM - Enum of Matdamageice
+%
+%   WARNING: DO NOT 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=MatdamageiceEnum()
+
+macro=StringToEnum('Matdamageice');
Index: /issm/trunk/src/m/enum/MaterialsRheologyZEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRheologyZEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/MaterialsRheologyZEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=MaterialsRheologyZEnum()
+%MATERIALSRHEOLOGYZENUM - Enum of MaterialsRheologyZ
+%
+%   WARNING: DO NOT 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=MaterialsRheologyZEnum()
+
+macro=StringToEnum('MaterialsRheologyZ');
Index: /issm/trunk/src/m/enum/MaterialsRheologyZbarEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaterialsRheologyZbarEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/MaterialsRheologyZbarEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=MaterialsRheologyZbarEnum()
+%MATERIALSRHEOLOGYZBARENUM - Enum of MaterialsRheologyZbar
+%
+%   WARNING: DO NOT 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=MaterialsRheologyZbarEnum()
+
+macro=StringToEnum('MaterialsRheologyZbar');
Index: /issm/trunk/src/m/enum/MaximumNumberOfEnums.m
===================================================================
--- /issm/trunk/src/m/enum/MaximumNumberOfEnums.m	(revision 13394)
+++ /issm/trunk/src/m/enum/MaximumNumberOfEnums.m	(revision 13395)
@@ -9,3 +9,3 @@
 %      macro=MaximumNumberOfEnums()
 
-macro=448;
+macro=474;
Index: /issm/trunk/src/m/enum/SurfaceforcingsDelta18oEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsDelta18oEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsDelta18oEnum.m	(revision 13395)
@@ -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/trunk/src/m/enum/SurfaceforcingsDelta18oSurfaceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsDelta18oSurfaceEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsDelta18oSurfaceEnum.m	(revision 13395)
@@ -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/trunk/src/m/enum/SurfaceforcingsIsdelta18oEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsIsdelta18oEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsIsdelta18oEnum.m	(revision 13395)
@@ -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/trunk/src/m/enum/SurfaceforcingsPrecipitationsPresentdayEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsPrecipitationsPresentdayEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsPrecipitationsPresentdayEnum.m	(revision 13395)
@@ -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/trunk/src/m/enum/SurfaceforcingsTemperaturesLgmEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsTemperaturesLgmEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsTemperaturesLgmEnum.m	(revision 13395)
@@ -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/trunk/src/m/enum/SurfaceforcingsTemperaturesPresentdayEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsTemperaturesPresentdayEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/SurfaceforcingsTemperaturesPresentdayEnum.m	(revision 13395)
@@ -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/trunk/src/m/enum/TemperatureBasalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TemperatureBasalEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/TemperatureBasalEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=TemperatureBasalEnum()
+%TEMPERATUREBASALENUM - Enum of TemperatureBasal
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TemperatureBasalEnum()
+
+macro=StringToEnum('TemperatureBasal');
Index: /issm/trunk/src/m/enum/TemperatureSurfaceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TemperatureSurfaceEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/TemperatureSurfaceEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=TemperatureSurfaceEnum()
+%TEMPERATURESURFACEENUM - Enum of TemperatureSurface
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/EnumDefinitions/Synchronize.sh
+%            Please read src/c/EnumDefinitions/README for more information
+%
+%   Usage:
+%      macro=TemperatureSurfaceEnum()
+
+macro=StringToEnum('TemperatureSurface');
Index: /issm/trunk/src/m/enum/ThicknessAcrossGradientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThicknessAcrossGradientEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/ThicknessAcrossGradientEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=ThicknessAcrossGradientEnum()
+%THICKNESSACROSSGRADIENTENUM - Enum of ThicknessAcrossGradient
+%
+%   WARNING: DO NOT 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=ThicknessAcrossGradientEnum()
+
+macro=StringToEnum('ThicknessAcrossGradient');
Index: /issm/trunk/src/m/enum/ThicknessAlongGradientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThicknessAlongGradientEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/ThicknessAlongGradientEnum.m	(revision 13395)
@@ -0,0 +1,11 @@
+function macro=ThicknessAlongGradientEnum()
+%THICKNESSALONGGRADIENTENUM - Enum of ThicknessAlongGradient
+%
+%   WARNING: DO NOT 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=ThicknessAlongGradientEnum()
+
+macro=StringToEnum('ThicknessAlongGradient');
Index: /issm/trunk/src/m/enum/TotalSmbEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TotalSmbEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/TotalSmbEnum.m	(revision 13395)
@@ -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/trunk/src/m/enum/TransientParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientParamEnum.m	(revision 13395)
+++ /issm/trunk/src/m/enum/TransientParamEnum.m	(revision 13395)
@@ -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/trunk/src/m/exp/clicktoflowline.m
===================================================================
--- /issm/trunk/src/m/exp/clicktoflowline.m	(revision 13395)
+++ /issm/trunk/src/m/exp/clicktoflowline.m	(revision 13395)
@@ -0,0 +1,24 @@
+function clicktoflowline(index,x,y,u,v,filename)
+%CLICKTOFLOWLINE - create a flowline ARGUS file
+%
+%   create a flowline contour file (named 'filename') by clicking
+%   on a velocity field once (velocity must be plotted first)
+%
+%   Usage: 
+%      clicktoflowline(index,x,y,u,v,x0,y0,filename)
+%
+%   Example: 
+%      clicktoflowline(md.mesh.elements,md.mesh.x,md.mesh.y,md.inversion.vx_obs,md.inversion.vy_obs,'flowline.exp')
+
+%Get click position
+[x0,y0]=ginput(1);
+
+%Get flowline
+line=flowlines(index,x,y,u,v,x0,y0,200);
+
+%plot
+hold on
+plot(line.x,line.y,'r-');
+
+%Write argus file
+expwrite(line,filename);
Index: /issm/trunk/src/m/exp/downstreamflowlines.m
===================================================================
--- /issm/trunk/src/m/exp/downstreamflowlines.m	(revision 13395)
+++ /issm/trunk/src/m/exp/downstreamflowlines.m	(revision 13395)
@@ -0,0 +1,110 @@
+function flowpath=downstreamflowlines(index,x,y,u,v,x0,y0,varargin)
+%DOWNSTREAMFLOWLINES - compute flowlines from a given set of seed points
+%
+%   Usage:
+%      flowpath=downstreamflowlines(index,x,y,u,v,x0,y0)
+%
+%   the velocity field is given by the couple (u,v) and the coordinates
+%   of the seed points are (x0,y0). One can use one or several seed 
+%   points
+%
+%   Example:
+%      flowpath=downstreamflowlines(md.mesh.elements,md.mesh.x,md.mesh.y,md.vx,md.initialization.vy,x0,y0)
+
+%check input size
+if nargin>9 | nargin<7,
+	help flowlines
+	error('flowlines error message: bad usage');
+end
+
+%check input
+if (length(x)~=length(y) | length(x)~=length(u) | length(x)~=length(v)),
+	error('flowlines error message: x,y,u and v must have the same length');
+end
+if length(x)<3,
+	error('flowlines error message: at least one element is required');
+end
+if length(x0)~=length(y0),
+	error('flowlines error message: x0 and y0 do not have the same length');
+end
+
+%get maxiter and precision
+if nargin==9
+	maxiter=varargin{1};%maximum number of iterations
+	precision=varargin{2}; %division of each segment (higer precision increases number of segments)
+else
+	maxiter=200; %maximum number of iterations
+	precision=1; %division of each segment (higer precision increases number of segments)
+end
+
+%check seed points
+tria=TriaSearch(index,x,y,x0,y0);
+pos=find(isnan(tria));
+x0(pos)=[];
+y0(pos)=[];
+
+%initialize other variables
+N=length(x0);
+X=x0; Y=y0;
+flowpath=struct('x',cell(N,1),'y',cell(N,1),'name','','density',1);
+for i=1:N,
+	flowpath(i).x=x0(i);
+	flowpath(i).y=y0(i);
+end
+done=zeros(N,1);
+
+%get avegared length of each element
+length_tria=1/3*(sqrt( (x(index(:,1))-x(index(:,2))).^2+(y(index(:,1))-y(index(:,2))).^2 )+...
+	sqrt((x(index(:,1))-x(index(:,3))).^2+(y(index(:,1))-y(index(:,3))).^2 )+...
+	sqrt((x(index(:,2))-x(index(:,3))).^2+(y(index(:,2))-y(index(:,3))).^2 ));
+
+%take velocity for each element
+u=u(index)*[1;1;1]/3;
+v=v(index)*[1;1;1]/3;
+
+%initialization:
+counter=1;
+
+while any(~done) 
+
+	%find current triangle
+	queue=find(~done);
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+
+	%check that the point is actually inside a triangle of the mesh
+	listnan=find(isnan(tria));
+	for i=1:length(listnan)
+		%remove the last point
+		flowpath(queue(listnan(i))).x(end)=[];
+		flowpath(queue(listnan(i))).y(end)=[];
+		done(queue(listnan(i)))=1;
+	end
+	tria(listnan)=[]; 
+	queue(listnan)=[];
+
+	if isempty(tria),
+		break;
+	end
+
+	%velocity of the current triangle and norm it
+	ut=u(tria); vt=v(tria); normv=sqrt(ut.^2+vt.^2);
+	ut=ut./normv;vt=vt./normv;
+
+	%check counter
+	if counter>maxiter
+		disp(['Maximum number of iterations (' num2str(maxiter) ') reached while going forward'])
+		break
+	end
+	counter=counter+1;
+
+	%remove stagnant point
+	done(queue(find(ut==0 & vt==0)))=1;
+
+	%build next point
+	for i=1:length(queue)
+		X(queue(i))=flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision;
+		Y(queue(i))=flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision;
+		flowpath(queue(i)).x=[flowpath(queue(i)).x;flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision];
+		flowpath(queue(i)).y=[flowpath(queue(i)).y;flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision];
+	end
+end
Index: /issm/trunk/src/m/exp/expbox.m
===================================================================
--- /issm/trunk/src/m/exp/expbox.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expbox.m	(revision 13395)
@@ -0,0 +1,41 @@
+function expbox(filename)
+%EXPBOX - Create an ARGUS file using two clicks
+%
+%   Two clicks on a plot are used to generate a rectangular box
+%   This box is written in EXP format on filename
+%
+%   Usage:
+%      expbox(filename)
+
+%check
+if exist(filename,'file'),
+	choice=input(['A file ' filename ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return
+	end
+end
+
+%Get points
+disp('Click twice to define a rectangular domain. First click for upper left corner, second for lower right corner');
+[x,y]=ginput(2);
+
+x1=x(1);
+x2=x(2);
+x3=x2;
+x4=x1;
+
+y1=y(1);
+y2=y1;
+y3=y(2);
+y4=y3;
+
+%Build Exp structure
+A=struct();
+A.nods=5;
+A.density=1;
+A.x=[x1 x2 x3 x4 x1]';
+A.y=[y1 y2 y3 y4 y1]';
+
+%Write structure
+expwrite(A,filename);
Index: /issm/trunk/src/m/exp/expcircle.m
===================================================================
--- /issm/trunk/src/m/exp/expcircle.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expcircle.m	(revision 13395)
@@ -0,0 +1,31 @@
+function expcircle(filename,x0,y0,radius,numberofnodes)
+%EXPCIRCLE - create a circular contour corresponding to given parameters
+%
+%   Creates a closed argus contour centered on x,y of radius size.
+%   The contour is made of numberofnodes
+%
+%   Usage:
+%      expcircle(filename,x0,y0,radius,numberofnodes)
+%
+%   See also EXPMASTER, EXPDOC
+
+%Calculate the cartesians coordinates of the points
+x_list=ones(numberofnodes+1,1);
+y_list=ones(numberofnodes+1,1);
+
+theta=(0:2*pi/numberofnodes:2*pi*(1-1/numberofnodes))';
+theta=[theta;0];
+
+x_list=radius*x_list.*cos(theta);
+y_list=radius*y_list.*sin(theta);
+
+%offset x_list and y_list by x0 and y0:
+x_list=x_list+x0;
+y_list=y_list+y0;
+
+contour.x=x_list;
+contour.y=y_list;
+contour.density=1;
+contour.name='circle';
+
+expwrite(contour,filename);
Index: /issm/trunk/src/m/exp/expcoarsen.m
===================================================================
--- /issm/trunk/src/m/exp/expcoarsen.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expcoarsen.m	(revision 13395)
@@ -0,0 +1,74 @@
+function expcoarsen(newfile,oldfile,resolution);
+%EXPCOARSEN - coarsen an exp contour
+%
+%   This routine read an Argus file and remove points with respect to
+%   the resolution (in meters) given in input. 
+%
+%   Usage:
+%      expcoarsen(newfile,oldfile,resolution)
+%
+%   Example:
+%       expcoarsen('DomainOutline.exp','Antarctica.exp',4000)
+
+%Some checks
+if nargin~=3 | nargout
+	error('expcoarsen usage: expcoarsen(newfile,oldfile,resolution)')
+elseif ~exist(oldfile)
+	error(['expcut error message: the file ' oldfile ' does not exist'])
+elseif exist(newfile),
+	choice=input(['A file ' newfile ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return;
+	end
+end
+
+%Get exp oldfile
+[path root ext ver]=fileparts(oldfile);
+A=expread(oldfile);
+numprofiles=size(A,2);
+
+%Go through the profiles
+count=1;
+while count<=numprofiles,
+
+	%get number of points and initialize j
+	numpoints=length(A(count).x);
+	j=1;
+
+	%stop if we have reached end of profile (always keep the last point)
+	while j<numpoints,
+
+		%See whether we keep this point or not
+		distance=sqrt((A(count).x(j)-A(count).x(j+1))^2+(A(count).y(j)-A(count).y(j+1))^2);
+		if distance<resolution & j<numpoints-1  %do not remove last point
+			A(count).x(j+1)=[];
+			A(count).y(j+1)=[];
+			numpoints=numpoints-1;
+		else
+			division=floor(distance/resolution)+1;
+			if division>=2,
+				x=linspace(A(count).x(j),A(count).x(j+1),division)';
+				y=linspace(A(count).y(j),A(count).y(j+1),division)';
+				A(count).x=[A(count).x(1:j);x(2:end-1); A(count).x(j+1:end)];
+				A(count).y=[A(count).y(1:j);y(2:end-1); A(count).y(j+1:end)];
+
+				%update current point
+				j=j+1+division-2;
+				numpoints=numpoints+division-2;
+			else
+				%update current point
+				j=j+1;
+			end
+		end
+	end
+	if length(A(count).x)<=1,
+		A(count)=[];
+		numprofiles=numprofiles-1;
+	else
+		count=count+1;
+	end
+end
+
+%write output
+expwrite(A,newfile);
Index: /issm/trunk/src/m/exp/expcontract.m
===================================================================
--- /issm/trunk/src/m/exp/expcontract.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expcontract.m	(revision 13395)
@@ -0,0 +1,34 @@
+function normal_node=expcontract(newfile,oldfile,distance)
+%EXPCONTRACT - contract or expand a profile, according to the normal.
+% 
+%   Usage:
+%      expcontract(newfile,oldfile,distance)
+%
+%   See also EXPMASTER, EXPDOC
+
+
+contour=expread(oldfile);
+num=numel(contour.x);
+
+normal=zeros(num-1,2);
+normal_node=zeros(num-1,2);
+
+for i=1:num-1,
+	normal(i,:)=[ contour.y(i)-contour.y(i+1) contour.x(i+1)-contour.x(i)];
+	normal(i,:)=normal(i,:)/sqrt(normal(i,1)^2+normal(i,2)^2);
+end
+
+normal_node(2:end,:)=[normal(1:end-1,:)+normal(2:end,:)];
+normal_node(1,:)=normal(1,:)+normal(end,:);
+
+normal_node_norm=sqrt(normal_node(:,1).^2+normal_node(:,2).^2);
+normal_node(:,1)=normal_node(:,1)./normal_node_norm;
+normal_node(:,2)=normal_node(:,2)./normal_node_norm;
+
+contour.x(1:end-1)=contour.x(1:end-1)+distance*normal_node(:,1);
+contour.y(1:end-1)=contour.y(1:end-1)+distance*normal_node(:,2);
+
+contour.x(end)=contour.x(1);
+contour.y(end)=contour.y(1);
+
+expwrite(contour,newfile);
Index: /issm/trunk/src/m/exp/expcreatecontour.m
===================================================================
--- /issm/trunk/src/m/exp/expcreatecontour.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expcreatecontour.m	(revision 13395)
@@ -0,0 +1,36 @@
+function expcreatecontour(filename);
+%EXPCREATECONTOUR - create a contour from a list of points
+%
+%   expcreatecontour: from a list of (x,y) points (retrieve using ginput on an undetermined
+%   number of points: used RETURN key to end input), create an Argus .exp 
+%   file holding the corresponding closed contour.
+%    
+%   Usage:
+%      expcreatecontour(filename)
+%
+%   See also EXPMASTER, EXPDOC
+
+%Get root of filename
+[path root ext ver]=fileparts(filename);
+
+%Get contour
+disp('Click on contour points you desire. Type RETURN to end input of points');
+[x,y]=ginput();
+
+%close contour
+x=[x;x(1)];
+y=[y;y(1);];
+
+%plot contour
+hold on;
+plot(x,y,'r-');
+
+%create structure for expwrite routine
+a.x=x;
+a.y=y;
+a.name=root;
+a.density=1;
+
+%write contour using expwrite
+expwrite(a,filename);
+
Index: /issm/trunk/src/m/exp/expcreateprofile.m
===================================================================
--- /issm/trunk/src/m/exp/expcreateprofile.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expcreateprofile.m	(revision 13395)
@@ -0,0 +1,31 @@
+function expcreateprofile(filename);
+%EXPCREATEPROFILE - create an Argus file from a list of points
+%
+%   expcreateprofile: from a list of (x,y) points (retrieve using ginput on an undetermined
+%   number of points: used RETURN key to end input), create an Argus .exp 
+%   file holding the corresponding open profile.
+%    
+%   Usage:
+%      expcreateprofile(filename)
+%
+%   See also EXPMASTER, EXPDOC
+
+%Get root of filename
+[path root ext ver]=fileparts(filename);
+
+%Get profile
+disp('Click on profile points you desire. Type RETURN to end input of points');
+[x,y]=ginput();
+
+%plot contour
+hold on;
+plot(x,y,'r-');
+
+%create structure for expwrite routine
+a.x=x;
+a.y=y;
+a.name=root;
+a.density=1;
+
+%write profile using expwrite
+expwrite(a,filename);
Index: /issm/trunk/src/m/exp/expdisp.m
===================================================================
--- /issm/trunk/src/m/exp/expdisp.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expdisp.m	(revision 13395)
@@ -0,0 +1,52 @@
+function expdisp(domainoutline,varargin)
+%EXPDISP - plot the contours of a domain outline file
+%
+%   This routine reads in a domain outline file (Argus format) and plots all the contours 
+%
+%   Usage:
+%      expdisp(domainoutline,varargin)
+%      expdisp(domainoutline,figurenumber,linestyle,linewidth,unitmultiplier)
+%
+%   Example:
+%      expdisp('Domain.exp',1,'--r',2,10^3);
+%
+%   See also EXPMASTER, EXPDOC
+
+%check nargin
+if ~nargin | nargin>5
+	help expdisp
+	error('expdisp error message: bad usage');
+end
+
+%parse input
+if nargin<=1,
+	figurenumber=1;
+else
+	figurenumber=varargin{1};
+end
+if nargin<=2
+	linestyle='r-';
+else
+	linestyle=varargin{2};
+end
+if nargin<=3
+	linewidth=1;
+else
+	linewidth=varargin{3};
+end
+if nargin<=4
+	unitmultiplier=1;
+else
+	unitmultiplier=varargin{4}; if isnan(unitmultiplier), unitmultiplier=1; end
+end
+
+domain=expread(domainoutline);
+
+figure(figurenumber),hold on
+for i=1:length(domain),
+	if (isnumeric(linestyle))
+		plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,'Color',linestyle,'linewidth',linewidth);
+	else
+		plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,linestyle,'linewidth',linewidth);
+	end
+end
Index: /issm/trunk/src/m/exp/expexcludeoutliers.m
===================================================================
--- /issm/trunk/src/m/exp/expexcludeoutliers.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expexcludeoutliers.m	(revision 13395)
@@ -0,0 +1,19 @@
+function excludeoutliers(newcontourname,contourname,domainname)
+%EXCLUDEOUTLIERS - exclude points of contour that are not within the domain
+%contour. return new contours in a different file.
+%
+%        Usage: excludeoutliers('NewContour.exp','Contour.exp','DomainOutline.exp');
+%
+%
+%   See also EXPMASTER, EXPDOC
+
+
+contour=expread(contourname);
+
+for i=1:length(contour),
+	flags=ContourToNodes(contour(i).x,contour(i).y,domainname,0);
+	contour(i).x=contour(i).x(find(flags));
+	contour(i).y=contour(i).y(find(flags));
+end
+
+expwrite(contour,newcontourname);
Index: /issm/trunk/src/m/exp/expflip.m
===================================================================
--- /issm/trunk/src/m/exp/expflip.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expflip.m	(revision 13395)
@@ -0,0 +1,19 @@
+function expflip(domainname)
+%EXPFLIP: flip orientation of all contours and domains in domainname exp file.
+%
+%Usage: expflip('MassFlux1.exp');a
+%
+%
+
+
+
+
+
+a=expread(domainname,1);
+
+for i=1:length(a),
+	a(i).x=flipud(a(i).x);
+	a(i).y=flipud(a(i).y);
+end
+
+expwrite(a,domainname);
Index: /issm/trunk/src/m/exp/explink.m
===================================================================
--- /issm/trunk/src/m/exp/explink.m	(revision 13395)
+++ /issm/trunk/src/m/exp/explink.m	(revision 13395)
@@ -0,0 +1,28 @@
+function explink(domainoutline,minthreshold,step)
+%EXPLINK - allow to link several segments of domain outline together
+%
+%   Takes a domain outline made of various segments, and links them together in one 
+%   domain outline. Use expview to see end result.
+%
+%   Usage:
+%      explink(domainoutline,minthreshold,step)
+%
+%   See also EXPMASTER, EXPDOC
+
+notdone=1;
+
+while notdone,
+
+	for i=1:1000,
+		status=expconcatenate(domainoutline,minthreshold+(i-1)*step);
+		if status==0,
+			return;
+		end
+		if status==1,
+			break;
+		end
+		if status==-1,
+			continue;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/expll2xy.m
===================================================================
--- /issm/trunk/src/m/exp/expll2xy.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expll2xy.m	(revision 13395)
@@ -0,0 +1,37 @@
+function expll2xy(filename,sgn,central_meridian,standard_parallel)  
+%EXPLL2XY: switch exp argus file from lat,long to x,y
+%   Usage:
+%      expll2xy(filename,sgn,central_meridian,standard_parallel)
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==4,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==2
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help expll2xy
+	error('bad usage');
+end
+
+%read filename: 
+domain=expread(filename);
+
+%change to x,y: 
+for i=1:length(domain),
+	[domain(i).x domain(i).y]= ll2xy(domain(i).y,domain(i).x,sgn,delta,slat);
+end
+
+%write back to filename: 
+expwrite(domain,filename);
Index: /issm/trunk/src/m/exp/expread.m
===================================================================
--- /issm/trunk/src/m/exp/expread.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expread.m	(revision 13395)
@@ -0,0 +1,81 @@
+function Struct=expread(filename);
+%EXPREAD - read a file exp and build a Structure
+%
+%   This routine reads a file .exp and build a Structure containing the 
+%   fields x and y corresponding to the coordinates, one for the filename of
+%   the exp file, for the density, for the nodes, and a field closed to 
+%   indicate if the domain is closed. 
+%   The first argument is the .exp file to be read and the second one (optional) 
+%   indicate if the last point shall be read (1 to read it, 0 not to).
+%
+%   Usage:
+%      Struct=expread(filename)
+%
+%   Example:
+%      Struct=expread('domainoutline.exp')
+%      Struct=expread('domainoutline.exp')
+%
+%   See also EXPDOC, EXPWRITEASVERTICES
+
+%some checks
+if ~exist(filename),
+	error(['expread error message: file ' filename ' not found!']);
+end
+
+%initialize number of profile
+count=0;
+
+%open file
+fid=fopen(filename,'r');
+
+%loop over the number of profiles
+while (~feof(fid)),
+
+	%update number of profiles
+	count=count+1;
+
+	%Get file name
+	A=fscanf(fid,'%s %s',2);
+	if ~strncmp(A,'##Name:',7), break; end
+	if length(A)>7, 
+		Struct(count).name=A(8:end);
+	else
+		Struct(count).name='';
+	end
+
+	%Get Icon
+	A=fscanf(fid,'%s %s',2);
+	if ~strncmp(A,'##Icon:',7), break; end
+
+	%Get Info
+	A=fscanf(fid,'%s %s %s %s',4);
+	if ~strncmp(A,'#Points',7), break; end
+
+	%Get number of nodes and density
+	A=fscanf(fid,'%f %f',[1 2]);
+	Struct(count).nods=A(1);
+	Struct(count).density=A(2);
+
+	%Get Info
+	A=fscanf(fid,'%s %s %s %s',5);
+	if ~strncmp(A,'#XposYpos',9), break; end
+
+	%Get Coordinates
+	A=fscanf(fid,'%f %f',[2 Struct(count).nods]);
+	Struct(count).x=A(1,:)';
+	Struct(count).y=A(2,:)';
+
+	if(Struct(count).nods~=length(Struct(count).x))error(['Profile ' num2str(count) ' reports incorrect length']); end;
+
+	%Check if closed
+	if (Struct(count).nods > 1) && ...
+	   (Struct(count).x(end) == Struct(count).x(1)) && ...
+	   (Struct(count).y(end) == Struct(count).y(1))
+		Struct(count).closed=true;
+	else
+		Struct(count).closed=false;
+	end
+end
+
+%close file
+fclose(fid);
Index: /issm/trunk/src/m/exp/expread.py
===================================================================
--- /issm/trunk/src/m/exp/expread.py	(revision 13395)
+++ /issm/trunk/src/m/exp/expread.py	(revision 13395)
@@ -0,0 +1,100 @@
+import os.path
+import numpy
+from collections import OrderedDict
+from MatlabFuncs import *
+
+def expread(filename):
+	"""
+	EXPREAD - read a file exp and build a Structure
+
+	   This routine reads a file .exp and build a Structure containing the 
+	   fields x and y corresponding to the coordinates, one for the filename of
+	   the exp file, for the density, for the nodes, and a field closed to 
+	   indicate if the domain is closed. 
+	   The first argument is the .exp file to be read and the second one (optional) 
+	   indicate if the last point shall be read (1 to read it, 0 not to).
+
+	   Usage:
+	      contours=expread(filename)
+
+	   Example:
+	      contours=expread('domainoutline.exp')
+	      contours=expread('domainoutline.exp')
+
+	   See also EXPDOC, EXPWRITEASVERTICES
+	"""
+
+	#some checks
+	if not os.path.exists(filename):
+		raise OSError("expread error message: file '%s' not found!" % filename)
+
+	#initialize number of profile
+	contours=[]
+
+	#open file
+	fid=open(filename,'r')
+
+	#loop over the number of profiles
+	while True:
+
+		#update number of profiles
+		contour=OrderedDict()
+
+		#Get file name
+		A=fid.readline()
+		while A=='\n':
+			A=fid.readline()
+		if not A:
+			break
+		A=A.split(None,1)
+		if not (len(A) == 2 and strcmp(A[0],'##') and strncmp(A[1],'Name:',5)):
+			break
+		if len(A[1])>5: 
+			contour['name']=A[1][5:-1]
+		else:
+			contour['name']=''
+
+		#Get Icon
+		A=fid.readline().split(None,1)
+		if not (len(A) == 2 and strcmp(A[0],'##') and strncmp(A[1],'Icon:',5)):
+			break
+
+		#Get Info
+		A=fid.readline().split()
+		if not (len(A) == 4 and strcmp(A[0],'#') and strcmp(A[1],'Points')):
+			break
+
+		#Get number of nodes and density
+		A=fid.readline().split()
+		contour['nods']   =float(A[0])
+		contour['density']=float(A[1])
+
+		#Get Info
+		A=fid.readline().split()
+		if not (len(A) == 5 and strcmp(A[0],'#') and strcmp(A[1],'X') and strcmp(A[2],'pos') \
+		                                         and strcmp(A[3],'Y') and strcmp(A[4],'pos')):
+			break
+
+		#Get Coordinates
+		contour['x']=numpy.empty(contour['nods'])
+		contour['y']=numpy.empty(contour['nods'])
+		for i in xrange(int(contour['nods'])):
+			A=fid.readline().split()
+			contour['x'][i]=float(A[0])
+			contour['y'][i]=float(A[1])
+
+		#Check if closed
+		if (contour['nods'] > 1) and \
+		   (contour['x'][-1] == contour['x'][0]) and \
+		   (contour['y'][-1] == contour['y'][0]):
+			contour['closed']=True
+		else:
+			contour['closed']=False
+
+		contours.append(contour)
+
+	#close file
+	fid.close()
+
+	return contours
+
Index: /issm/trunk/src/m/exp/expsquare.m
===================================================================
--- /issm/trunk/src/m/exp/expsquare.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expsquare.m	(revision 13395)
@@ -0,0 +1,45 @@
+function expsquare(filename)
+%EXPBOX - Create a ARGUS file using to clicks
+%
+%   Two clicks on a plot are used to generate a square box
+%   This box is written in EXP format on filename
+%
+%   Usage:
+%      expbox(filename)
+
+%check
+if exist(filename,'file'),
+	choice=input(['A file ' filename ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return
+	end
+end
+
+%Get points
+disp('Click twice to define a square domain. First click for upper left corner, second for lower right corner');
+[x,y]=ginput(2);
+
+xmiddle=mean(x);
+ymiddle=mean(y);
+
+x1=x(1); y1=y(1);
+x3=x(2); y3=y(2);
+
+Diag=[x1-xmiddle;y1-ymiddle];
+
+Vector=[xmiddle;ymiddle]+[-Diag(2);Diag(1)];
+x2=Vector(1); y2=Vector(2);
+
+Vector=[xmiddle;ymiddle]-[-Diag(2);Diag(1)];
+x4=Vector(1); y4=Vector(2);
+
+%Build Exp structure
+A=struct();
+A.nods=5;
+A.density=1;
+A.x=[x1 x2 x3 x4 x1]';
+A.y=[y1 y2 y3 y4 y1]';
+
+%Write structure
+expwrite(A,filename);
Index: /issm/trunk/src/m/exp/expswapxy.m
===================================================================
--- /issm/trunk/src/m/exp/expswapxy.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expswapxy.m	(revision 13395)
@@ -0,0 +1,23 @@
+function expswapxy(filename)
+%EXPSWAP - swap x and y fields
+% 
+%   Usage:
+%      expswap(file)
+%
+%   See also EXPMASTER, EXPDOC
+
+
+contours=expread(filename,1);
+
+newcontours=contours(1);
+
+for i=1:length(contours), 
+	contour=contours(i);
+	newcontour=contour;
+	newcontour.x=contour.y;
+	newcontour.y=contour.x;
+	newcontours(end+1)=newcontour;
+end
+newcontours=newcontours(2:end);
+
+expwrite(newcontours,filename);
Index: /issm/trunk/src/m/exp/exptool.m
===================================================================
--- /issm/trunk/src/m/exp/exptool.m	(revision 13395)
+++ /issm/trunk/src/m/exp/exptool.m	(revision 13395)
@@ -0,0 +1,351 @@
+function exptool(newfile,varargin)
+%EXPMASTER - allow to create, modify, add, cut, .. segments of domain outline together
+%
+%   this routine is used to create, modify, cut,... an Argus file (.exp)
+%
+%   exptool(newprofile,'optionname',optionvalue)
+%      creation of an argus file newprofile
+%
+%   Available options:
+%      - include: include list of existing ARGUS files
+%      - color: line color (default='r')
+%      - selectioncolor: line color of selected profiles (default='b')
+%      - linestyle (default='-')
+%      - linewidth (default=0.2)
+%      - marker (default='+')
+%      - markersize (default=7)
+%      - markeredgecolor (default='r')
+%
+%   Usage:
+%      exptool(newfile,varargin)
+%
+%   Example:
+%      exptool('domain.exp','include',{'domain1.exp' 'domain2.exp'},'color','g','marker','+')
+%
+%   See also EXPDOC
+
+%recover options
+options=pairoptions(varargin{:});
+
+%Some checks
+if ~nargin | nargout
+	error('exptool usage: exptool(newfile,varargin)')
+elseif exist(newfile,'file'),
+	%recursive call to exptool if file already exists
+	if ~exist(options,'include'),
+		exptool(newfile,'include',newfile,varargin{:});
+		return;
+	end
+
+	%check modification
+	choice=input(['A file ' newfile ' already exists, do you want to modify it? (y/n)'],'s');
+	if ~strcmpi(choice,'y'),
+		disp('no modification done ... exiting');
+		return
+	end
+end
+
+%Add default options
+options=addfielddefault(options,'color','r');
+options=addfielddefault(options,'selectioncolor','b');
+options=addfielddefault(options,'LineStyle','-');
+options=addfielddefault(options,'LineWidth',0.2);
+options=addfielddefault(options,'Marker','+');
+options=addfielddefault(options,'MarkerSize',7);
+options=addfielddefault(options,'MarkerEdgeColor','r');
+
+%put all the argus profiles given in input in one structure A
+A=struct([]);
+numprofiles=0;
+numpoints=0;
+closed=[];
+
+%initialize the variables with files provided by 'include' option
+if exist(options,'include'),
+	files=getfieldvalue(options,'include');
+	if ischar(files), files={files}; end
+	for i=1:length(files),
+		filename=files{i};
+		if ~exist(filename,'file'),
+			error(['exptool error message:, ' filename ' does not exist. Exiting...']);
+		else
+			%read file
+			B=expread(filename);
+			%go through all profiles of B
+			for i=1:size(B,2)
+				%plug profile in A
+				if numprofiles
+					A(numprofiles+1)=B(i);
+				else
+					A=B(i);
+				end
+				%update numprofiles and numpoints
+				numpoints=numpoints+length(B(i).x);
+				numprofiles=numprofiles+1;
+				%figure out if the profile is closed or not
+				if (B(i).x(1)==B(i).x(end) & B(i).y(1)==B(i).y(end) & length(B(i).x)>1 )
+					closed(numprofiles)=1;
+				else
+					closed(numprofiles)=0;
+				end
+			end
+		end
+	end
+end
+
+%Get root of newfile
+[path root ext]=fileparts(newfile);
+
+%get current figure
+if ~isempty(get(0,'children')),%if there is already a figure (return the number of opened figures)
+	set(gcf,'Renderer','zbuffer'); %fixes a bug on Mac OS X (not needed in future Matlab version)
+	P=get(gcf,'position');
+	F=getframe(gca);
+	F=F.cdata;
+	%get current axis
+	xlim=get(gca,'Xlim');
+	ylim=get(gca,'Ylim');
+	%recreate x_m and y_m
+	x_m=linspace(xlim(1),xlim(2),size(F,2));
+	y_m=linspace(ylim(2),ylim(1),size(F,1)); %getframe reverse axis...
+	%plot the data in another figure
+	figure; set(gcf,'position',P);
+	imagesc(x_m,y_m,F); set(gca,'Ydir','normal');
+	prevplot=1;
+	prevplot2=1;
+else
+	figure
+	prevplot=0;
+	prevplot2=0;
+end
+
+%plot existing profile if any
+hold on
+
+%Build backup structre for do and redo
+backup=cell(1,3);
+backup{1,1}=A;
+backup{1,2}=numprofiles;
+backup{1,3}=numpoints;
+backup{1,4}=closed;
+
+loop=1;
+counter=1;
+while loop
+
+	%Go through A and rule out the empty profiles
+	list=[];
+	for i=1:size(A,2);
+		if length(A(i).x)==0
+			list(end+1)=i;
+			numprofiles=numprofiles-1;
+		end
+	end
+	A(list)=[];
+	closed(list)=[];
+
+	%Now erase all that have been done and plot the new structure A as it is
+	undoplots(prevplot);
+	if numprofiles
+		prevplot2=1;
+		for i=1:numprofiles
+			if length(A(i).x)==1,
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+					'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker','o');
+			else
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+			prevplot2=prevplot2+1;
+		end
+	end
+
+	%display menu
+	title('Main Menu','FontSize',14);
+   UIControl_FontSize_bak = get(0, 'DefaultUIControlFontSize');
+   set(0, 'DefaultUIControlFontSize',10);
+   button=menu('exptool menu',...
+      'add a profile (open)',...                %1
+      'add a contour (closed)',...              %2
+      'remove a profile',...                    %3
+      'modify the position of a point',...      %4
+      'add points inside a profile',...         %5
+      'add points at the end of a profile',...  %6
+      'remove points',...                       %7
+      'remove several points',...               %8
+      'cut a segment',...                       %9
+      'cut a large area',...                    %10
+      'merge profiles',...                      %11
+      'close profile',...                       %12
+		'change orientation',...                  %13
+      'undo',...                                %14
+      'redo',...                                %15
+      'quit');                                  %16
+   set(0, 'DefaultUIControlFontSize', UIControl_FontSize_bak);
+
+	%UNDO??
+	if button==14;
+		if counter==1
+			disp('Already at oldest change');
+		else
+			counter=counter-1;
+			A=backup{counter,1};
+			numprofiles=backup{counter,2};
+			numpoints=backup{counter,3};
+			closed=backup{counter,4};
+		end
+	%REDO??
+	elseif button==15
+		if counter==size(backup,1)
+			disp('Already at newest change');
+		else
+			counter=counter+1;
+			A=backup{counter,1};
+			numprofiles=backup{counter,2};
+			numpoints=backup{counter,3};
+			closed=backup{counter,4};
+		end
+	end
+
+	switch button
+
+		case 1
+
+			[A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot2,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 2
+
+			[A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot2,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 3
+
+			[A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot2,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 4
+
+			[A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 5
+
+			[A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 6
+
+			[A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot2,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 7
+
+			[A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 8
+
+			[A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 9
+
+			[A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 10
+
+			[A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 11
+
+			[A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+
+		case 12
+
+			[A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+		case 13
+
+			[A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+			counter=counter+1;
+			backup{counter,1}=A;
+			backup{counter,2}=numprofiles;
+			backup{counter,3}=numpoints;
+			backup{counter,4}=closed;
+
+			%QUIT
+		case 16
+
+			loop=0;
+
+		otherwise
+			%do nothing
+	end
+
+end
+
+hold off
+
+%write contour using expwrite
+title('New file written, exiting...','FontSize',14);
+if isempty(A)
+	disp('Profile empty, no file written')
+else
+	expwrite(A,newfile);
+end
+
+%close window
+close;
Index: /issm/trunk/src/m/exp/expwrite.m
===================================================================
--- /issm/trunk/src/m/exp/expwrite.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expwrite.m	(revision 13395)
@@ -0,0 +1,41 @@
+function expwrite(a,filename);
+%EXPWRITE - write an Argus file from a structure given in input
+%
+%   This routine write an Argus file form a structure containing the fields:
+%   x and y of the coordinates of the points.
+%   The first argument is the structure containing the points coordinates 
+%   and the second one the file to be write.
+%
+%   Usage:
+%      expwrite(a,filename)
+% 
+%   Example:
+%      expwrite(coordstruct,'domainoutline.exp')
+%
+%   See also EXPDOC, EXPREAD, EXPWRITEASVERTICES
+
+fid=fopen(filename,'w');
+for n=1:length(a),
+	if(length(a(n).x)~=length(a(n).y)),
+		error('contours x and y coordinates must be of identical size');
+	end
+   
+	if isfield(a,'name'),
+		if ~isempty(a(n).name),
+			fprintf(fid,'%s%s\n','## Name:',a(n).name);
+		else
+			fprintf(fid,'%s\n','## Name:');
+		end
+	else
+		fprintf(fid,'%s\n','## Name:');
+	end
+   
+	fprintf(fid,'%s\n','## Icon:0');
+	fprintf(fid,'%s\n','# Points Count Value');
+	fprintf(fid,'%i %f\n',[length(a(n).x) a(n).density]);
+	fprintf(fid,'%s\n','# X pos Y pos');
+	fprintf(fid,'%10.10f %10.10f\n',[a(n).x a(n).y]');
+	fprintf(fid,'\n');
+
+end
+fclose(fid);
Index: /issm/trunk/src/m/exp/expwrite.py
===================================================================
--- /issm/trunk/src/m/exp/expwrite.py	(revision 13395)
+++ /issm/trunk/src/m/exp/expwrite.py	(revision 13395)
@@ -0,0 +1,43 @@
+import numpy
+
+def expwrite(contours,filename):
+	"""
+	EXPWRITE - write an Argus file from a structure given in input
+
+	   This routine write an Argus file form a structure containing the fields:
+	   x and y of the coordinates of the points.
+	   The first argument is the structure containing the points coordinates 
+	   and the second one the file to be write.
+
+	   Usage:
+	      expwrite(contours,filename)
+
+	   Example:
+	      expwrite(coordstruct,'domainoutline.exp')
+
+	   See also EXPDOC, EXPREAD, EXPWRITEASVERTICES
+	"""
+
+	fid=open(filename,'w')
+	for contour in contours:
+		if numpy.size(contour['x'])!=numpy.size(contour['y']):
+			raise RuntimeError("contours x and y coordinates must be of identical size")
+   
+		if 'name' in contour:
+			if contour['name']:
+				fid.write("%s%s\n" % ('## Name:',contour['name']))
+			else:
+				fid.write("%s\n" % '## Name:')
+		else:
+			fid.write("%s\n" % '## Name:')
+   
+		fid.write("%s\n" % '## Icon:0')
+		fid.write("%s\n" % '# Points Count Value')
+		fid.write("%i %f\n" % (numpy.size(contour['x']),contour['density']))
+		fid.write("%s\n" % '# X pos Y pos')
+		for x,y in zip(contour['x'],contour['y']):
+			fid.write("%10.10f %10.10f\n" % (x,y))
+		fid.write("\n")
+
+	fid.close()
+
Index: /issm/trunk/src/m/exp/expxy2ll.m
===================================================================
--- /issm/trunk/src/m/exp/expxy2ll.m	(revision 13395)
+++ /issm/trunk/src/m/exp/expxy2ll.m	(revision 13395)
@@ -0,0 +1,37 @@
+function expxy2ll(filename,sgn,central_meridian,standard_parallel)  
+%EXPLL2XY: switch exp argus file from lat,long to x,y
+%   Usage:
+%      expxy2ll(filename,sgn,central_meridian,standard_parallel)
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==4,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==2
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help expxy2ll
+	error('bad usage');
+end
+
+%read filename: 
+domain=expread(filename);
+
+%change to x,y: 
+for i=1:length(domain),
+	[domain(i).y domain(i).x]= xy2ll(domain(i).x,domain(i).y,sgn,delta,slat); %watch out to swap lat and long
+end
+
+%write back to filename: 
+expwrite(domain,filename);
Index: /issm/trunk/src/m/exp/flowlines.m
===================================================================
--- /issm/trunk/src/m/exp/flowlines.m	(revision 13395)
+++ /issm/trunk/src/m/exp/flowlines.m	(revision 13395)
@@ -0,0 +1,163 @@
+function flowpath=flowlines(index,x,y,u,v,x0,y0,varargin)
+%FLOWLINES - compute flowlines from a given set of seed points
+%
+%   Usage:
+%      flowpath=flowlines(index,x,y,u,v,x0,y0)
+%
+%   the velocity field is given by the couple (u,v) and the coordinates
+%   of the seed points are (x0,y0). One can use one or several seed 
+%   points
+%
+%   Example:
+%      flowpath=flowlines(md.mesh.elements,md.mesh.x,md.mesh.y,md.vx,md.initialization.vy,x0,y0)
+
+%check input size
+if nargin>8 | nargin<7,
+	help flowlines
+	error('flowlines error message: bad usage');
+end
+
+%check input
+if (length(x)~=length(y) | length(x)~=length(u) | length(x)~=length(v)),
+	error('flowlines error message: x,y,u and v must have the same length');
+end
+if length(x)<3,
+	error('flowlines error message: at least one element is required');
+end
+if length(x0)~=length(y0),
+	error('flowlines error message: x0 and y0 do not have the same length');
+end
+
+%get maxiter and precision
+if nargin==8
+	maxiter=varargin{1};
+else
+	maxiter=200; %maximum number of iterations
+end
+precision=1; %division of each segment (higer precision increases number of segments)
+
+%check seed points
+tria=TriaSearch(index,x,y,x0,y0);
+pos=find(isnan(tria));
+x0(pos)=[];
+y0(pos)=[];
+
+%initialize other variables
+N=length(x0);
+X=x0; Y=y0;
+flowpath=struct('x',cell(N,1),'y',cell(N,1),'name','','density',1);
+for i=1:N,
+	flowpath(i).x=x0(i);
+	flowpath(i).y=y0(i);
+end
+done=zeros(N,1);
+
+%get avegared length of each element
+length_tria=1/3*(sqrt( (x(index(:,1))-x(index(:,2))).^2+(y(index(:,1))-y(index(:,2))).^2 )+...
+	sqrt((x(index(:,1))-x(index(:,3))).^2+(y(index(:,1))-y(index(:,3))).^2 )+...
+	sqrt((x(index(:,2))-x(index(:,3))).^2+(y(index(:,2))-y(index(:,3))).^2 ));
+
+%take velocity for each element
+u=u(index)*[1;1;1]/3;
+v=v(index)*[1;1;1]/3;
+
+%initialization:
+counter=1;
+
+while any(~done) 
+
+	%find current triangle
+	queue=find(~done);
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+
+	%check that the point is actually inside a triangle of the mesh
+	listnan=find(isnan(tria));
+	for i=1:length(listnan)
+		%remove the last point
+		flowpath(queue(listnan(i))).x(end)=[];
+		flowpath(queue(listnan(i))).y(end)=[];
+		done(queue(listnan(i)))=1;
+	end
+	tria(listnan)=[]; 
+	queue(listnan)=[];
+
+	if isempty(tria),
+		break;
+	end
+
+	%velocity of the current triangle and norm it
+	ut=u(tria); vt=v(tria); normv=sqrt(ut.^2+vt.^2);
+	ut=ut./normv;vt=vt./normv;
+
+	%check counter
+	if counter>maxiter
+		disp(['Maximum number of iterations (' num2str(maxiter) ') reached while going forward'])
+		break
+	end
+	counter=counter+1;
+
+	%remove stagnant point
+	done(queue(find(ut==0 & vt==0)))=1;
+
+	%build next point
+	for i=1:length(queue)
+		X(queue(i))=flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision;
+		Y(queue(i))=flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision;
+		flowpath(queue(i)).x=[flowpath(queue(i)).x;flowpath(queue(i)).x(end)+ut(i)*length_tria(tria(i))/precision];
+		flowpath(queue(i)).y=[flowpath(queue(i)).y;flowpath(queue(i)).y(end)+vt(i)*length_tria(tria(i))/precision];
+	end
+end
+
+%same process but reverse (vel=-vel) to have a vcomplete flow line
+counter=1;
+X=x0; Y=y0;
+done=zeros(N,1);
+
+while any(~done) 
+
+	%find current triangle
+	queue=find(~done);
+	tria=TriaSearch(index,x,y,X(queue),Y(queue));
+
+	%check that the point is actually inside a triangle of the mesh
+	listnan=find(isnan(tria));
+	for i=1:length(listnan)
+		%remove the last point
+		flowpath(queue(listnan(i))).x(1)=[];
+		flowpath(queue(listnan(i))).y(1)=[];
+		done(queue(listnan(i)))=1;
+	end
+	tria(listnan)=[]; 
+	queue(listnan)=[];
+
+	if isempty(tria),
+		break;
+	end
+
+	%velocity of the current triangle and norm it
+	ut=-u(tria); vt=-v(tria); normv=sqrt(ut.^2+vt.^2);
+	ut=ut./normv;vt=vt./normv;
+
+	%check counter
+	if counter>maxiter
+		disp(['Maximum number of iterations (' num2str(maxiter) ') reached while going backward'])
+		break
+	end
+	counter=counter+1;
+
+	%remove stagnant point
+	done(queue(find(ut==0 & vt==0)))=1;
+
+	%build next point
+	for i=1:length(queue)
+		X(queue(i))=flowpath(queue(i)).x(1)+ut(i)*length_tria(tria(i))/precision;
+		Y(queue(i))=flowpath(queue(i)).y(1)+vt(i)*length_tria(tria(i))/precision;
+		flowpath(queue(i)).x=[flowpath(queue(i)).x(1)+ut(i)*length_tria(tria(i))/precision; flowpath(queue(i)).x];
+		flowpath(queue(i)).y=[flowpath(queue(i)).y(1)+vt(i)*length_tria(tria(i))/precision; flowpath(queue(i)).y];
+	end
+end
+
+%EXP compatibility
+for i=1:length(queue)
+	flowpath(queue(i)).name=['flowline' num2str(i)];
+end
Index: /issm/trunk/src/m/exp/manipulation/addcontour.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/addcontour.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/addcontour.m	(revision 13395)
@@ -0,0 +1,50 @@
+function [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ADDCONTOUR - add a closed contour
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options)
+		   
+	title('click to add a point to the new profile, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	x=[];
+	y=[];
+
+	while loop
+
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				x(end+1)=x(1);
+				y(end+1)=y(1);
+				A(end+1).x=x; 
+				A(end).y=y; 
+				A(end).name=root; 
+				A(end).density=1; 
+				numprofiles=numprofiles+1;
+				numpoints=numpoints+length(x);
+				closed(end+1)=1;
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/addendprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/addendprofile.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/addendprofile.m	(revision 13395)
@@ -0,0 +1,86 @@
+function [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ADDENDPROFILE - add point at the end of a n existing profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if ~any(~closed)
+		disp('all profiles are closed')
+		return
+	end	   
+	%select a profile first
+	if numprofiles>1
+		%first step, select a profile
+		isclosed=1;
+		title('click on a profile, RETURN to exit','FontSize',14)
+		while isclosed
+			[xi,yi] = ginput(1);
+			if ~isempty(xi)
+				%get the closest point 
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if closed(profsel)
+					disp('selected profile is closed, make another selection')
+				else
+					isclosed=0;
+				end
+
+			else
+				%RETURN -> out
+				return
+			end
+		end
+	else
+		profsel=1;
+	end
+
+	%initialize x and y
+	x=A(profsel).x;
+	y=A(profsel).y;
+
+	%plot the selected profile
+	hold on
+	plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+		'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+	loop=1;
+	while loop
+
+		%first step, select a profile
+		title('click to add point to the selected profile, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize')+2,'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				A(profsel).x=x; 
+				A(profsel).y=y; 
+				A(profsel).name=root; 
+				A(profsel).density=1; 
+				numpoints=numpoints+length(x);
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/addinsideprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/addinsideprofile.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/addinsideprofile.m	(revision 13395)
@@ -0,0 +1,79 @@
+function [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ADDINSIDEPROFILE - add apoint inside a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<2
+		disp('at least two points are required, exiting...')
+		return
+	end	   
+	hold on
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	loop=1;
+	while loop
+
+		%first step, select a segment
+		title('click on a segment, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		%first click
+		if ~isempty(xi)
+
+			%get the closest segment
+			[profsel indsel]=closestsegment(A,numprofiles,xi,yi);
+
+			%check that at least one segment exists
+			if indsel==0
+				disp('at least two points in one profile are required, exiting...')
+				return
+			end
+
+			%highlight selected segment
+			plot([A(profsel).x(indsel) A(profsel).x(indsel+1)],[A(profsel).y(indsel) A(profsel).y(indsel+1)],...
+				'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+			%next click
+			title('click on the new point''s location, RETURN to exit','FontSize',14)
+			[xi,yi,but] = ginput(1);
+
+			%second click
+			if ~isempty(xi)
+
+				%add point to A
+				A(profsel).x=[A(profsel).x(1:indsel,1); xi; A(profsel).x(indsel+1:end,1)];
+				A(profsel).y=[A(profsel).y(1:indsel,1); yi; A(profsel).y(indsel+1:end,1)];
+				numpoints=numpoints+1;
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+
+			else
+				%RETURN->exit
+				return
+			end
+		else
+			%RETURN-> exit
+			return
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/addprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/addprofile.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/addprofile.m	(revision 13395)
@@ -0,0 +1,48 @@
+function [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ADDPROFILE - add a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+		   
+	title('click to add a point to the new profile, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	x=[];
+	y=[];
+
+	while loop
+
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				A(end+1).x=x; 
+				A(end).y=y; 
+				A(end).name=root; 
+				A(end).density=1; 
+				numprofiles=numprofiles+1;
+				numpoints=numpoints+length(x);
+				closed(end+1)=0;
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/closeprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/closeprofile.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/closeprofile.m	(revision 13395)
@@ -0,0 +1,68 @@
+function [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%CLOSEPROFILE - close one or several profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile to be closed')
+		return
+	end
+		   
+	title('click on the profiles to be closed, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks,
+		if numprofiles==0    
+			disp('no profile present, exiting...')
+			return            
+		end  
+		if ~any(~closed),
+			disp('All the profiles are closed, exiting...')
+			return
+		end
+
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it from the selection
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			elseif closed(profsel),
+				%profile already closed, do nothing
+				disp('selected profile aready closed, make another selection'),
+			else
+				%add the profile to the list to be closed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%close the profiles
+			for i=1:length(selection),
+				A(selection(i)).x(end+1)=A(selection(i)).x(1);
+				A(selection(i)).y(end+1)=A(selection(i)).y(1);
+				numpoints=numpoints+1;
+				closed(selection(i))=1;
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/closestpoint.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/closestpoint.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/closestpoint.m	(revision 13395)
@@ -0,0 +1,21 @@
+function [profsel indsel]=closestpoint(A,numprofiles,xi,yi)
+%CLOSESTPOINT - find the closest point of a profile
+%
+%   This routine find the point of the profile A that is the closest
+%   to (xi,yi) and return the number of the profile and the number of
+%   the point
+%
+%   Usage:
+%     [profsel indsel]=closestpoint(A,numprofiles,xi,yi) 
+
+	%loop over the points of each profile, find the closest to (xi,yi)
+	for i=1:numprofiles,
+		distance=(xi-A(i).x).^2+(yi-A(i).y).^2;
+		[newdistance p]=min(distance);
+		if ((i==1) | (newdistance<olddistance)),
+			indsel=p;
+			profsel=i;
+			olddistance=newdistance;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/closestsegment.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/closestsegment.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/closestsegment.m	(revision 13395)
@@ -0,0 +1,28 @@
+function [profsel indsel]=closestsegment(A,numprofiles,xi,yi)
+%CLOSESTSEGMENT - find the closest segment of a profile
+%
+%   This routine find the segment of the profile A that is the closest
+%   to (xi,yi) and return the number of the profile and the number of
+%   the first point belonging to this closest segment
+%
+%   Usage:
+%     [profsel indsel]=closestsegment(A,numprofiles,xi,yi) 
+
+	%loop over the middles of each profile, find the closest to (xi,yi)
+	profsel=0;
+	indsel=0;
+	first=1;
+	for i=1:numprofiles,
+		if length(A(i).x)>1
+			middles=[(A(i).x(1:end-1)+A(i).x(2:end))/2 (A(i).y(1:end-1)+A(i).y(2:end))/2];
+			distance=(xi-middles(:,1)).^2+(yi-middles(:,2)).^2;
+			[newdistance p]=min(distance);
+			if (first | (newdistance<olddistance)),
+				first=0;
+				indsel=p;
+				profsel=i;
+				olddistance=newdistance;
+			end
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/cutarea.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/cutarea.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/cutarea.m	(revision 13395)
@@ -0,0 +1,156 @@
+function [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options);
+%CUTAREA - cut several point of a profile
+%
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile. The user must click 3 times to select the
+%   area to be removed. Twice to select the tips and one to select
+%   the part of the profile to be removed
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	points=[];
+
+	%loop (at least 3 clicks needed)
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile present, exiting...')
+			return
+		end	   
+		if numpoints<3
+			disp('at least two points are needed, exiting...')
+			return
+		end	   
+
+		%select a point
+		if isempty(points)
+			title('click on the first tip, RETURN to exit','FontSize',14)
+		elseif length(points)==1
+			title('click on the second tip, RETURN to exit','FontSize',14)
+		else
+			title('click in the middle of the area to be cut, RETURN to exit','FontSize',14)
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			%get the closest point
+			%first time, look at all profiles
+			if isempty(points)
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if ((closed(profsel) & length(A(profsel).x)<4) |  (~closed(profsel) & length(A(profsel).x)<3)),
+					disp('the selected profile has less than 3 points, make another selection');
+				else
+					selection=profsel;
+					points(end+1)=indsel;
+					plot(A(profsel).x,A(profsel).y,...
+						'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+					text(A(selection).x(indsel),A(selection).y(indsel),num2str(1),'FontSize',14,'background',[0.7 0.7 0.9]);
+				end
+			else
+				%get the 2d or 3d point for the given contou
+				[profsel indsel]=closestpoint(A(selection),1,xi,yi);
+				if ismember(indsel,points)
+					disp('the selected points must be distinct')
+				else
+					%second click?
+					if length(points)==1,
+						points(end+1)=indsel;
+						text(A(selection).x(indsel),A(selection).y(indsel),num2str(2),'FontSize',14,'background',[0.7 0.7 0.9]);
+					%third click?
+					else
+						p1=points(1); p2=points(2); p3=indsel;
+						x=A(selection).x; y=A(selection).y;
+						if p1<p2
+							if p3>p1 & p3<p2
+								if closed(selection)
+									%open the profile
+									n=length(A(selection).x);
+									A(selection).x=[A(selection).x(p2:end-1,1);A(selection).x(1:p1,1)];
+									A(selection).y=[A(selection).y(p2:end-1,1);A(selection).y(1:p1,1)];
+									numpoints=numpoints-(n-length(A(selection).x));
+									closed(selection)=0;
+								else
+									%cut in 2 profiles
+									A(selection).x=x(1:p1);
+									A(selection).y=y(1:p1);
+									closed(selection)=0;
+									A(end+1).x=x(p2:end);
+									A(end).y=y(p2:end);
+									A(end).density=A(selection).density;
+									A(end).name=A(selection).name;
+									closed(end+1)=0;
+									numprofiles=numprofiles+1;
+									numpoints=numpoints-(p2-p1-1);
+								end
+							else
+								%only point removal
+								n=length(A(selection).x);
+								A(selection).x=x(p1:p2);
+								A(selection).y=y(p1:p2);
+								numpoints=numpoints-(n-length(A(selection).x));
+								closed(selection)=0;
+							end
+						else
+							if p3>p2 & p3<p1
+								if closed(selection)
+									%open the profile
+									n=length(A(selection).x);
+									A(selection).x=[A(selection).x(p1:end-1,1);A(selection).x(1:p2,1)];
+									A(selection).y=[A(selection).y(p1:end-1,1);A(selection).y(1:p2,1)];
+									numpoints=numpoints-(n-length(A(selection).x));
+									closed(selection)=0;
+								else
+									%cut in 2 profiles
+									closed(selection)=0;
+									A(selection).x=x(1:p2);
+									A(selection).y=y(1:p2);
+									A(end+1).x=x(p1:end);
+									A(end).y=y(p1:end);
+									A(end).density=A(selection).density;
+									A(end).name=A(selection).name;
+									closed(end+1)=0;
+									numprofiles=numprofiles+1;
+									numpoints=numpoints-(p1-p2-1);
+								end
+							else
+								%only point removal
+								n=length(A(selection).x);
+								x(1:p2-1)=[];x(p1-p2+2:end)=[];%it should have been x(p2+1:end)
+								y(1:p2-1)=[];y(p1-p2+2:end)=[];
+								A(selection).x=x;
+								A(selection).y=y;
+								numpoints=numpoints-(n-length(A(selection).x));
+								closed(selection)=0;
+							end
+						end
+
+						%plot new profile
+						undoplots(prevplot);
+						for i=1:numprofiles
+							plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+								'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+						end
+						points=[];
+
+					end
+				end
+			end
+		else
+			%RETRUN-> quit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/cutprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/cutprofile.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/cutprofile.m	(revision 13395)
@@ -0,0 +1,79 @@
+function [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%CUTPROFILE - cut a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<2
+		disp('at least two points are needed')
+		return
+	end	   
+	hold on
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	loop=1;
+	while loop
+
+		%select a segment
+		title('click the segment to cut, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest segment
+			[profsel indsel]=closestsegment(A,numprofiles,xi,yi);
+
+			%check that at least one segment exists
+			if indsel==0
+				disp('at least 2 points are required');
+				return,
+			end
+
+			if ((closed(profsel) & length(A(profsel).x)<3) | (~closed(profsel) & length(A(profsel).x)<2))
+				disp('at least 2 points are required, make another selection');
+			else
+				%cut A
+				if closed(profsel)
+					%open the contour
+					A(profsel).x=[A(profsel).x(indsel+1:end-1,1);A(profsel).x(1:indsel,1)];
+					A(profsel).y=[A(profsel).y(indsel+1:end-1,1);A(profsel).y(1:indsel,1)];
+					numpoints=numpoints-1;
+					closed(profsel)=0;
+				else
+					%cut the contour in 2 profiles
+					A(end+1).x=A(profsel).x(indsel+1:end,1);
+					A(end).y=A(profsel).y(indsel+1:end,1);
+					A(end).name=root; 
+					A(end).density=1; 
+					A(profsel).x=A(profsel).x(1:indsel,1);
+					A(profsel).y=A(profsel).y(1:indsel,1);
+					numprofiles=numprofiles+1;
+					closed(end+1)=0;
+				end
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+			end
+		else
+			%RETURN->exit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/mergeprofiles.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/mergeprofiles.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/mergeprofiles.m	(revision 13395)
@@ -0,0 +1,152 @@
+function [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options);
+%MERGEPROFILES - merge profiles
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile. The user must select the two tips that
+%   he/she wants to merge
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+hold on
+loop=1;
+
+%Take all the tips coordinates of open profiles
+counter=1; tips=[];
+for i=1:numprofiles
+	if ~closed(i),
+		%x and y coord, profile number, 1 if beginning, 2 and if end
+		if length(A(i).x)==1,
+			tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+			counter=counter+1;
+		else
+			tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+			tips(counter+1,:) = [A(i).x(end) A(i).y(end) i  2];
+			counter=counter+2;
+		end
+	end
+end
+
+if size(tips,1)<2
+	disp('at least one unclosed profile is required')
+	return
+end
+
+%plot the tips only
+plot(tips(:,1),tips(:,2),...
+	'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+firsttip=1;
+
+%loop (at least 2 clicks needed)
+while loop
+
+	%some checks
+	if size(tips,1)<2
+		disp('at least one unclosed profiles are required')
+		return
+	end
+
+	%select a point
+	if firsttip
+		title('click on the first tip, RETURN to exit','FontSize',14)
+	else
+		title('click on the second tip, RETURN to exit','FontSize',14)
+	end
+
+	[xi,yi] = ginput(1);
+
+	if ~isempty(xi)
+
+		if firsttip
+			%find the selected tip
+			distance=(xi-tips(:,1)).^2+(yi-tips(:,2)).^2;
+			[dmin tip1]=min(distance);
+			numprofile1=tips(tip1,3);
+			firsttip=0;
+
+			%remove tip1 from tips list
+			newtips=tips;
+			newtips(tip1,:)=[];
+
+			%plot selected tip
+			plot(tips(tip1,1),tips(tip1,2),...
+				'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(A(numprofile1).x,A(numprofile1).y,...
+				'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+
+		%second selection
+		else
+			distance=(xi-newtips(:,1)).^2+(yi-newtips(:,2)).^2;
+			[dmin tip2]=min(distance);
+			numprofile2=newtips(tip2,3);
+
+			if numprofile1==numprofile2
+				%close the profile
+				A(numprofile1).x(end+1)=A(numprofile1).x(1);
+				A(numprofile1).y(end+1)=A(numprofile1).y(1);
+				numpoints=numpoints+1;
+				closed(numprofile1)=1;
+
+			else
+
+				if tips(tip1,4)==1 & newtips(tip2,4)==1,
+					A(numprofile1).x=[flipud(A(numprofile2).x); A(numprofile1).x];
+					A(numprofile1).y=[flipud(A(numprofile2).y); A(numprofile1).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==1 & newtips(tip2,4)==2,
+					A(numprofile1).x=[A(numprofile2).x; A(numprofile1).x];
+					A(numprofile1).y=[A(numprofile2).y; A(numprofile1).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==2 & newtips(tip2,4)==1,
+					A(numprofile1).x=[A(numprofile1).x; A(numprofile2).x];
+					A(numprofile1).y=[A(numprofile1).y; A(numprofile2).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==2 & newtips(tip2,4)==2,
+					A(numprofile1).x=[A(numprofile1).x; flipud(A(numprofile2).x)];
+					A(numprofile1).y=[A(numprofile1).y; flipud(A(numprofile2).y)];
+					numprofiles=numprofiles-1;
+				end
+
+				%delete profile2
+				A(numprofile2)=[];
+				closed(numprofile2)=[];
+
+			end
+
+			%update tips
+			counter=1; tips=[];
+			for i=1:numprofiles
+				if ~closed(i),
+					%x and y coord, profile number, 1 if beginning, 2 and if end
+					if length(A(i).x)==1,
+						tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+						counter=counter+1;
+					else
+						tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+						tips(counter+1,:) = [A(i).x(end) A(i).y(end) i  2];
+						counter=counter+2;
+					end
+				end
+			end
+
+			%plot new profile
+			undoplots(prevplot);
+			for i=1:numprofiles
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+			if ~isempty(tips)
+				plot(tips(:,1),tips(:,2),...
+					'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			end
+
+			%back to beginning
+			firsttip=1;
+		end
+	else
+		%RETRUN-> quit
+		loop=0;
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/modifyposition.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/modifyposition.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/modifyposition.m	(revision 13395)
@@ -0,0 +1,77 @@
+function [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options);
+%MODIFYPOSITION - modify the prosition of a point of a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting..')
+		return
+	end
+
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	while loop
+
+		%select a point to be modified 
+		title('click on the point to be modified, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest point
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			%plot the point in blue
+			plot(A(profsel).x(indsel),A(profsel).y(indsel),...
+				'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+			%select new location
+			title('click on the new location, RETURN to exit','FontSize',14)
+			[xi,yi] = ginput(1);
+
+			if ~isempty(xi)
+
+				%modification of its coordinates
+				A(profsel).x(indsel)=xi;
+				A(profsel).y(indsel)=yi;
+
+				%modify the last point if the profile is closed and indsel=end or 1
+				if closed(profsel)
+					if indsel==1 
+						A(profsel).x(end)=xi;
+						A(profsel).y(end)=yi;
+					elseif indsel==length(A(profsel).x)
+						A(profsel).x(1)=xi;
+						A(profsel).y(1)=yi;
+					end
+				end
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+			else
+				%RETURN-> exit
+				loop=0;
+			end
+		else
+			%RETURN-> exit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/orientprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/orientprofile.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/orientprofile.m	(revision 13395)
@@ -0,0 +1,54 @@
+function [A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%ORIENTPROFILE - cahnge profile orientation
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click on the profiles to be reoriented, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile to be reoriented, exiting...')
+			return
+		end
+		   
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it from list
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			else
+				%add the profile to the list to be removed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%reorient profiles
+			selection=sort(selection);
+			for i=1:length(selection),
+				A(selection(i)).x=flipud(A(selection(i)).x);
+				A(selection(i)).y=flipud(A(selection(i)).y);
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/removepoints.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/removepoints.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/removepoints.m	(revision 13395)
@@ -0,0 +1,85 @@
+function [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+%REMOVEPOINTS - remove a point from a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end
+
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+	end
+
+	while loop
+
+		%check that at least one point is present
+		if numpoints==0
+			disp('at least one point are needed')
+			return
+		end	   
+
+		%select a point to be deleted
+		title('click on the point to be removed, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest point
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			%remove point of A
+			A(profsel).x(indsel)=[];
+			A(profsel).y(indsel)=[];
+
+			%unclose the domain if only 2 points remaining
+			if closed(profsel)
+				if length(A(profsel).x)==3
+					A(profsel).x(end)=[];
+					A(profsel).y(end)=[];
+					numpoints=numpoints-1;
+					closed(profsel)=0;
+				end
+			end
+
+			%remove the last point if the profile is closed and indsel=end or 1
+			if closed(profsel)
+				if indsel==1 
+					A(profsel).x(end)=A(profsel).x(1);
+					A(profsel).y(end)=A(profsel).y(1);
+				elseif indsel==length(A(profsel).x)
+					A(profsel).x(1)=A(profsel).x(end);
+					A(profsel).y(1)=A(profsel).y(end);
+				end
+			end
+			numpoints=numpoints-1;
+
+			%plot new profile
+			undoplots(prevplot);
+			for i=1:numprofiles
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+					'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				if length(A(i).x)==1
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker','o');
+				end
+			end
+
+		else
+			%RETURN-> exit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/removeprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/removeprofile.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/removeprofile.m	(revision 13395)
@@ -0,0 +1,56 @@
+function [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+%REMOVEPROFILE - delete a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click on the profiles to be removed, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile to be removed, exiting...')
+			return
+		end
+		   
+		[xi,yi] = ginput(1);
+					  
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			else
+				%add the profile to the list to be removed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%remove the profiles
+			selection=sort(selection);
+			for i=1:length(selection),
+				numprofiles=numprofiles-1;
+				numpoints=numpoints-length(A(selection(i)-(i-1)).x);
+				A(selection(i)-(i-1))=[];
+				closed(selection(i)-(i-1))=[];
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/removeseveralpoints.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/removeseveralpoints.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/removeseveralpoints.m	(revision 13395)
@@ -0,0 +1,130 @@
+function [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+%REMOVESEVERALPOINTS - remove several point
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+		
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<3
+		disp('at least 3 points are required, exiting...')
+		return
+	end	   
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	points=[];
+
+	%loop (at least 3 clicks needed)
+	while loop
+
+		%some checks
+		if numpoints<3
+			disp('at least 3 points are required, exiting...')
+			return
+		end
+
+		%select a point
+		if isempty(points)
+			title('click on the first tip, RETURN to exit','FontSize',14)
+		elseif length(points)==1
+			title('click on the second tip, RETURN to exit','FontSize',14)
+		else
+			title('click in the middle of the area to be removed, RETURN to exit','FontSize',14)
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			%get the closest point
+			%first time, look at all profiles
+			if isempty(points)
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if ((closed(profsel) & length(A(profsel).x)<4) |  (~closed(profsel) & length(A(profsel).x)<3)),
+					disp('the selected profile has less than 3 points, make another selection');
+				else
+					selection=profsel;
+					points(end+1)=indsel;
+					plot(A(profsel).x,A(profsel).y,...
+						'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+					text(A(selection).x(indsel),A(selection).y(indsel),num2str(1),'FontSize',14,'background',[0.7 0.7 0.9]);
+				end
+				%disp(['p1= ' num2str(indsel)]),
+			else
+				%get the 2d or 3d point for the given contou
+				[profsel indsel]=closestpoint(A(selection),1,xi,yi);
+				if ismember(indsel,points)
+					disp('the selected points must be distinct')
+				else
+					%second click?
+					if length(points)==1,
+						points(end+1)=indsel;
+						text(A(selection).x(indsel),A(selection).y(indsel),num2str(2),'FontSize',14,'background',[0.7 0.7 0.9]);
+						%disp(['p2= ' num2str(indsel)]),
+					%third click?
+					else
+						p1=points(1); p2=points(2); p3=indsel;
+						%disp(['p3= ' num2str(indsel)]),
+						if p1<p2
+							if p3>p1 & p3<p2
+								A(selection).x(p1+1:p2-1)=[];
+								A(selection).y(p1+1:p2-1)=[];
+								numpoints=numpoints-(p2-p1-1);
+							else
+								A(selection).x=A(selection).x(p1:p2);
+								A(selection).y=A(selection).y(p1:p2);
+								numpoints=numpoints-(numpoints-1-p2)-(p1-1);
+								if closed(selection)
+									%reattach the tips
+									A(selection).x(end+1)=A(selection).x(1);
+									A(selection).y(end+1)=A(selection).y(1);
+									numpoints=numpoints+1;
+								end
+							end
+						else
+							if p3>p2 & p3<p1
+								A(selection).x(p2+1:p1-1)=[];
+								A(selection).y(p2+1:p1-1)=[];
+								numpoints=numpoints-(p1-p2-1);
+							else
+								A(selection).x=A(selection).x(p2:p1);
+								A(selection).y=A(selection).y(p2:p1);
+								numpoints=numpoints-(numpoints-1-p1)-(p2-1);
+								if closed(selection)
+									%reattach the tips
+									A(selection).x(end+1)=A(selection).x(1);
+									A(selection).y(end+1)=A(selection).y(1);
+									numpoints=numpoints+1;
+								end
+							end
+						end
+
+						%plot new profiles
+						undoplots(prevplot);
+						for i=1:numprofiles
+							plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+								'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+						end
+						points=[];
+
+					end
+				end
+			end
+		else
+			%RETRUN-> quit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/manipulation/undoplots.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/undoplots.m	(revision 13395)
+++ /issm/trunk/src/m/exp/manipulation/undoplots.m	(revision 13395)
@@ -0,0 +1,12 @@
+function  undoplots(prevplot)
+%UNDOPLOTS - undo plots
+%
+%   Usage:undoplots(prevplot)
+
+	%erase all previous plots
+	g=get(gca,'children');
+	L=length(g);
+	for i=1:L-prevplot
+		delete(g(i));
+	end
+end
Index: /issm/trunk/src/m/extrusion/DepthAverage.m
===================================================================
--- /issm/trunk/src/m/extrusion/DepthAverage.m	(revision 13395)
+++ /issm/trunk/src/m/extrusion/DepthAverage.m	(revision 13395)
@@ -0,0 +1,33 @@
+function  vector_average=DepthAverage(md,vector);
+%DEPTHAVERAGE - computes depth average of 3d vector, and return value on 2d mesh. 
+%
+%   Usage:
+%      vector_average=DepthAverage(md,vector);
+%
+%   Example:
+%      vel_bar=DepthAverage(md,md.initialization.vel);
+
+%check that the model given in input is 3d
+if ~md.mesh.dimension==3;
+	error('DepthAverage error message: the model given in input must be 3d')
+end
+
+%nods data
+if (length(vector)==md.mesh.numberofvertices),
+	vector_average=zeros(md.mesh.numberofvertices2d,1);
+	for i=1:md.mesh.numberoflayers-1,
+		vector_average=vector_average+(project2d(md,vector,i)+project2d(md,vector,i+1))/2.*(project2d(md,md.mesh.z,i+1)-project2d(md,md.mesh.z,i));
+	end
+	vector_average=vector_average./project2d(md,md.geometry.thickness,1);
+
+%element data
+elseif (length(vector)==md.mesh.numberofelements),
+	vector_average=zeros(md.mesh.numberofelements2d,1);
+	for i=1:md.mesh.numberoflayers-1,
+		vector_average=vector_average+project2d(md,vector,i).*(project2d(md,md.mesh.z,i+1)-project2d(md,md.mesh.z,i));
+	end
+	vector_average=vector_average./project2d(md,md.geometry.thickness,1);
+
+else
+	error('vector size not supported yet');
+end
Index: /issm/trunk/src/m/extrusion/project2d.m
===================================================================
--- /issm/trunk/src/m/extrusion/project2d.m	(revision 13395)
+++ /issm/trunk/src/m/extrusion/project2d.m	(revision 13395)
@@ -0,0 +1,36 @@
+function projection_value=project2d(md3d,value,layer)
+%PROJECT2D - returns the value of a field for a given layer of the mesh
+%
+%   project 'value' vector taken at layer 'layer' from extruded 2d-3d mesh onto 2d mesh 
+%   used to do the extrusion. This routine is used to compare values between a 2d-3d mesh
+%   at a certain layer, and the equivalent value (if it exists), on the original 2d mesh. 
+%   This routine relies heavily on projections (contained in 3d model md) recored during 
+%   the extrude operation.
+%
+%   Usage:
+%      projection_value=project2d(md3d,value,layer)
+%
+%   Example:
+%      vel2=project2d(md3d,md3d.vel,2);
+
+%some checks on list of arguments
+if ((nargin~=3) ),
+	help project2d
+	error('project2d error message');
+end
+
+if (md3d.mesh.dimension~=3),
+	error('wrong model type ... should be ''3d''');
+end
+
+if ((layer<1) | (layer>md3d.mesh.numberoflayers)),
+	error(['layer must be between 1 and ' num2str(md3d.mesh.numberoflayers)]);
+end
+
+if size(value,1)==md3d.mesh.numberofvertices,
+	projection_value=value((layer-1)*md3d.mesh.numberofvertices2d+1:layer*md3d.mesh.numberofvertices2d,:);
+elseif size(value,1)==md3d.mesh.numberofvertices+1,
+	projection_value=[value((layer-1)*md3d.mesh.numberofvertices2d+1:layer*md3d.mesh.numberofvertices2d,:); value(end,:)];
+else
+	projection_value=value((layer-1)*md3d.mesh.numberofelements2d+1:layer*md3d.mesh.numberofelements2d,:);
+end
Index: /issm/trunk/src/m/extrusion/project3d.m
===================================================================
--- /issm/trunk/src/m/extrusion/project3d.m	(revision 13395)
+++ /issm/trunk/src/m/extrusion/project3d.m	(revision 13395)
@@ -0,0 +1,85 @@
+function projected_vector=project3d(md,varargin);
+%PROJECT3D - vertically project a vector from 2d mesh
+%
+%   vertically project a vector from 2d mesh (split in noncoll and coll areas) into a 3d mesh.
+%   This vector can be a node vector of size (md.mesh.numberofvertices2d,N/A) or an 
+%   element vector of size (md.mesh.numberofelements2d,N/A). 
+%   arguments: 
+%      'vector': 2d vector
+%      'type': 'element' or 'node'. 
+%   options: 
+%      'layer' a layer number where vector should keep its values. If not specified, all layers adopt the 
+%             value of the 2d vector.
+%      'padding': default to 0 (value adopted by other 3d layers not being projected0
+%
+%   Egs:
+%      extruded_vector=project3d(md,'vector',vector2d,'type','node','layer',1,'padding',NaN);
+%      extruded_vector=project3d(md,'vector',vector2d,'type','element','padding',0);
+%      extruded_vector=project3d(md,'vector',vector2d,'type','node');
+
+%some regular checks
+if nargin==0,
+	help project3d
+	error('bad usage');
+end
+if md.mesh.dimension~=3
+	error('input model is not 3d');
+end
+
+%retrieve parameters from options.
+options      = pairoptions(varargin{:});
+vector2d     = getfieldvalue(options,'vector');     %mandatory
+type         = getfieldvalue(options,'type');       %mandatory
+layer        = getfieldvalue(options,'layer',0);    %optional (do all layers otherwise)
+paddingvalue = getfieldvalue(options,'padding',0);  %0 by default
+
+if length(vector2d)==1,
+	projected_vector=vector2d;
+
+elseif strcmpi(type,'node'),
+
+	%Initialize 3d vector
+	if size(vector2d,1)==md.mesh.numberofvertices2d
+		projected_vector=paddingvalue*ones(md.mesh.numberofvertices,  size(vector2d,2));
+	elseif size(vector2d,1)==md.mesh.numberofvertices2d+1
+		projected_vector=paddingvalue*ones(md.mesh.numberofvertices+1,size(vector2d,2));
+		projected_vector(end,:)=vector2d(end,:);
+		vector2d=vector2d(1:end-1,:);
+	else
+		error('vector length not supported')
+	end
+
+	%Fill in
+	if layer==0,
+		for i=1:md.mesh.numberoflayers,
+			projected_vector(((i-1)*md.mesh.numberofvertices2d+1):(i*md.mesh.numberofvertices2d),:)=vector2d;
+		end
+	else
+		projected_vector(((layer-1)*md.mesh.numberofvertices2d+1):(layer*md.mesh.numberofvertices2d),:)=vector2d;
+	end
+
+elseif strcmpi(type,'element'),
+
+	%Initialize 3d vector
+	if size(vector2d,1)==md.mesh.numberofelements2d
+		projected_vector=paddingvalue*ones(md.mesh.numberofelements,  size(vector2d,2));
+	elseif size(vector2d,1)==md.mesh.numberofelements2d+1
+		projected_vector=paddingvalue*ones(md.mesh.numberofelements+1,size(vector2d,2));
+		projected_vector(end,:)=vector2d(end,:);
+		vector2d=vector2d(1:end-1,:);
+	else
+		error('vector length not supported')
+	end
+
+	%Fill in
+	if layer==0,
+		for i=1:(md.mesh.numberoflayers-1),
+			projected_vector( ((i-1)*md.mesh.numberofelements2d+1):(i*md.mesh.numberofelements2d),:)=vector2d;
+		end
+	else
+		projected_vector( ((layer-1)*md.mesh.numberofelements2d+1):(layer*md.mesh.numberofelements2d),:)=vector2d;
+	end
+
+else
+	error('project3d error message: unknown projection type');
+end
Index: /issm/trunk/src/m/extrusion/project3d.py
===================================================================
--- /issm/trunk/src/m/extrusion/project3d.py	(revision 13395)
+++ /issm/trunk/src/m/extrusion/project3d.py	(revision 13395)
@@ -0,0 +1,92 @@
+import numpy
+from pairoptions import *
+from MatlabFuncs import *
+
+def project3d(md,*args):
+	"""
+	PROJECT3D - vertically project a vector from 2d mesh
+
+	   vertically project a vector from 2d mesh (split in noncoll and coll areas) into a 3d mesh.
+	   This vector can be a node vector of size (md.mesh.numberofvertices2d,N/A) or an 
+	   element vector of size (md.mesh.numberofelements2d,N/A). 
+	   arguments: 
+	      'vector': 2d vector
+	      'type': 'element' or 'node'. 
+	   options: 
+	      'layer' a layer number where vector should keep its values. If not specified, all layers adopt the 
+	             value of the 2d vector.
+	      'padding': default to 0 (value adopted by other 3d layers not being projected0
+
+	   Egs:
+	      extruded_vector=project3d(md,'vector',vector2d,'type','node','layer',1,'padding',NaN);
+	      extruded_vector=project3d(md,'vector',vector2d,'type','element','padding',0);
+	      extruded_vector=project3d(md,'vector',vector2d,'type','node');
+	"""
+
+	#some regular checks
+	if not md:
+		raise TypeError("bad usage")
+	if not md.mesh.dimension==3:
+		raise TypeError("input model is not 3d")
+
+	#retrieve parameters from options.
+	options      = pairoptions(*args)
+	vector2d     = options.getfieldvalue('vector')       #mandatory
+	type         = options.getfieldvalue('type')         #mandatory
+	layer        = options.getfieldvalue('layer',0)      #optional (do all layers otherwise)
+	paddingvalue = options.getfieldvalue('padding',0)    #0 by default
+
+	vector1d=False
+	if isinstance(vector2d,numpy.ndarray) and len(vector2d.shape)==1:
+		vector1d=True
+		vector2d=vector2d.reshape(numpy.size(vector2d),1)
+
+	if   isinstance(vector2d,(bool,int,long,float)) or numpy.size(vector2d)==1:
+		projected_vector=vector2d
+
+	elif strcmpi(type,'node'):
+
+		#Initialize 3d vector
+		if   numpy.size(vector2d,axis=0)==md.mesh.numberofvertices2d:
+			projected_vector=paddingvalue*numpy.ones((md.mesh.numberofvertices,  numpy.size(vector2d,axis=1)))
+		elif numpy.size(vector2d,axis=0)==md.mesh.numberofvertices2d+1:
+			projected_vector=paddingvalue*numpy.ones((md.mesh.numberofvertices+1,numpy.size(vector2d,axis=1)))
+			projected_vector[-1,:]=vector2d[-1,:]
+			vector2d=vector2d[:-1,:]
+		else:
+			raise TypeError("vector length not supported")
+
+		#Fill in
+		if layer==0:
+			for i in xrange(md.mesh.numberoflayers):
+				projected_vector[(i*md.mesh.numberofvertices2d):((i+1)*md.mesh.numberofvertices2d),:]=vector2d
+		else:
+			projected_vector[((layer-1)*md.mesh.numberofvertices2d):(layer*md.mesh.numberofvertices2d),:]=vector2d
+
+	elif strcmpi(type,'element'):
+
+		#Initialize 3d vector
+		if   numpy.size(vector2d,axis=0)==md.mesh.numberofelements2d:
+			projected_vector=paddingvalue*numpy.ones((md.mesh.numberofelements,  numpy.size(vector2d,axis=1)))
+		elif numpy.size(vector2d,axis=0)==md.mesh.numberofelements2d+1:
+			projected_vector=paddingvalue*numpy.ones((md.mesh.numberofelements+1,numpy.size(vector2d,axis=1)))
+			projected_vector[-1,:]=vector2d[-1,:]
+			vector2d=vector2d[:-1,:]
+		else:
+			raise TypeError("vector length not supported")
+
+		#Fill in
+		if layer==0:
+			for i in xrange(md.mesh.numberoflayers-1):
+				projected_vector[(i*md.mesh.numberofelements2d):((i+1)*md.mesh.numberofelements2d),:]=vector2d
+		else:
+			projected_vector[((layer-1)*md.mesh.numberofelements2d):(layer*md.mesh.numberofelements2d),:]=vector2d
+
+	else:
+		raise TypeError("project3d error message: unknown projection type")
+
+	if vector1d:
+		projected_vector=projected_vector.reshape((numpy.size(projected_vector)))
+
+	return projected_vector
+
Index: /issm/trunk/src/m/geometry/FlagElements.m
===================================================================
--- /issm/trunk/src/m/geometry/FlagElements.m	(revision 13395)
+++ /issm/trunk/src/m/geometry/FlagElements.m	(revision 13395)
@@ -0,0 +1,57 @@
+function flag=FlagElements(md,region),
+%FLAGELEMENTS - flag the elements in an region
+%
+%   The region can be given with an exp file, a list of elements.
+%
+%   Usage: 
+%      flag=FlagElements(md,region);
+%
+%   Example:
+%      flag=FlagElements(md,'all');
+%      flag=FlagElements(md,'');
+%      flag=FlagElements(md,'Domain.exp');
+%      flag=FlagElements(md,'~Domain.exp');
+%      flag=FlagElements(md,md.mask.elementongroundedice);
+
+	if ischar(region),
+		if isempty(region),
+			flag=zeros(md.mesh.numberofelements,1);
+			invert=0;
+		elseif strcmpi(region,'all')
+			flag=ones(md.mesh.numberofelements,1);
+			invert=0;
+		else
+			%make sure that we actually don't want the elements outside the domain outline!
+			if strcmpi(region(1),'~'),
+				region=region(2:length(region));
+				invert=1;
+			else
+				invert=0;
+			end
+
+			%does the region domain outline exist or do we have to look for xlim,ylim in basinzoom?
+			if ~exist(region,'file'),
+				if (length(region)>3 & ~strcmp(region(end-3),'.exp')),
+					error(['Error: File ' region ' not found!']);
+				end
+				[xlim,ylim]=basinzoom('basin',region);
+				flag_nodes=double(md.mesh.x<xlim(2) & md.mesh.x>xlim(1) &  md.mesh.y<ylim(2) & md.mesh.y>ylim(1));
+				flag=prod(flag_nodes(md.mesh.elements),2);
+			else
+				%ok, flag elements
+				flag=ContourToMesh(md.mesh.elements(:,1:3),md.mesh.x,md.mesh.y,region,'element',1);
+			end
+		end
+		if invert,
+			flag=~flag;
+		end
+	elseif isfloat(region) | islogical(region),
+		if size(region,1)~=md.mesh.numberofelements,
+			help FlagElements
+			error('Flaglist for region must be of same size as number of elements in model');
+		end
+		flag=region;
+	else
+		error('Invalid region option');
+	end
+end
Index: /issm/trunk/src/m/geometry/FlagElements.py
===================================================================
--- /issm/trunk/src/m/geometry/FlagElements.py	(revision 13395)
+++ /issm/trunk/src/m/geometry/FlagElements.py	(revision 13395)
@@ -0,0 +1,62 @@
+import numpy
+import os
+#from basinzoom import *
+#from ContourToMesh import *
+from MatlabFuncs import *
+
+def FlagElements(md,region):
+	"""
+	FLAGELEMENTS - flag the elements in an region
+
+	   The region can be given with an exp file, a list of elements.
+
+	   Usage: 
+	      flag=FlagElements(md,region);
+
+	   Example:
+	      flag=FlagElements(md,'all');
+	      flag=FlagElements(md,'');
+	      flag=FlagElements(md,'Domain.exp');
+	      flag=FlagElements(md,'~Domain.exp');
+	      flag=FlagElements(md,md.mask.elementongroundedice);
+	"""
+
+	if   isinstance(region,(str,unicode)):
+		if   not region:
+			flag=numpy.zeros(md.mesh.numberofelements,'bool')
+			invert=0
+		elif strcmpi(region,'all'):
+			flag=numpy.ones(md.mesh.numberofelements,'bool')
+			invert=0
+		else:
+			#make sure that we actually don't want the elements outside the domain outline!
+			if strcmpi(region[0],'~'):
+				region=region[1:]
+				invert=1
+			else:
+				invert=0
+
+			#does the region domain outline exist or do we have to look for xlim,ylim in basinzoom?
+			if not os.path.exists(region):
+				if len(region)>3 and not strcmp(region[-4:],'.exp'):
+					raise IOError("Error: File 'region' not found!" % region)
+				xlim,ylim=basinzoom('basin',region)
+				flag_nodes=numpy.logical_and(numpy.logical_and(md.mesh.x<xlim[1],md.mesh.x>xlim[0]),numpy.logical_and(md.mesh.y<ylim[1],md.mesh.y>ylim[0])).astype(float)
+				flag=numpy.prod(flag_nodes[md.mesh.elements],axis=1)
+			else:
+				#ok, flag elements
+				flag=ContourToMesh(md.mesh.elements[:,0:3],md.mesh.x,md.mesh.y,region,'element',1)
+
+		if invert:
+			flag=numpy.logical_not(flag)
+
+	elif isinstance(region,numpy.nparray) or isinstance(region,bool):
+		if not numpy.size(region,0)==md.mesh.numberofelements:
+			raise TypeError("Flaglist for region must be of same size as number of elements in model.")
+		flag=region
+
+	else:
+		raise TypeError("Invalid region option")
+
+	return flag
+
Index: /issm/trunk/src/m/geometry/GetAreas.m
===================================================================
--- /issm/trunk/src/m/geometry/GetAreas.m	(revision 13395)
+++ /issm/trunk/src/m/geometry/GetAreas.m	(revision 13395)
@@ -0,0 +1,51 @@
+function areas=GetAreas(index,x,y,varargin)
+%GETAREAS - compute areas or volumes of elements
+%
+%   compute areas of triangular elements or volumes 
+%   of pentahedrons
+%
+%   Usage:
+%      areas  =GetAreas(index,x,y);
+%      volumes=GetAreas(index,x,y,z);
+%
+%   Examples:
+%      areas  =GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+%      volumes=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y,md.z);
+
+%get number of elements and number of nodes
+nels=size(index,1);
+nods=length(x);
+if nargin==4, z=varargin{1}; end
+
+%some checks
+if nargout~=1 | (nargin~=3 & nargin~=4),
+	help GetAreas
+	error('GetAreas error message: bad usage')
+end
+if ((length(y)~=nods) | (nargin==4 & length(z)~=nods)),
+	error('GetAreas error message: x,y and z do not have the same length')
+end
+if max(index(:))>nods,
+	error(['GetAreas error message: index should not have values above ' num2str(nods) ])
+end
+if (nargin==3 & size(index,2)~=3),
+	error('GetAreas error message: index should have 3 columns for 2d meshes.')
+end
+if (nargin==4 & size(index,2)~=6),
+	error('GetAreas error message: index should have 6 columns for 3d meshes.')
+end
+
+%initialization
+areas=zeros(nels,1);
+x1=x(index(:,1)); x2=x(index(:,2)); x3=x(index(:,3));
+y1=y(index(:,1)); y2=y(index(:,2)); y3=y(index(:,3));
+
+%compute the volume of each element
+if nargin==3,
+	%compute the surface of the triangle
+	areas=(0.5*((x2-x1).*(y3-y1)-(y2-y1).*(x3-x1)));
+else
+	%V=area(triangle)*1/3(z1+z2+z3)
+	thickness=mean(z(index(:,4:6)),2)-mean(z(index(:,1:3)),2);
+	areas=(0.5*((x2-x1).*(y3-y1)-(y2-y1).*(x3-x1))).*thickness;
+end
Index: /issm/trunk/src/m/geometry/SegIntersect.m
===================================================================
--- /issm/trunk/src/m/geometry/SegIntersect.m	(revision 13395)
+++ /issm/trunk/src/m/geometry/SegIntersect.m	(revision 13395)
@@ -0,0 +1,79 @@
+function bval=SegIntersect(seg1,seg2)
+%SEGINTERSECT - test of segments intersection
+%
+%   return 1 if the two segments intersect
+%   seg1=[x1 y1; x2 y2]
+%   seg2=[x1 y1; x2 y2]
+%
+%   Usage:
+%      bval=SegIntersect(seg1,seg2)
+
+bval=1;
+
+xA=seg1(1,1); yA=seg1(1,2);
+xB=seg1(2,1); yB=seg1(2,2);
+xC=seg2(1,1); yC=seg2(1,2);
+xD=seg2(2,1); yD=seg2(2,2);
+
+O2A=[xA;yA]-[xD/2.+xC/2.;yD/2.+yC/2.];
+O2B=[xB;yB]-[xD/2.+xC/2.;yD/2.+yC/2.];
+O1C=[xC;yC]-[xA/2.+xB/2.;yB/2.+yA/2.];
+O1D=[xD;yD]-[xA/2.+xB/2.;yB/2.+yA/2.];
+
+n1=[yA-yB;xB-xA]; %normal vector to segA
+n2=[yC-yD;xD-xC]; %normal vector to segB
+
+test1=n2'*O2A;
+test2=n2'*O2B;
+
+if test1*test2>0
+	bval=0;
+	return;
+end
+
+test3=n1'*O1C;
+test4=n1'*O1D;
+
+if test3*test4>0
+	bval=0;
+	return;
+end
+
+%if colinear
+if test1*test2==0 & test3*test4==0 & det([n1 n2])==0
+
+	%projection on the axis O1O2
+	O2O1=[xA/2.+xB/2.;yB/2.+yA/2.]-[xD/2.+xC/2.;yD/2.+yC/2.];
+	O1A=O2O1'*(O2A-O2O1);
+	O1B=O2O1'*(O2B-O2O1);
+	O1C=O2O1'*O1C;
+	O1D=O2O1'*O1D;
+	
+	%test if one point is included in the other segment (->bval=1)
+	if (O1C-O1A)*(O1D-O1A)<0
+		bval=1;
+		return;
+	end
+	if (O1C-O1B)*(O1D-O1B)<0
+		bval=1;
+		return;
+	end
+	if (O1A-O1C)*(O1B-O1C)<0
+		bval=1;
+		return;
+	end
+	if (O1A-O1D)*(O1B-O1D)<0
+		bval=1;
+		return;
+	end
+
+	 %test if the 2 segments have the same middle (->bval=1)
+	if O2O1==0
+		bval=1;
+		return;
+	end
+
+	%else
+	bval=0;
+	return;
+end
Index: /issm/trunk/src/m/geometry/SegIntersect.py
===================================================================
--- /issm/trunk/src/m/geometry/SegIntersect.py	(revision 13395)
+++ /issm/trunk/src/m/geometry/SegIntersect.py	(revision 13395)
@@ -0,0 +1,83 @@
+import numpy
+from MatlabFuncs import *
+
+def SegIntersect(seg1,seg2):
+	"""
+	SEGINTERSECT - test of segments intersection
+
+	   return 1 if the two segments intersect
+	   seg1=[x1 y1; x2 y2]
+	   seg2=[x1 y1; x2 y2]
+
+	   Usage:
+	      bval=SegIntersect(seg1,seg2)
+	"""
+
+	bval=1
+
+	xA=seg1[0,0]
+	yA=seg1[0,1]
+	xB=seg1[1,0]
+	yB=seg1[1,1]
+	xC=seg2[0,0]
+	yC=seg2[0,1]
+	xD=seg2[1,0]
+	yD=seg2[1,1]
+
+	O2A=numpy.array([xA,yA])-numpy.array([xD/2.+xC/2.,yD/2.+yC/2.])
+	O2B=numpy.array([xB,yB])-numpy.array([xD/2.+xC/2.,yD/2.+yC/2.])
+	O1C=numpy.array([xC,yC])-numpy.array([xA/2.+xB/2.,yB/2.+yA/2.])
+	O1D=numpy.array([xD,yD])-numpy.array([xA/2.+xB/2.,yB/2.+yA/2.])
+
+	n1=numpy.array([yA-yB,xB-xA])    #normal vector to segA
+	n2=numpy.array([yC-yD,xD-xC])    #normal vector to segB
+
+	test1=numpy.dot(n2,O2A)
+	test2=numpy.dot(n2,O2B)
+
+	if test1*test2>0:
+		bval=0
+		return bval
+
+	test3=numpy.dot(n1,O1C)
+	test4=numpy.dot(n1,O1D)
+
+	if test3*test4>0:
+		bval=0
+		return bval
+
+	#if colinear
+	if test1*test2==0 and test3*test4==0 and det(numpy.hstack((n1.reshape((-1,1)),n2.reshape(-1,1))))==0:
+
+		#projection on the axis O1O2
+		O2O1=numpy.array([xA/2.+xB/2.,yB/2.+yA/2.])-numpy.array([xD/2.+xC/2.,yD/2.+yC/2.])
+		O1A=numpy.dot(O2O1,(O2A-O2O1))
+		O1B=numpy.dot(O2O1,(O2B-O2O1))
+		O1C=numpy.dot(O2O1,O1C)
+		O1D=numpy.dot(O2O1,O1D)
+
+		#test if one point is included in the other segment (->bval=1)
+		if (O1C-O1A)*(O1D-O1A)<0:
+			bval=1
+			return bval
+		if (O1C-O1B)*(O1D-O1B)<0:
+			bval=1
+			return bval
+		if (O1A-O1C)*(O1B-O1C)<0:
+			bval=1
+			return bval
+		if (O1A-O1D)*(O1B-O1D)<0:
+			bval=1
+			return bval
+
+		#test if the 2 segments have the same middle (->bval=1)
+		if O2O1==0:
+			bval=1
+			return bval
+
+		#else
+		bval=0
+		return bval
+
+	return bval
+
Index: /issm/trunk/src/m/geometry/ThicknessCorrection.m
===================================================================
--- /issm/trunk/src/m/geometry/ThicknessCorrection.m	(revision 13395)
+++ /issm/trunk/src/m/geometry/ThicknessCorrection.m	(revision 13395)
@@ -0,0 +1,77 @@
+function md=ThicknessCorrection(md,varargin)
+%THICKNESSCORRECTION - correct the thickness of the ice shelf near the grounding line
+%
+%   This routine corrects the thickness and the bed on the transition zone
+%   by forcing the hydrostatic equilibrium.
+%   the thickness is modified as follows:
+%      thickness = (1-coeff) * thickness_observation + coeff * thickness_hydrostatic
+%   where:
+%      coeff=(d/distance)^2;
+%      distance=10km by default but can be specified
+%
+%   Usage:
+%      md=ThicknessCorrection(md,varargin);
+%
+%   Example:
+%      md=ThicknessCorrection(md);
+%      md=ThicknessCorrection(md,15000);
+
+%initialize thickness with the observations, and get hydrostatic thickness from the dem
+thickness=md.geometry.thickness;
+thickness_hydro=md.geometry.surface/(1-md.materials.rho_ice/md.materials.rho_water);
+hydrostatic_ratio=zeros(size(md.geometry.thickness));
+
+%get nodes on ice sheet and on ice shelf
+pos_shelf=find(~md.mask.vertexongroundedice);
+pos_GL=intersect(unique(md.mesh.elements(find(md.mask.elementongroundedice),:)),unique(md.mesh.elements(find(md.mask.elementonfloatingice),:)));
+debug=(length(pos_shelf)>50000);
+
+%check that there is a GL
+if isempty(pos_GL)
+	error('ThicknessCorrection error message: no grounding line has been detected. Check the model mask');
+end
+
+%get distance
+if nargin==2,
+	distance=varargin{1};
+else
+	distance=10000;
+end
+
+%modify thickness
+if (debug), fprintf('%s','      correction progress:   0.00 %'); end
+for i=1:length(pos_shelf)
+
+	if (debug & mod(i,100)==0),
+		fprintf('\b\b\b\b\b\b\b%5.2f%s',i/length(pos_shelf)*100,' %');
+	end
+
+	%search the node on ice sheet the closest to i
+	[d posd]=min(sqrt((md.mesh.x(pos_shelf(i))-md.mesh.x(pos_GL)).^2+(md.mesh.y(pos_shelf(i))-md.mesh.y(pos_GL)).^2));
+
+	if d>distance,
+
+		%if d > 15km, hydrostatic equilibrium
+		hydrostatic_ratio(pos_shelf(i))=1;
+		thickness(pos_shelf(i))=thickness_hydro(pos_shelf(i));
+
+	else
+
+		%else: quadratic combination of hydrostatic equilibrium and observations
+		hydrostatic_ratio(pos_shelf(i))=(d/distance)^2;
+		thickness(pos_shelf(i))=(1-hydrostatic_ratio(pos_shelf(i)))*thickness(pos_shelf(i))+hydrostatic_ratio(pos_shelf(i))*thickness_hydro(pos_shelf(i));
+
+	end
+end
+if (debug), fprintf('\b\b\b\b\b\b\b%5.2f%s\n',100,' %'); end
+
+%check the computed thickness
+minth=1/(1-md.materials.rho_ice/md.materials.rho_water);
+pos=find(isnan(thickness) | (thickness<=0));
+thickness(pos)=minth;
+hydrostatic_ratio(pos)=-1;
+
+%change bed to take into account the changes in thickness
+md.geometry.thickness=thickness;
+md.geometry.hydrostatic_ratio=hydrostatic_ratio;
+md.geometry.bed=md.geometry.surface-md.geometry.thickness;
Index: /issm/trunk/src/m/geometry/find_point.m
===================================================================
--- /issm/trunk/src/m/geometry/find_point.m	(revision 13395)
+++ /issm/trunk/src/m/geometry/find_point.m	(revision 13395)
@@ -0,0 +1,14 @@
+function f=find_point(tabx,taby,pointx,pointy)
+%FIND_POINT - find closest point
+%
+%   find which point of the list (tabx,taby) is
+%   the closest to (poinx,pointy)
+%
+%   Usage:
+%      f=find_point(tabx,taby,pointx,pointy)
+
+%Compute distance between point and cloud of points
+distance=sqrt((tabx-pointx).^2+(taby-pointy).^2);
+
+%find index of the minimum distance and return the first one only
+f=find(distance==min(min(distance)),1);
Index: /issm/trunk/src/m/geometry/slope.m
===================================================================
--- /issm/trunk/src/m/geometry/slope.m	(revision 13395)
+++ /issm/trunk/src/m/geometry/slope.m	(revision 13395)
@@ -0,0 +1,32 @@
+function [sx,sy,s]=slope(md)
+%SLOPE - compute the surface slope
+%
+%   Usage:
+%      [sx,sy,s]=slope(md)
+
+%load some variables (it is much faster if the variab;es are loaded from md once for all) 
+if (md.mesh.dimension==2),
+	numberofelements=md.mesh.numberofelements;
+	numberofnodes=md.mesh.numberofvertices;
+	index=md.mesh.elements;
+	x=md.mesh.x; y=md.mesh.y;
+else
+	numberofelements=md.mesh.numberofelements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	index=md.mesh.elements2d;
+	x=md.mesh.x2d; y=md.mesh.y2d;
+end
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+
+summation=[1;1;1];
+sx=(md.geometry.surface(index).*alpha)*summation;
+sy=(md.geometry.surface(index).*beta)*summation;
+s=sqrt(sx.^2+sy.^2);
+
+if md.mesh.dimension==3,
+	sx=project3d(md,'vector',sx,'type','element');
+	sy=project3d(md,'vector',sy,'type','element');
+	s=sqrt(sx.^2+sy.^2);
+end
Index: /issm/trunk/src/m/interp/InterpFromFile.m
===================================================================
--- /issm/trunk/src/m/interp/InterpFromFile.m	(revision 13395)
+++ /issm/trunk/src/m/interp/InterpFromFile.m	(revision 13395)
@@ -0,0 +1,200 @@
+function data_out=InterpFromFile(x,y,filename,default_value)
+%INTERPFROMFILE - load data and interpolate on the given nodes
+%
+%   load a matlab file (extension .mat) which holds 3 or 4 variables
+%   and interpolate the data on the mesh and plug it onto the model.
+%
+%   o 3 variables
+%     - a vector x (if the name of the variable do not begin with "x", an error can appear)
+%     - a vector y (if the name of the variable do not begin with "y", an error can appear)
+%     - a vector or matrix data (if the name of the variable do not begin with the field name, an error can appear)
+%   o 4 variables
+%     - a vector x (if the name of the variable do not begin with "x", an error can appear)
+%     - a vector y (if the name of the variable do not begin with "y", an error can appear)
+%     - a matrix with 3 columns (if the name of the variable do not begin with "index" or "elements", an error can appear)
+%     - a vector data (if the name of the variable do not begin with the field name, an error can appear)
+%
+%   Usage:
+%      data=InterpFromFile(x,y,filename,default_value);
+%
+%   Example:
+%      md.geometry.surface=InterpFromFile(md.mesh.x,md.mesh.y,'surfacefile.mat',0);
+%
+%   See also: PLUGVELOCITIES, INTERPFROMGRID, INTERPFROMMESH2D, INTERPFROMMESH3D
+
+%some checks
+if nargin~=4 | nargout~=1
+	help InterpFromFile
+	error('plugdata error message: bad usage');
+end
+if ~exist(filename)
+	error(['plugdata error message: file ' filename  ' does not exist']);
+end
+if length(x)~=length(y),
+	error('plugdata error message: x and y should have the same length');
+end
+
+%load file
+Names=FieldFindVarNames(filename);
+Data=load(filename);
+if strcmpi(Names.interp,'node'),
+	data_out=InterpFromGridToMesh(Data.(Names.xname),Data.(Names.yname),Data.(Names.dataname),x,y,default_value);
+else
+	data_out=InterpFromMeshToMesh2d(Data.(Names.indexname),Data.(Names.xname),Data.(Names.yname),Data.(Names.dataname),x,y);
+end
+
+end
+function Names=FieldFindVarNames(filename)
+%FIELDFINDVARNAMES - find names of variables in a data set file
+%
+%   This routines looks at the variables contained in a file and finds out
+%   the names of the variables that are needed for an interpolation (x,y,data)
+%   or (index,x,y,data)
+%
+%   Usage:
+%      Names=FieldFindVarNames(filename)
+%
+%   Example:
+%      Names=FieldFindVarNames('thickness.mat')
+%
+%   See also: INTERPFROMFILE, GRIDDATA
+
+%some checks
+if nargin~=1 | nargout~=1
+	help FieldFindVarNames
+	error('FieldFindVarNames error message: bad usage');
+end
+if ~exist(filename)
+	error(['FieldFindVarNames error message: file ' filename  ' does not exist']);
+end
+
+%Get variables
+A=whos('-file',filename);
+
+%find x,y,vx and vy
+xenum=NaN; yenum=NaN; dataenum=NaN; indexenum=NaN;
+if length(A)==3,
+	isnode=1;
+	for i=1:3
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		elseif (strncmpi(A(i).name,filename,3) | strncmpi(A(i).name,'data',4)),
+			dataenum=i;
+		else
+			%nothing
+		end
+	end
+elseif length(A)==4,
+	isnode=0;
+	for i=1:4
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		elseif (strncmpi(A(i).name,'index',5) | strncmpi(A(i).name,'elements',7));
+			indexenum=i;
+		elseif (strncmpi(A(i).name,filename,3) | strncmpi(A(i).name,'data',4)),
+			dataenum=i;
+		else
+			%nothing
+		end
+	end
+else
+	error(['FieldFindVarNames error message: file ' filename  ' not supported yet (it should hold 3 variables x,y and data (for nodes) OR 4 variables  x,y,index and data (for mesh))']);
+end
+
+%2: if only one item is missing, find it by elimination
+if ~isnode,
+	pos=find(isnan([xenum yenum indexenum dataenum]));
+	if length(pos)==1,
+		list=[xenum yenum indexenum dataenum]; list(pos)=[];
+		if pos==1,
+			xenum=setdiff(1:4,list);
+		elseif pos==2,
+			yenum=setdiff(1:4,list);
+		elseif pos==3,
+			indexenum=setdiff(1:4,list);
+		elseif pos==4,
+			dataenum=setdiff(1:4,list);
+		end
+	end
+else
+	pos=find(isnan([xenum yenum dataenum]));
+	if length(pos)==1,
+		list=[xenum yenum indexenum dataenum]; list(pos)=[];
+		if pos==1,
+			xenum=setdiff(1:3,list);
+		elseif pos==2,
+			yenum=setdiff(1:3,list);
+		elseif pos==3,
+			dataenum=setdiff(1:3,list);
+		end
+	end
+end
+
+%assum that we have found at least xenum and yenum
+if ( isnan(xenum) | isnan(yenum))
+	error(['FieldFindVarNames error message: file ' filename  ' not supported yet (the coordinates vectors should be named x and y)']);
+end
+
+%find index
+if (~isnode & isnan(indexenum)),
+	for i=1:4
+		lengthi=min(A(i).size);
+		if (lengthi==3),
+			indexenum=i;
+		end
+	end
+	if isnan(indexenum),
+		error(['FieldFindVarNames error message: file ' filename  ' not supported yet (index not found)']);
+	end
+end
+
+%4: last chance
+if ~isnode,
+	pos=find(isnan([xenum yenum indexenum dataenum]));
+	if length(pos)==1,
+		list=[xenum yenum indexenum dataenum]; list(pos)=[];
+		if pos==1,
+			xenum=setdiff(1:4,list);
+		elseif pos==2,
+			yenum=setdiff(1:4,list);
+		elseif pos==3,
+			indexenum=setdiff(1:4,list);
+		elseif pos==4,
+			dataenum=setdiff(1:4,list);
+		end
+	end
+else
+	pos=find(isnan([xenum yenum dataenum]));
+	if length(pos)==1,
+		list=[xenum yenum indexenum dataenum]; list(pos)=[];
+		if pos==1,
+			xenum=setdiff(1:3,list);
+		elseif pos==2,
+			yenum=setdiff(1:3,list);
+		elseif pos==3,
+			dataenum=setdiff(1:3,list);
+		end
+	end
+end
+
+%last check
+if isnan(dataenum)
+	error(['FieldFindVarNames error message: file ' filename  ' not supported yet (data not found)']);
+end
+
+%create output
+Names=struct();
+Names.xname=A(xenum).name;
+Names.yname=A(yenum).name;
+Names.dataname=A(dataenum).name;
+if ~isnode,
+	Names.indexname=A(indexenum).name; 
+	Names.interp='mesh';
+else
+	Names.interp='node';
+end
+end
Index: /issm/trunk/src/m/interp/PatchToVec.m
===================================================================
--- /issm/trunk/src/m/interp/PatchToVec.m	(revision 13395)
+++ /issm/trunk/src/m/interp/PatchToVec.m	(revision 13395)
@@ -0,0 +1,21 @@
+function vec=PatchToVec(Patch);
+%PATCHTOVEC - converts a patch to a vector by averaging over each vertex
+%
+%   Usage:
+%      vec=PatchToVec(Patch)
+
+%if the patch is P0: we have element values, return an element vector
+switch(size(Patch.value,2)),
+	case 1,
+		vec(Patch.element)=Patch.value;
+	case 3,
+		connectivity=sparse(Patch.index(:),1,1);
+		value       =sparse(Patch.index(:),1,Patch.value(:));
+		vec=full(value./connectivity);
+	case 6,
+		connectivity=sparse(Patch.index(:),1,1);
+		value       =sparse(Patch.index(:),1,Patch.value(:));
+		vec=full(value./connectivity);
+	otherwise,
+		error('interpolation not supported yet');
+	end
Index: /issm/trunk/src/m/interp/ProfileValues.m
===================================================================
--- /issm/trunk/src/m/interp/ProfileValues.m	(revision 13395)
+++ /issm/trunk/src/m/interp/ProfileValues.m	(revision 13395)
@@ -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/trunk/src/m/interp/SectionValues.m
===================================================================
--- /issm/trunk/src/m/interp/SectionValues.m	(revision 13395)
+++ /issm/trunk/src/m/interp/SectionValues.m	(revision 13395)
@@ -0,0 +1,127 @@
+function [index,X,Y,Z,S,data_interp]=SectionValues(md,data,infile,resolution)
+%SECTIONVALUES - compute the value of a field on a section
+%
+%   This routine gets the value of a given field of the model on points
+%   given by filname (Argus type file)
+%
+%   Usage:
+%      [elements,x,y,z,s,data]=SectionValues(md,data,filename,resolution)
+%      [elements,x,y,z,s,data]=SectionValues(md,data,profile_structure,resolution)
+
+%check what we have for profile as input
+if ischar(infile),
+	%read infile:
+	profile=expread(infile);
+	nods=profile.nods;
+	x=profile.x;
+	y=profile.y;
+else
+	%read infile:
+	nods=infile.nods;
+	x=infile.x;
+	y=infile.y;
+end
+
+
+%get the specified resolution
+if isnumeric(resolution(1))
+	res_h=resolution(1);
+else
+	error('SectionValues error message: wrong resolution type. Resolution must be an array [horizontal_resolution vertical_resolution]')
+end
+if md.mesh.dimension==3
+	if (length(resolution)==2 & isnumeric(resolution(2)))
+		res_v=resolution(2);
+	else
+		error('SectionValues error message: wrong resolution type. Resolution must be an array [horizontal_resolution vertical_resolution]')
+	end
+end
+
+%initialization
+X=[]; %X-coordinate
+Y=[]; %Y-coordinate
+S=0;  %curvilinear coordinate
+
+for i=1:nods-1
+
+	x_start=x(i);
+	x_end=x(i+1);
+	y_start=y(i);
+	y_end=y(i+1);
+	s_start=S(end);
+
+	length_segment=sqrt((x_end-x_start)^2+(y_end-y_start)^2);
+	portion=ceil(length_segment/res_h);
+
+	x_segment=zeros(portion,1);
+	y_segment=zeros(portion,1);
+	s_segment=zeros(portion,1);
+
+	for j=1:portion
+		x_segment(j)=x_start+(j-1)*(x_end-x_start)/portion;
+		y_segment(j)=y_start+(j-1)*(y_end-y_start)/portion;
+		s_segment(j)=s_start+j*length_segment/portion;
+	end
+
+	%plug into X and Y
+	X=[X;x_segment];
+	Y=[Y;y_segment];
+	S=[S;s_segment];
+end
+X(end+1)=x(nods);
+Y(end+1)=y(nods);
+
+%Number of nodes:
+numberofnodes=size(X,1);
+
+%Compute Z
+Z=zeros(numberofnodes,1);
+
+%New mesh and Data interpolation
+if (md.mesh.dimension==2)
+
+	%Interpolation of data on specified points
+	data_interp=InterpFromMesh2d(md.mesh.elements,md.mesh.x,md.mesh.y,data,X,Y);
+	%data_interp=InterpFromMeshToMesh2d(md.mesh.elements,md.mesh.x,md.mesh.y,data,X,Y);
+	%data_interp=griddata(md.mesh.x,md.mesh.y,data,X,Y);
+
+	%Compute index
+	index=[1:1:(numberofnodes-1);2:1:numberofnodes]';
+
+else
+
+	%vertically extrude mesh
+
+	%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),X,Y)+offset;
+	surface=InterpFromMeshToMesh2d(md.mesh.elements2d,md.mesh.x2d,md.mesh.y2d,project2d(md,md.geometry.surface,1),X,Y)-offset;
+
+	%Some useful parameters
+	layers=ceil(mean(md.geometry.thickness)/res_v);
+	nodesperlayer=numberofnodes;
+	nodestot=nodesperlayer*layers;
+	elementsperlayer=nodesperlayer-1;
+	elementstot=(nodesperlayer-1)*(layers-1);
+
+	%initialization
+	X3=zeros(nodesperlayer*layers,1); Y3=zeros(nodesperlayer*layers,1); Z3=zeros(nodesperlayer*layers,1); S3=zeros(nodesperlayer*layers,1); index3=zeros(elementstot,4);
+
+	%Get new coordinates in 3d
+	for i=1:layers
+		X3(i:layers:end)=X;
+		Y3(i:layers:end)=Y;
+		Z3(i:layers:end)=bed+(i-1)*(surface-bed)/(layers-1);
+		S3(i:layers:end)=S;
+
+		if i<layers %Build index3 with quads
+			index3((i-1)*elementsperlayer+1:i*elementsperlayer,:)=[i:layers:nodestot-layers; i+1:layers:nodestot-layers; i+layers+1:layers:nodestot; i+layers:layers:nodestot]';
+		end
+	end
+
+	%Interpolation of data on specified points
+	data_interp=InterpFromMeshToMesh3d(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,data,X3,Y3,Z3,NaN);
+
+	%build outputs
+	X=X3; Y=Y3; Z=Z3;  S=S3; index=index3;
+end
Index: /issm/trunk/src/m/interp/averaging.m
===================================================================
--- /issm/trunk/src/m/interp/averaging.m	(revision 13395)
+++ /issm/trunk/src/m/interp/averaging.m	(revision 13395)
@@ -0,0 +1,90 @@
+function average=averaging(md,data,iterations,varargin)
+%AVERAGING - smooths the input over the mesh
+%
+%   This routine takes a list over the elements or the nodes in input
+%   and return a list over the nodes.
+%   For each iterations it computes the average over each element (average 
+%   of the vertices values) and then computes the average over each node
+%   by taking the average of the element around a node weighted by the
+%   elements volume
+%   For 3d mesh, a last argument can be added to specify the layer to be averaged on.
+%
+%   Usage:
+%      smoothdata=averaging(md,data,iterations)
+%      smoothdata=averaging(md,data,iterations,layer)
+%
+%   Examples:
+%      velsmoothed=averaging(md,md.initialization.vel,4);
+%      pressure=averaging(md,md.initialization.pressure,0);
+%      temperature=averaging(md,md.initialization.temperature,1,1);
+
+if ((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
+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 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 & 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.x2d,md.mesh.y2d);
+end
+summation=1/rep*ones(rep,1);
+linesize=rep*numberofelements;
+
+%update weights that holds the volume of all the element holding the node i
+weights=sparse(line,ones(linesize,1),repmat(areas,rep,1),numberofnodes,1);
+
+%initialization
+if length(data)==numberofelements
+	average_node=sparse(line,ones(linesize,1),repmat(areas.*data,rep,1),numberofnodes,1);
+	average_node=average_node./weights;
+else
+	average_node=data;
+end
+
+%loop over iteration
+for i=1:iterations
+	average_el=average_node(index)*summation;
+	average_node=sparse(line,ones(linesize,1),repmat(areas.*average_el,rep,1),numberofnodes,1);
+	average_node=average_node./weights;
+end
+
+%return output as a full matrix (C code do not like sparse matrices)
+average=full(average_node);
Index: /issm/trunk/src/m/interp/plugvelocities.m
===================================================================
--- /issm/trunk/src/m/interp/plugvelocities.m	(revision 13395)
+++ /issm/trunk/src/m/interp/plugvelocities.m	(revision 13395)
@@ -0,0 +1,166 @@
+function md=plugvelocities(md,filename,default_value)
+%PLUGVELOCITIES - load velocities on a model
+%
+%   load a matlab file (extension .mat) which holds 4 variables
+%   x,y,vx,vy to be plugged onto the model (or similar names)
+%   x and y must be vectors, vx, vy matrices
+%
+%   Usage:
+%      md=plugvelocities(md,filename,default_value)
+%
+%   Example:
+%      md=plugvelocities(md,'velocityfile.mat',0);
+%
+%   See also: INTERPFROMFILE, GRIDDATA
+
+disp('WARNING: deprecated functions (plugvelocities)');
+%some checks
+if nargin~=3 | nargout~=1
+	help plugvelocities
+	error('plugvelocities error message: bad usage');
+end
+if ~exist(filename)
+	error(['plugvelocities error message: file ' filename  ' does not exist']);
+end
+
+%load velocities 
+Names=VelFindVarNames(filename);
+Vel=load(filename);
+
+%Interpolation
+if strcmpi(Names.interp,'node'),
+	md.inversion.vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,default_value);
+	md.inversion.vy_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,default_value);
+else
+	md.inversion.vx_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,default_value);
+	md.inversion.vy_obs=InterpFromMeshToMesh2d(Vel.(Names.indexname),Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vyname),md.mesh.x,md.mesh.y,default_value);
+end
+
+md.inversion.vel_obs=sqrt(md.inversion.vx_obs.^2+md.inversion.vy_obs.^2);
+md.initialization.vx=md.inversion.vx_obs;
+md.initialization.vy=md.inversion.vy_obs;
+md.initialization.vel=md.inversion.vel_obs;
+end
+
+function Names=VelFindVarNames(filename)
+%VELFINDVARNAMES - find names of variables in a velocity data set file
+%
+%   This routines looks at the variables contained in a file and finds out
+%   the names of the variables that are needed for an interpolation (x,y,vx,vy)
+%   or (index,x,y,vx,vy)
+%
+%   Usage:
+%      Names=VelFindVarNames(filename)
+%
+%   Example:
+%      Names=VelFindVarNames('velocities.mat')
+%
+%   See also: INTERPFROMFILE, GRIDDATA
+
+%some checks
+if nargin~=1 | nargout~=1
+	help VelFindVarNames
+	error('VelFindVarNames error message: bad usage');
+end
+if ~exist(filename)
+	error(['VelFindVarNames error message: file ' filename  ' does not exist']);
+end
+
+%Get variables
+A=whos('-file',filename);
+
+%find x,y,vx and vy
+xenum=NaN; yenum=NaN; vxenum=NaN; vyenum=NaN; indexenum=NaN;
+if length(A)==4,
+	isnode=1;
+	for i=1:4
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		else
+			if (strcmpi(A(i).name(end),'x') | strncmpi(A(i).name,'vx',2));
+				vxenum=i;
+			elseif (strcmpi(A(i).name(end),'y') | strncmpi(A(i).name,'vy',2));
+				vyenum=i;
+			end
+		end
+	end
+elseif length(A)==5,
+	isnode=0;
+	for i=1:5
+		if strcmpi(A(i).name(1),'x');
+			xenum=i;
+		elseif strcmpi(A(i).name(1),'y');
+			yenum=i;
+		elseif (strcmpi(A(i).name(1),'index') | strcmpi(A(i).name(1),'elements'));
+			indexenum=i;
+		else
+			if (strcmpi(A(i).name(end),'x') | strncmpi(A(i).name,'vx',2));
+				vxenum=i;
+			elseif (strcmpi(A(i).name(end),'y') | strncmpi(A(i).name,'vy',2));
+				vyenum=i;
+			end
+		end
+	end
+else
+	error(['VelFindVarNames error message: file ' filename  ' not supported yet (it should hold 4 variables x,y,vx and vy (for nodes) OR 5 variables  x,y,index,vx and vy (for mesh))']);
+end
+
+%assum that we have found at least vxenum and vyenum
+if ( isnan(vxenum) | isnan(vyenum))
+	error(['VelFindVarNames error message: file ' filename  ' not supported yet (the velocities should be named vx and vy)']);
+end
+
+%find index
+if (~isnode & isnan(indexenum)),
+	for i=1:5
+		lengthi=min(A(i).size);
+		if (lengthi==3),
+			indexenum=i;
+		end
+	end
+	if isnan(indexenum),
+		error(['VelFindVarNames error message: file ' filename  ' not supported yet (index not found)']);
+	end
+end
+
+%find x y
+if (isnan(xenum) | isnan(yenum))
+
+	%check the size
+	if A(vxenum).size(1)==A(vxenum).size(2),
+		error(['VelFindVarNames error message: file ' filename  ' not supported (velocities is a square matrix, save x and y with another name)']);
+	end
+	if ~(A(vxenum).size(1)==A(vyenum).size(1) & A(vxenum).size(2)==A(vyenum).size(2)),
+		error(['VelFindVarNames error message: file ' filename  ' not supported (vx and vy matrices do not have the same size)']);
+	end
+
+	%find xenum and yenum
+	for i=1:4
+		lengthi=max(A(i).size);
+		if ((i~=vxenum) & (lengthi==A(vxenum).size(1) | lengthi==A(vxenum).size(1)+1)),
+			yenum=i;
+		elseif ((i~=vxenum) & (lengthi==A(vxenum).size(2) | lengthi==A(vxenum).size(2)+1)),
+			xenum=i;
+		end
+	end
+
+	%last check
+	if (isnan(xenum) | isnan(yenum))
+		error(['plugdata error message: file ' filename  ' not supported yet']);
+	end
+end
+
+%create output
+Names=struct();
+Names.xname=A(xenum).name;
+Names.yname=A(yenum).name;
+Names.vxname=A(vxenum).name;
+Names.vyname=A(vyenum).name;
+if ~isnode,
+	Names.indexname=A(indexenum).name; 
+	Names.interp='mesh';
+else
+	Names.interp='node';
+end
Index: /issm/trunk/src/m/inversions/MisfitDeinterlace.m
===================================================================
--- /issm/trunk/src/m/inversions/MisfitDeinterlace.m	(revision 13395)
+++ /issm/trunk/src/m/inversions/MisfitDeinterlace.m	(revision 13395)
@@ -0,0 +1,21 @@
+function Jstruct=MisfitDeinterlace(misfit,type)
+%MISFITDEINTERLACE - deinterlace misfits that are mixed together, using type.
+%
+%   Usage:
+%      Jstruct=MisfitDeinterlace(misfit,type)
+%
+%   Example:
+%      Jstruct=MisfitDeinterlace(md.results.diagnostic.J,md.fit)
+%
+%
+Jstruct=struct();
+
+count=1;
+for i=0:max(type),
+	pos=find(type==i);
+	if length(pos),
+		Jstruct(count).type=i;
+		Jstruct(count).J=misfit(pos);
+		count=count+1;
+	end
+end
Index: /issm/trunk/src/m/inversions/misfit.m
===================================================================
--- /issm/trunk/src/m/inversions/misfit.m	(revision 13395)
+++ /issm/trunk/src/m/inversions/misfit.m	(revision 13395)
@@ -0,0 +1,37 @@
+function J=misfit(md)
+%MISFIT - compute misfit
+%
+%   Usage:
+%      J=misfit(md)
+%
+%   Example:
+%      J=misfit(md)
+%
+
+if md.mesh.dimension==2,
+	elements=md.mesh.elements;
+	x=md.mesh.x;
+	y=md.mesh.y;
+	vx=md.initialization.vx;
+	vy=md.initialization.vy;
+	vx_obs=md.inversion.vx_obs;
+	vy_obs=md.inversion.vy_obs;
+else
+	elements=md.mesh.elements2d;
+	x=md.mesh.x2d;
+	y=md.mesh.y2d;
+	vx=project2d(md,md.initialization.vx,md.mesh.numberoflayers);
+	vy=project2d(md,md.initialization.vy,md.mesh.numberoflayers);
+	vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers);
+	vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers);
+end
+
+%compute areas;
+areas=GetAreas(elements,x,y);
+
+%compute delta v on elements
+deltav=1/2*(   (vx-vx_obs).^2+(vy-vy_obs).^2)/md.constants.yts^2;
+deltav_elem=deltav(elements)*[1;1;1]/3;
+
+%compute misfit
+J=sum(deltav_elem.*areas);
Index: /issm/trunk/src/m/inversions/parametercontrolB.m
===================================================================
--- /issm/trunk/src/m/inversions/parametercontrolB.m	(revision 13395)
+++ /issm/trunk/src/m/inversions/parametercontrolB.m	(revision 13395)
@@ -0,0 +1,122 @@
+function md=parametercontrolB(md,varargin),
+%PARAMETERCONTROLB - parameterization for control method on B
+%
+%   It is possible to specify the number of steps, values for the
+%   minimum and maximum values of B, the 
+%   kind of cm_responses to use or the the optscal.
+%   
+%   Usage:
+%       md=parametercontrolB(md,varargin)
+%
+%   Example:
+%      md=parametercontrolB(md)
+%      md=parametercontrolB(md,'nsteps',20,'cm_responses',0)
+%      md=parametercontrolB(md,'cm_min',10,'cm_max',10^8,'cm_jump',0.99,'maxiter',20)
+%      md=parametercontrolB(md,eps_cm',10^-4,'optscal',[10^7 10^8])
+%
+%   See also  PARAMETERCONTROLDRAG
+
+%process options
+options=pairoptions(varargin{:});
+
+%control type
+md.inversion.control_parameters={'MaterialsRheologyBbar'};
+
+%weights
+weights=getfieldvalue(options,'weights',ones(md.mesh.numberofvertices,1));
+if (length(weights)~=md.mesh.numberofvertices)
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+else
+	md.inversion.cost_functions_coefficients=weights;
+end
+
+%nsteps
+nsteps=getfieldvalue(options,'nsteps',100);
+if (length(nsteps)~=1 | nsteps<=0 | floor(nsteps)~=nsteps)
+	md.inversion.nsteps=100;
+else
+	md.inversion.nsteps=nsteps;
+end
+
+
+%cm_min
+cm_min=getfieldvalue(options,'cm_min',paterson(273.15+5)*ones(md.mesh.numberofvertices,1));
+if (length(cm_min)==1)
+	md.inversion.min_parameters=cm_min*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_min)==md.mesh.numberofvertices)
+	md.inversion.min_parameters=cm_min;
+else
+	md.inversion.min_parameters=cm_min;
+end
+
+%cm_max
+cm_max=getfieldvalue(options,'cm_max',paterson(273.15-70)*ones(md.mesh.numberofvertices,1));
+if (length(cm_max)==1)
+	md.inversion.max_parameters=cm_max*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_max)==md.mesh.numberofvertices)
+	md.inversion.max_parameters=cm_max;
+else
+	md.inversion.max_parameters=cm_max;
+end
+
+%eps_cm
+eps_cm=getfieldvalue(options,'eps_cm',NaN);
+if (length(eps_cm)~=1 | eps_cm<0 )
+	md.inversion.cost_function_threshold=NaN;
+else
+	md.inversion.cost_function_threshold=eps_cm;
+end
+
+%maxiter
+maxiter=getfieldvalue(options,'maxiter',10*ones(md.inversion.nsteps,1));
+if (any(maxiter<0) | any(floor(maxiter)~=maxiter))
+	md.inversion.maxiter_per_step=10*ones(md.inversion.nsteps,1);
+else
+	md.inversion.maxiter_per_step=repmat(maxiter(:),md.inversion.nsteps,1);
+	md.inversion.maxiter_per_step(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_jump
+cm_jump=getfieldvalue(options,'cm_jump',0.9*ones(md.inversion.nsteps,1));
+if ~isreal(cm_jump)
+	md.inversion.step_threshold=0.9*ones(md.inversion.nsteps,1);
+else
+	md.inversion.step_threshold=repmat(cm_jump(:),md.inversion.nsteps,1);
+	md.inversion.step_threshold(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_responses
+found=0;
+if exist(options,'cm_responses'),
+	cm_responses=getfieldvalue(options,'cm_responses');
+	if ~any(~ismember(cm_responses,[ 101:105])),
+		md.inversion.cost_functions=repmat(cm_responses(:),md.inversion.nsteps,1);
+		md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.cost_functions=[...
+		103*ones(third,1);...
+		101*ones(third,1);...
+		repmat([101;101;103;101],third,1)...
+		];
+	md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+end
+
+%optscal
+found=0;
+if exist(options,'optscal'),
+	optscal=getfieldvalue(options,'optscal');
+	if ~any(optscal<0),
+		md.inversion.gradient_scaling=repmat(optscal(:),md.inversion.nsteps,1);
+		md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.gradient_scaling=[2*10^8*ones(3,1);10^8*ones(third-3,1);10^7*ones(2*third,1);];
+	md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+end
Index: /issm/trunk/src/m/inversions/parametercontroldrag.m
===================================================================
--- /issm/trunk/src/m/inversions/parametercontroldrag.m	(revision 13395)
+++ /issm/trunk/src/m/inversions/parametercontroldrag.m	(revision 13395)
@@ -0,0 +1,121 @@
+function md=parametercontroldrag(md,varargin),
+%PARAMETERCONTROLDRAG - parameterization for control method on drag
+%
+%   It is possible to specify the number of steps, values for the
+%   minimum and maximum values of the drag, the 
+%   kind of cm_responses to use or the the optscal.
+%   
+%   Usage:
+%       md=parametercontroldrag(md,varargin)
+%
+%   Example:
+%      md=parametercontroldrag(md)
+%      md=parametercontroldrag(md,'nsteps',20,'cm_responses',0)
+%      md=parametercontroldrag(md,'cm_min',1,'cm_max',150,'cm_jump',0.99,'maxiter',20)
+%      md=parametercontroldrag(md,eps_cm',10^-4,'optscal',[10^7 10^8])
+%
+%   See also PARAMETERCONTROLB
+
+%process options
+options=pairoptions(varargin{:});
+
+%control type
+md.inversion.control_parameters={'FrictionCoefficient'};
+
+%weights
+weights=getfieldvalue(options,'weights',ones(md.mesh.numberofvertices,1));
+if (length(weights)~=md.mesh.numberofvertices)
+	md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,1);
+else
+	md.inversion.cost_functions_coefficients=weights;
+end
+
+%nsteps
+nsteps=getfieldvalue(options,'nsteps',100);
+if (length(nsteps)~=1 | nsteps<=0 | floor(nsteps)~=nsteps)
+	md.inversion.nsteps=100;
+else
+	md.inversion.nsteps=nsteps;
+end
+
+%cm_min
+cm_min=getfieldvalue(options,'cm_min',1*ones(md.mesh.numberofvertices,1));
+if (length(cm_min)==1)
+	md.inversion.min_parameters=cm_min*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_min)==md.mesh.numberofvertices)
+	md.inversion.min_parameters=cm_min;
+else
+	md.inversion.min_parameters=cm_min;
+end
+
+%cm_max
+cm_max=getfieldvalue(options,'cm_max',250*ones(md.mesh.numberofvertices,1));
+if (length(cm_max)==1)
+	md.inversion.max_parameters=cm_max*ones(md.mesh.numberofvertices,1);
+elseif (length(cm_max)==md.mesh.numberofvertices)
+	md.inversion.max_parameters=cm_max;
+else
+	md.inversion.max_parameters=cm_max;
+end
+
+%eps_cm
+eps_cm=getfieldvalue(options,'eps_cm',NaN);
+if (length(eps_cm)~=1 | eps_cm<0 )
+	md.inversion.cost_function_threshold=NaN;
+else
+	md.inversion.cost_function_threshold=eps_cm;
+end
+
+%maxiter
+maxiter=getfieldvalue(options,'maxiter',10*ones(md.inversion.nsteps,1));
+if (any(maxiter<0) | any(floor(maxiter)~=maxiter))
+	md.inversion.maxiter_per_step=10*ones(md.inversion.nsteps,1);
+else
+	md.inversion.maxiter_per_step=repmat(maxiter(:),md.inversion.nsteps,1);
+	md.inversion.maxiter_per_step(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_jump
+cm_jump=getfieldvalue(options,'cm_jump',0.8*ones(md.inversion.nsteps,1));
+if ~isreal(cm_jump)
+	md.inversion.step_threshold=0.8*ones(md.inversion.nsteps,1);
+else
+	md.inversion.step_threshold=repmat(cm_jump(:),md.inversion.nsteps,1);
+	md.inversion.step_threshold(md.inversion.nsteps+1:end)=[];
+end
+
+%cm_responses
+found=0;
+if exist(options,'cm_responses'),
+	cm_responses=getfieldvalue(options,'cm_responses');
+	if ~any(~ismember(cm_responses,[101 105]))
+		md.inversion.cost_functions=repmat(cm_responses(:),md.inversion.nsteps,1);
+		md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.cost_functions=[...
+		103*ones(third,1);...
+		101*ones(third,1);...
+		repmat([101;101;103;101],third,1)...
+		];
+	md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+end
+
+%optscal
+found=0;
+if exist(options,'optscal'),
+	optscal=getfieldvalue(options,'optscal');
+	if ~any(optscal<0),
+		md.inversion.gradient_scaling=repmat(optscal(:),md.inversion.nsteps,1);
+		md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+		found=1;
+	end
+end
+if ~found
+	third=ceil(md.inversion.nsteps/3);
+	md.inversion.gradient_scaling=[50*ones(3,1);15*ones(third-3,1);10*ones(third,1);repmat([10;10;20;10],third,1)];
+	md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+end
Index: /issm/trunk/src/m/io/loadmodel.m
===================================================================
--- /issm/trunk/src/m/io/loadmodel.m	(revision 13395)
+++ /issm/trunk/src/m/io/loadmodel.m	(revision 13395)
@@ -0,0 +1,46 @@
+function varargout=loadmodel(path)
+%LOADMODEL - load a model using built-in load module
+%
+%   check that model prototype has not changed. if so, adapt to new model prototype.
+%
+%   Usage:
+%      md=loadmodel(path)
+%      loadmodel path
+
+%check nargout
+if nargout>1,
+	error('loadmodel usage error: md=loadmodel(path)');
+end
+
+%check existence
+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
+
+try,
+	%recover model on file and name it md
+	warning off MATLAB:unknownElementsNowStruc;
+	warning off MATLAB:load:classNotFound
+	struc=load(path,'-mat');
+	warning on MATLAB:unknownElementsNowStruc;
+	warning on MATLAB:load:classNotFound
+
+	name=char(fieldnames(struc));
+	if size(name,1)>1,
+		error(['loadmodel error message: file ' path ' contains several variables. Only one model should be present.']); 
+	end
+	md=struc.(name);
+	if nargout,
+		varargout{1}=md;
+	else
+		assignin('caller',name,md);
+	end
+catch me
+	disp(getReport(me))
+	error(['could not load model ' path]);
+end
Index: /issm/trunk/src/m/io/loadmodellist.m
===================================================================
--- /issm/trunk/src/m/io/loadmodellist.m	(revision 13395)
+++ /issm/trunk/src/m/io/loadmodellist.m	(revision 13395)
@@ -0,0 +1,50 @@
+function varargout=loadmodellist(path)
+%LOADMODELLIST- load a model using built-in load module
+%
+%   check that modellist prototype has not changed. if so, adapt to new modellist prototype.
+%
+%   Usage:
+%      mds=loadmodellist(path)
+%      loadmodellist path
+
+%check nargout
+if nargout>1,
+	error('loadmodellist usage error: mds=loadmodellist(path)');
+end
+%check existence
+if ~exist(path)
+	error(['loadmodellist error message: file ' path ' does not exist']);
+end
+
+%check that the file is readable
+[stat,mess]=fileattrib(path);
+if( stat==0 | mess.UserRead~=1),
+	error(['loadmodellist error message: file ' path ' is not readable (permission dinied).']);
+end
+
+%check number of variables
+if length(whos('-file',path))>1,
+	error(['loadmodellist error message: file ' path ' contains several variables. Only one model should be present.']);
+end
+
+try,
+	struc=load(path,'-mat');
+
+	%get name of model variable
+	fieldname=char(fieldnames(struc));
+	mds=eval(['struc.' fieldname]);
+	if ~strcmpi(class(mds),'model'),
+		mds2=modellist;
+		mds2=structtomodel(mds2,mds);
+		mds=mds2;
+		clear mds2;
+	end
+	if nargout,
+		varargout{1}=mds;
+	else
+		assignin('caller',fieldname,mds);
+	end
+catch me
+	disp(getReport(me))
+	error(['could not load model ' path]);
+end
Index: /issm/trunk/src/m/kml/exp2kml.m
===================================================================
--- /issm/trunk/src/m/kml/exp2kml.m	(revision 13395)
+++ /issm/trunk/src/m/kml/exp2kml.m	(revision 13395)
@@ -0,0 +1,19 @@
+function exp2kml(input,output)
+%EXP2KML: transform Argus exp file to kml
+%
+% Usage:    exp2kml('temp.exp','temp2.kml')
+%
+%
+
+
+%First, read exp file
+domain=expread(input);
+
+
+%then transform: 
+string=ge_plot(domain.x,domain.y,'name',domain.name);
+
+%open kml file for writing: 
+fid=fopen(output,'w');
+fprintf(fid,'%s',string);
+fclose(fid);
Index: /issm/trunk/src/m/kml/kml2exp.m
===================================================================
--- /issm/trunk/src/m/kml/kml2exp.m	(revision 13395)
+++ /issm/trunk/src/m/kml/kml2exp.m	(revision 13395)
@@ -0,0 +1,29 @@
+function kml2exp(input,output)
+%KML2EXP: transform kml file Argus exp file.
+%
+% Usage:    kmltoexp('temp.kml','temp2.exp')
+%
+%
+
+
+
+
+%First, read polygon kml file.
+structure=kml_shapefile(input);
+	
+%create exp file: 
+domain=struct();
+for i=1:length(structure),
+
+	if isfield(structure,'name'),
+		domain(end+1).name=structure(i).name;
+	else
+		domain(end+1).name='NaN';
+	end
+
+	domain(end).density=1;
+	domain(end).x=structure(i).X;
+	domain(end).y=structure(i).Y;
+end
+domain=domain(2:end);
+expwrite(domain,output);
Index: /issm/trunk/src/m/kml/kml2expg.m
===================================================================
--- /issm/trunk/src/m/kml/kml2expg.m	(revision 13395)
+++ /issm/trunk/src/m/kml/kml2expg.m	(revision 13395)
@@ -0,0 +1,13 @@
+function kml2expg(filename)
+
+	[path,name,ext]=fileparts(filename);
+
+	if strcmpi(ext,'.kmz'),
+		eval(['!unzip ' filename]);
+		eval(['!mv doc.kml ' name '.kml']);
+		kml2exp([name '.kml'],[name '.exp']);
+		expll2xy([name '.exp'],1);
+	end
+
+	kml2exp([name '.kml'],[name '.exp']);
+	expll2xy([name '.exp'],1);
Index: /issm/trunk/src/m/kml/kmlimagesc.m
===================================================================
--- /issm/trunk/src/m/kml/kmlimagesc.m	(revision 13395)
+++ /issm/trunk/src/m/kml/kmlimagesc.m	(revision 13395)
@@ -0,0 +1,67 @@
+function kmlimagesc(md,fieldname,varargin)
+%KMLIMAGESC - create lat,long kml image
+%
+%   Usage:
+%      kmlimagesc(md,field,options);
+%
+%   Options: 
+%      'hemisphere': default +1;
+%      'central_meridian: 45 for Greenland and 0 for Antarctica
+%      'standard_parallel: 70 for Greenland and 71 for Antarctica
+%      'posting': default .1 degree
+%
+
+%process varargin for options: 
+options=pairoptions(varargin{:});
+
+%recover field: 
+field=md.(fieldname);
+
+%recover some options, and set defaults
+fontsize=getfieldvalue(options,'fontsize',12);
+posting=getfieldvalue(options,'posting',.1);
+minlong=getfieldvalue(options,'minlong',min(md.mesh.long));
+maxlong=getfieldvalue(options,'maxlong',max(md.mesh.long));
+minlat=getfieldvalue(options,'minlat',min(md.mesh.lat));
+maxlat=getfieldvalue(options,'maxlat',max(md.mesh.lat));
+minfield=getfieldvalue(options,'minfield',min(field));
+maxfield=getfieldvalue(options,'maxfield',max(field));
+
+%do we have hemisphere setup?:
+if ~isstr(md.mesh.hemisphere),
+	error('md.mesh.hemisphere should be ''s'' or ''n''');
+end
+
+if strcmpi(md.mesh.hemisphere,'s'),
+	hemisphere=1;
+	central_meridian=getfieldvalue(options,'central_meridian',45);
+	standard_parallel=getfieldvalue(options,'standard_parallel',70);
+elseif strcmpi(md.mesh.hemisphere,'n'),
+	hemisphere=-1;
+	central_meridian=getfieldvalue(options,'central_meridian',0);
+	standard_parallel=getfieldvalue(options,'standard_parallel',71);
+else
+	error('md.mesh.hemisphere should be ''s'' or ''n''');
+end
+
+%figure out nlines and ncols in our image
+nlines=(maxlat-minlat)/posting;
+ncols=(maxlong-minlong)/posting;
+
+%regrid to lat,long grid
+[x_m,y_m,field]=InterpFromMeshToGrid(md.mesh.elements,md.mesh.long,md.mesh.lat,field,minlong,maxlat,posting,posting,nlines,ncols,NaN);
+field=flipud(field);
+
+%massage  and log:
+pos=find(field<minfield); field(pos)=minfield;
+pos=find(field>maxfield);field(pos)=maxfield;
+
+%create google earth kml file out of this regridded dataset:
+imagestr=ge_imagesc(x_m,y_m,field,'imgURL',[fieldname '.png'],'name',fieldname);
+imagestr=ge_folder(fieldname,imagestr);
+colorbarstr=ge_colorbar((min(x_m)+max(x_m))/2,(min(y_m)+max(y_m))/2,field,'name',fieldname);
+colorbarstr=ge_folder('Colorbar',colorbarstr);
+ge_output([fieldname '.kml'],[imagestr colorbarstr]);
+
+%now, create kmz file:
+system(['mv ' [fieldname '.kml'] ' doc.kml && zip ' [fieldname '.kmz'] ' doc.kml ' fieldname '.png && rm -rf doc.kml ' [fieldname '.png'] ]);
Index: /issm/trunk/src/m/latlong/ll2xy.m
===================================================================
--- /issm/trunk/src/m/latlong/ll2xy.m	(revision 13395)
+++ /issm/trunk/src/m/latlong/ll2xy.m	(revision 13395)
@@ -0,0 +1,66 @@
+function [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)  
+%LL2XY - converts lat long to polar stereographic
+%
+%   Converts from geodetic latitude and longitude to Polar 
+%   Stereographic (X,Y) coordinates for the polar regions.
+%   Author: Michael P. Schodlok, December 2003 (map2ll)
+%
+%   Usage:
+%      [x,y] = ll2xy(lat,lon,sgn)
+%      [x,y] = ll2xy(lat,lon,sgn,central_meridian,standard_parallel)
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==5,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==3
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Info: creating coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help ll2xy
+	error('bad usage');
+end
+
+% Conversion constant from degrees to radians
+cde  = 57.29577951;
+% Radius of the earth in meters
+re   = 6378.273*10^3;
+% Eccentricity of the Hughes ellipsoid squared
+ex2   = .006693883;
+% Eccentricity of the Hughes ellipsoid
+ex    =  sqrt(ex2);
+
+latitude  = abs(lat) * pi/180.;
+longitude = (lon + delta) * pi/180.;
+
+% compute X and Y in grid coordinates.
+T = tan(pi/4-latitude/2) ./ ((1-ex*sin(latitude))./(1+ex*sin(latitude))).^(ex/2);
+
+if (90 - slat) <  1.e-5 
+	rho = 2.*re*T/sqrt((1.+ex)^(1.+ex)*(1.-ex)^(1.-ex));
+else
+	sl  = slat*pi/180.;
+	tc  = tan(pi/4.-sl/2.)/((1.-ex*sin(sl))/(1.+ex*sin(sl)))^(ex/2.);
+	mc  = cos(sl)/sqrt(1.0-ex2*(sin(sl)^2));
+	rho = re*mc*T/tc;
+end
+
+y = -rho .* sgn .* cos(sgn.*longitude);
+x =  rho .* sgn .* sin(sgn.*longitude);
+
+[cnt1,cnt2] = find(latitude >= pi / 2.);
+
+if cnt1
+	x(cnt1,1) = 0.0;
+	y(cnt1,1) = 0.0;
+end
Index: /issm/trunk/src/m/latlong/utm2ll.m
===================================================================
--- /issm/trunk/src/m/latlong/utm2ll.m	(revision 13395)
+++ /issm/trunk/src/m/latlong/utm2ll.m	(revision 13395)
@@ -0,0 +1,117 @@
+function  [Lat,Lon] = utm2ll(xx,yy,utmzone)
+% -------------------------------------------------------------------------
+% [Lat,Lon] = utm2ll(x,y,utmzone)
+%
+% Description: Function to convert vectors of UTM coordinates into Lat/Lon vectors (WGS84).
+% Some code has been extracted from UTMIP.m function by Gabriel Ruiz Martinez.
+%
+% Inputs:on)
+%    -3.485713    7.801235 -119.955246  -17.759537  -94.799019  121.640266
+%
+% Example 2: If you need Lat/Lon coordinates in Degrees, Minutes and Seconds
+% [Lat, Lon]=utm2ll(x,y,utmzone);
+% LatDMS=dms2mat(deg2dms(Lat))
+%LatDMS =
+%    40.00         18.00         55.55
+%    46.00         17.00          2.01
+%    37.00         34.00         40.17
+%    28.00         38.00         44.33
+%    38.00         51.00         19.96
+%    25.00          3.00         42.41
+% LonDMS=dms2mat(deg2dms(Lon))
+%LonDMS =
+%    -3.00         29.00          8.61
+%     7.00         48.00          4.40
+%  -119.00         57.00         18.93
+%   -17.00         45.00         34.33
+%   -94.00         47.00         56.47
+%   121.00         38.00         24.96
+%
+% Author:
+%   Rafael Palacios
+%   Universidad Pontificia Comillas
+%   Madrid, Spain
+% Version: Apr/06, Jun/06, Aug/06
+% Aug/06: corrected m-Lint warnings
+%-------------------------------------------------------------------------
+
+% Argument checking
+%
+error(nargchk(3, 3, nargin)); %3 arguments required
+n1=length(xx);
+n2=length(yy);
+n3=size(utmzone,1);
+if (n1~=n2 || n1~=n3)
+	error('x,y and utmzone vectors should have the same number or rows');
+end
+c=size(utmzone,2);
+if (c~=4)
+	error('utmzone should be a vector of strings like "30 T"');
+end
+
+% Memory pre-allocation
+%
+Lat=zeros(n1,1);
+Lon=zeros(n1,1);
+
+% Main Loop
+%
+for i=1:n1
+	if (utmzone(i,4)>'X' || utmzone(i,4)<'C')
+		fprintf('utm2ll: Warning utmzone should be a vector of strings like "30 T", not "30 t"\n');
+	end
+	if (utmzone(i,4)>'M')
+		hemis='N';   % Northern hemisphere
+	else
+		hemis='S';
+	end
+
+	x=xx(i);
+	y=yy(i);
+	zone=str2double(utmzone(i,1:2));
+
+	sa = 6378137.000000 ; sb = 6356752.314245;
+
+	%   e = ( ( ( sa ^ 2 ) - ( sb ^ 2 ) ) ^ 0.5 ) / sa;
+	e2 = ( ( ( sa ^ 2 ) - ( sb ^ 2 ) ) ^ 0.5 ) / sb;
+	e2cuadrada = e2 ^ 2;
+	c = ( sa ^ 2 ) / sb;
+	%   alpha = ( sa - sb ) / sa;             %f
+	%   ablandamiento = 1 / alpha;   % 1/f
+
+	X = x - 500000;
+
+	if hemis == 'S' || hemis == 's'
+		Y = y - 10000000;
+	else
+		Y = y;
+	end
+
+	S = ( ( zone * 6 ) - 183 );
+	lat =  Y / ( 6366197.724 * 0.9996 );
+	v = ( c / ( ( 1 + ( e2cuadrada * ( cos(lat) ) ^ 2 ) ) ) ^ 0.5 ) * 0.9996;
+	a = X / v;
+	a1 = sin( 2 * lat );
+	a2 = a1 * ( cos(lat) ) ^ 2;
+	j2 = lat + ( a1 / 2 );
+	j4 = ( ( 3 * j2 ) + a2 ) / 4;
+	j6 = ( ( 5 * j4 ) + ( a2 * ( cos(lat) ) ^ 2) ) / 3;
+	alfa = ( 3 / 4 ) * e2cuadrada;
+	beta = ( 5 / 3 ) * alfa ^ 2;
+	gama = ( 35 / 27 ) * alfa ^ 3;
+	Bm = 0.9996 * c * ( lat - alfa * j2 + beta * j4 - gama * j6 );
+	b = ( Y - Bm ) / v;
+	Epsi = ( ( e2cuadrada * a^ 2 ) / 2 ) * ( cos(lat) )^ 2;
+	Eps = a * ( 1 - ( Epsi / 3 ) );
+	nab = ( b * ( 1 - Epsi ) ) + lat;
+	senoheps = ( exp(Eps) - exp(-Eps) ) / 2;
+	Delt = atan(senoheps / (cos(nab) ) );
+	TaO = atan(cos(Delt) * tan(nab));
+	longitude = (Delt *(180 / pi ) ) + S;
+	latitude = ( lat + ( 1 + e2cuadrada* (cos(lat)^ 2) - ( 3 / 2 ) * e2cuadrada * sin(lat) * cos(lat) * ( TaO - lat ) ) * ( TaO - lat ) ) * ...
+		(180 / pi);
+
+	Lat(i)=latitude;
+	Lon(i)=longitude;
+
+end
Index: /issm/trunk/src/m/latlong/xy2ll.m
===================================================================
--- /issm/trunk/src/m/latlong/xy2ll.m	(revision 13395)
+++ /issm/trunk/src/m/latlong/xy2ll.m	(revision 13395)
@@ -0,0 +1,72 @@
+function [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel)
+%XY2LL - converts xy to lat long
+%
+%   Converts Polar  Stereographic (X,Y) coordinates for the polar regions to
+%   latitude and longitude Stereographic (X,Y) coordinates for the polar
+%   regions.
+%   Author: Michael P. Schodlok, December 2003 (map2xy.m)
+%
+%   Usage:
+%      [lat,lon] = xy2ll(x,y,sgn);
+%      [lat,lon] = xy2ll(x,y,sgn,central_meridian,standard_parallel);
+%
+%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+%                               -1 : south latitude (default is mer=0  lat=71)
+
+%Get central_meridian and standard_parallel depending on hemisphere
+if nargin==5,
+	delta = central_meridian;
+	slat  = standard_parallel;
+elseif nargin==3
+	if sgn == 1,
+		delta = 45; slat = 70;
+		disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+	elseif sgn==-1,
+		delta = 0;  slat = 71;
+		disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 71ºS Meridian: 0º)');
+	else
+		error('Sign should be either +1 or -1');
+	end
+else
+	help xy2ll
+	error('bad usage');
+end
+
+% Conversion constant from degrees to radians
+cde  = 57.29577951;
+% Radius of the earth in meters
+re   = 6378.273*10^3;
+% Eccentricity of the Hughes ellipsoid squared
+ex2   = .006693883;
+% Eccentricity of the Hughes ellipsoid
+ex    =  sqrt(ex2);
+
+sl  = slat*pi/180.;
+rho = sqrt(x.^2 + y.^2);
+cm = cos(sl) / sqrt(1.0 - ex2 * (sin(sl)^2));
+T = tan((pi / 4.0) - (sl / 2.0)) / ((1.0 - ex * sin(sl)) / (1.0 + ex * sin(sl)))^(ex / 2.0);
+
+if  abs(slat-90.) < 1.e-5
+	T = rho * sqrt((1. + ex)^(1. + ex) * (1. - ex)^(1. - ex)) / 2. / re;
+else
+	T = rho * T / (re * cm);
+end
+
+chi = (pi / 2.0) - 2.0 * atan(T);
+lat = chi + ((ex2 / 2.0) + (5.0 * ex2^2.0 / 24.0) + (ex2^3.0 / 12.0)) * ...
+	sin(2 * chi) + ((7.0 * ex2^2.0 / 48.0) + (29.0 * ex2^3 / 240.0)) * ...
+	sin(4.0 * chi) + (7.0 * ex2^3.0 / 120.0) * sin(6.0 * chi) ;
+
+lat = sgn * lat;
+lon = atan2(sgn * x,-sgn * y);
+lon = sgn * lon;
+
+[res1,res2] = find(rho <= 0.1);
+if res1
+	lat(res1,1) = 90. * sgn;
+	lon(res1,1) = 0.0;
+end
+
+lon = lon * 180. / pi;
+lat = lat * 180. / pi;
+lon = lon - delta; 
Index: /issm/trunk/src/m/materials/paterson.m
===================================================================
--- /issm/trunk/src/m/materials/paterson.m	(revision 13395)
+++ /issm/trunk/src/m/materials/paterson.m	(revision 13395)
@@ -0,0 +1,42 @@
+function rigidity=paterson(temperature)
+%PATERSON - figure out the rigidity of ice for a given temperature
+%
+%   rigidigty (in s^(1/3)Pa) is the flow law paramter in the flow law sigma=B*e(1/3) (Paterson, p97). 
+%   temperature is in Kelvin degrees
+%
+%   Usage:
+%      rigidity=paterson(temperature)
+
+if(temperature<0)
+	error('input temperature should be in Kelvin (positive)');
+end
+T=temperature-273.15;
+
+%The routine below is equivalent to:
+
+% n=3; T=temperature-273;
+% %From paterson,
+% Temp=[0;-2;-5;-10;-15;-20;-25;-30;-35;-40;-45;-50];
+% A=[6.8*10^-15;2.4*10^-15;1.6*10^-15;4.9*10^-16;2.9*10^-16;1.7*10^-16;9.4*
+% 10^-17;5.1*10^-17;2.7*10^-17;1.4*10^-17;7.3*10^-18;3.6*10^-18];;%s-1(kPa-3)
+% %Convert into rigidity B
+% B=A.^(-1/n)*10^3; %s^(1/3)Pa
+% %Now, do a cubic fit between Temp and B: 
+% fittedmodel=fit(Temp,B,'cubicspline');
+% rigidity=fittedmodel(temperature);
+
+rigidity=zeros(length(T),1);
+pos1=find(T<=-45);           rigidity(pos1)=10^8*(-0.000292866376675*(T(pos1)+50).^3+ 0.011672640664130*(T(pos1)+50).^2  -0.325004442485481*(T(pos1)+50)+  6.524779401948101);
+pos2=find(-45<=T & T<-40);   rigidity(pos2)=10^8*(-0.000292866376675*(T(pos2)+45).^3+ 0.007279645014004*(T(pos2)+45).^2  -0.230243014094813*(T(pos2)+45)+  5.154964909039554);
+pos3=find(-40<=T & T<-35);   rigidity(pos3)=10^8*(0.000072737147457*(T(pos3)+40).^3+  0.002886649363879*(T(pos3)+40).^2  -0.179411542205399*(T(pos3)+40)+  4.149132666831214);
+pos4=find(-35<=T & T<-30);   rigidity(pos4)=10^8*(-0.000086144770023*(T(pos4)+35).^3+ 0.003977706575736*(T(pos4)+35).^2  -0.145089762507325*(T(pos4)+35)+  3.333333333333331);
+pos5=find(-30<=T & T<-25);   rigidity(pos5)=10^8*(-0.000043984685769*(T(pos5)+30).^3+ 0.002685535025386*(T(pos5)+30).^2  -0.111773554501713*(T(pos5)+30)+  2.696559088937191);
+pos6=find(-25<=T & T<-20);   rigidity(pos6)=10^8*(-0.000029799523463*(T(pos6)+25).^3+ 0.002025764738854*(T(pos6)+25).^2  -0.088217055680511*(T(pos6)+25)+  2.199331606342181);
+pos7=find(-20<=T & T<-15);   rigidity(pos7)=10^8*(0.000136920904777*(T(pos7)+20).^3+  0.001578771886910*(T(pos7)+20).^2  -0.070194372551690*(T(pos7)+20)+  1.805165505978111);
+pos8=find(-15<=T & T<-10);   rigidity(pos8)=10^8*(-0.000899763781026*(T(pos8)+15).^3+ 0.003632585458564*(T(pos8)+15).^2  -0.044137585824322*(T(pos8)+15)+  1.510778053489523);
+pos9=find(-10<=T & T<-5);    rigidity(pos9)=10^8*(0.001676964325070*(T(pos9)+10).^3-  0.009863871256831*(T(pos9)+10).^2  -0.075294014815659*(T(pos9)+10)+  1.268434288203714);
+pos10=find(-5<=T & T<-2);    rigidity(pos10)=10^8*(-0.003748937622487*(T(pos10)+5).^3+0.015290593619213*(T(pos10)+5).^2  -0.048160403003748*(T(pos10)+5)+  0.854987973338348);
+pos11=find(-2<=T);           rigidity(pos11)=10^8*(-0.003748937622488*(T(pos11)+2).^3-0.018449844983174*(T(pos11)+2).^2  -0.057638157095631*(T(pos11)+2)+  0.746900791092860);
+
+%Now make sure that rigidity is positive
+pos=find(rigidity<0);        rigidity(pos)=10^6;
Index: /issm/trunk/src/m/materials/paterson.py
===================================================================
--- /issm/trunk/src/m/materials/paterson.py	(revision 13395)
+++ /issm/trunk/src/m/materials/paterson.py	(revision 13395)
@@ -0,0 +1,50 @@
+from numpy import *
+
+def paterson(temperature):
+
+    # Local Variables: pos11, pos5, pos10, temperature, pos, T, pos8, pos9, pos6, pos7, pos4, rigidity, pos2, pos3, pos1
+    # Function calls: length, zeros, argwhere, paterson, error
+    #PATERSON - figure out the rigidity of ice for a given temperature
+    #
+    #   rigidigty (in s^(1/3)Pa) is the flow law paramter in the flow law sigma=B*e(1/3) (Paterson, p97). 
+    #   temperature is in Kelvin degrees
+    #
+    #   Usage:
+    #      rigidity=paterson(temperature)
+    
+	pos=argwhere(temperature<0.)
+	if len(pos):
+		print 'input temperature should be in Kelvin (positive)'
+		return []
+    
+	T = temperature-273.15
+	#The routine below is equivalent to:
+	# n=3; T=temperature-273;
+	# %From paterson,
+	# Temp=[0;-2;-5;-10;-15;-20;-25;-30;-35;-40;-45;-50];
+	# A=[6.8*10^-15;2.4*10^-15;1.6*10^-15;4.9*10^-16;2.9*10^-16;1.7*10^-16;9.4*
+	# 10^-17;5.1*10^-17;2.7*10^-17;1.4*10^-17;7.3*10^-18;3.6*10^-18];;%s-1(kPa-3)
+	# %Convert into rigidity B
+	# B=A.^(-1/n)*10^3; %s^(1/3)Pa
+	# %Now, do a cubic fit between Temp and B: 
+	# fittedmodel=fit(Temp,B,'cubicspline');
+	# rigidity=fittedmodel(temperature);
+
+	rigidity=zeros(len(T))
+	pos1=argwhere(T<=-45);           rigidity[pos1]=10**8*(-0.000292866376675*(T[pos1]+50)**3+ 0.011672640664130*(T[pos1]+50)**2  -0.325004442485481*(T[pos1]+50)+  6.524779401948101)
+	pos2=argwhere(logical_and(-45<=T,T<-40));   rigidity[pos2]=10**8*(-0.000292866376675*(T[pos2]+45)**3+ 0.007279645014004*(T[pos2]+45)**2  -0.230243014094813*(T[pos2]+45)+  5.154964909039554)
+	pos3=argwhere(logical_and(-40<=T,T<-35));   rigidity[pos3]=10**8*(0.000072737147457*(T[pos3]+40)**3+  0.002886649363879*(T[pos3]+40)**2  -0.179411542205399*(T[pos3]+40)+  4.149132666831214)
+	pos4=argwhere(logical_and(-35<=T,T<-30));   rigidity[pos4]=10**8*(-0.000086144770023*(T[pos4]+35)**3+ 0.003977706575736*(T[pos4]+35)**2  -0.145089762507325*(T[pos4]+35)+  3.333333333333331)
+	pos5=argwhere(logical_and(-30<=T,T<-25));   rigidity[pos5]=10**8*(-0.000043984685769*(T[pos5]+30)**3+ 0.002685535025386*(T[pos5]+30)**2  -0.111773554501713*(T[pos5]+30)+  2.696559088937191)
+	pos6=argwhere(logical_and(-25<=T,T<-20));   rigidity[pos6]=10**8*(-0.000029799523463*(T[pos6]+25)**3+ 0.002025764738854*(T[pos6]+25)**2  -0.088217055680511*(T[pos6]+25)+  2.199331606342181)
+	pos7=argwhere(logical_and(-20<=T,T<-15));   rigidity[pos7]=10**8*(0.000136920904777*(T[pos7]+20)**3+  0.001578771886910*(T[pos7]+20)**2  -0.070194372551690*(T[pos7]+20)+  1.805165505978111)
+	pos8=argwhere(logical_and(-15<=T,T<-10));   rigidity[pos8]=10**8*(-0.000899763781026*(T[pos8]+15)**3+ 0.003632585458564*(T[pos8]+15)**2  -0.044137585824322*(T[pos8]+15)+  1.510778053489523)
+	pos9=argwhere(logical_and(-10<=T,T<-5));    rigidity[pos9]=10**8*(0.001676964325070*(T[pos9]+10)**3-  0.009863871256831*(T[pos9]+10)**2  -0.075294014815659*(T[pos9]+10)+  1.268434288203714)
+	pos10=argwhere(logical_and(-5<=T,T<-2));    rigidity[pos10]=10**8*(-0.003748937622487*(T[pos10]+5)**3+0.015290593619213*(T[pos10]+5)**2  -0.048160403003748*(T[pos10]+5)+  0.854987973338348)
+	pos11=argwhere(-2<=T);           rigidity[pos11]=10**8*(-0.003748937622488*(T[pos11]+2)**3-0.018449844983174*(T[pos11]+2)**2  -0.057638157095631*(T[pos11]+2)+  0.746900791092860)
+
+	#Now make sure that rigidity is positive
+	pos=argwhere(rigidity<0);        rigidity[pos]=1**6 
+
+	return rigidity
+
Index: /issm/trunk/src/m/mech/basalstress.m
===================================================================
--- /issm/trunk/src/m/mech/basalstress.m	(revision 13395)
+++ /issm/trunk/src/m/mech/basalstress.m	(revision 13395)
@@ -0,0 +1,22 @@
+function [bx by b]=basalstress(md)
+%BASALSTRESS - compute basal stress from basal drag and geometric information. 
+%
+%   Usage:
+%      [bx by b]=basalstress(md);
+%
+%   See also: plot_basaldrag
+
+
+%compute exponents
+s=averaging(md,1./md.friction.p,0);
+r=averaging(md,md.friction.q./md.friction.p,0);
+
+%compute horizontal velocity
+ub=sqrt(md.initialization.vx.^2+md.initialization.vy.^2)/md.constants.yts;
+ubx=md.initialization.vx/md.constants.yts;
+uby=md.initialization.vy/md.constants.yts;
+
+%compute basal drag
+bx=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed)).^r.*(md.friction.coefficient).^2.*ubx.^s;
+by=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed)).^r.*(md.friction.coefficient).^2.*uby.^s;
+b=(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed)).^r.*(md.friction.coefficient).^2.*ub.^s;
Index: /issm/trunk/src/m/mech/cfl_step.m
===================================================================
--- /issm/trunk/src/m/mech/cfl_step.m	(revision 13395)
+++ /issm/trunk/src/m/mech/cfl_step.m	(revision 13395)
@@ -0,0 +1,23 @@
+function maxtime=cfl_step(md,vx,vy);
+%CFL_STEP - return the maximum time step for the model in years
+%
+%   Dt < 0.5 / ( u/Dx +v/Dy )
+%
+%   Usage:
+%      maxtime=cfl_step(md,vx,vy);
+%
+%   Example:
+%      dt=cfl_step(md,md.results.DiagnosticSolution.Vx,md.results.DiagnosticSolution.Vy)
+
+%Check length of velocities 
+if size(vx,1)~=md.mesh.numberofvertices & size(vy,1)~=md.mesh.numberofvertices,
+	error('timestpes error message: size of velocity components must be the same as md.mesh.numberofvertices');
+end
+
+index=md.mesh.elements;
+edgex=max(md.mesh.x(index),[],2)-min(md.mesh.x(index),[],2);
+edgey=max(md.mesh.y(index),[],2)-min(md.mesh.y(index),[],2);
+vx=max(abs(vx(index)),[],2);
+vy=max(abs(vy(index)),[],2);
+
+maxtime=1/2*min(1./(vx./edgex+vy./edgey));
Index: /issm/trunk/src/m/mech/drivingstress.m
===================================================================
--- /issm/trunk/src/m/mech/drivingstress.m	(revision 13395)
+++ /issm/trunk/src/m/mech/drivingstress.m	(revision 13395)
@@ -0,0 +1,18 @@
+function [px,py,pmag]=drivingstress(md)
+%DRIVINGSTRESS -  evaluates the driving stress
+%
+%   The driving stress is computed according to the following formula: 
+%   driving stress= rho_ice*g*H*slope
+%
+%   Usage:
+%      [Fx,Fy,Fmag]=drivingstress(md)
+
+%Get slope
+[sx,sy,s]=slope(md);
+
+%Average thickness over elements
+thickness_bar=(md.geometry.thickness(md.mesh.elements(:,1))+md.geometry.thickness(md.mesh.elements(:,2))+md.geometry.thickness(md.mesh.elements(:,3)))/3;
+
+px=md.materials.rho_ice*md.constants.g*thickness_bar.*sx;
+py=md.materials.rho_ice*md.constants.g*thickness_bar.*sy;
+pmag=sqrt(px.^2+py.^2);
Index: /issm/trunk/src/m/mech/mechanicalproperties.m
===================================================================
--- /issm/trunk/src/m/mech/mechanicalproperties.m	(revision 13395)
+++ /issm/trunk/src/m/mech/mechanicalproperties.m	(revision 13395)
@@ -0,0 +1,118 @@
+function md=mechanicalproperties(md,vx,vy)
+%MECHANICALPROPERTIES - compute stress and strain rate for a goven velocity
+%
+%   this routine computes the components of the stress tensor
+%   strain rate tensor and their respective principal directions.
+%   the results are in the model md: md.results
+%
+%   Usage:
+%      md=mechanicalproperties(md,vx,vy)
+%
+%   Example:
+%      md=mechanicalproperties(md,md.initialization.vx,md.initialization.vy);
+%      md=mechanicalproperties(md,md.inversion.vx_obs,md.inversion.vy_obs);
+
+%some checks
+if length(vx)~=md.mesh.numberofvertices | length(vy)~=md.mesh.numberofvertices,
+	error(['the input velocity should be of size ' num2str(md.mesh.numberofvertices) '!'])
+end
+if ~(md.mesh.dimension==2)
+	error('only 2d model supported yet');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non macayeal elements. These will be treated like MacAyeal''s elements');
+end
+
+%initialization
+numberofelements=md.mesh.numberofelements;
+index=md.mesh.elements;
+summation=[1;1;1];
+directionsstress=zeros(numberofelements,4);
+directionsstrain=zeros(numberofelements,4);
+valuesstress=zeros(numberofelements,2);
+valuesstrain=zeros(numberofelements,2);
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,md.mesh.x,md.mesh.y);
+
+%compute shear
+vxlist=vx(index)/md.constants.yts;
+vylist=vy(index)/md.constants.yts;
+ux=(vxlist.*alpha)*summation;
+uy=(vxlist.*beta)*summation;
+vx=(vylist.*alpha)*summation;
+vy=(vylist.*beta)*summation;						
+uyvx=(vx+uy)./2;
+clear vxlist vylist
+
+%compute viscosity
+nu=zeros(numberofelements,1);
+B_bar=md.materials.rheology_B(index)*summation/3;
+power=(md.materials.rheology_n-1)./(2*md.materials.rheology_n);
+second_inv=(ux.^2+vy.^2+((uy+vx).^2)/4+ux.*vy);
+%some corrections
+location=find(second_inv~=0);
+nu(location)=B_bar(location)./(second_inv(location).^power(location));
+location=find(second_inv==0 & power~=0);
+nu(location)=10^18; 	%arbitrary maximum viscosity to apply where there is no effective shear
+location=find(second_inv==0 & power==0);
+nu(location)=B_bar(location);
+clear B_bar location second_inv power
+
+%compute stress
+tau_xx=nu.*ux;
+tau_yy=nu.*vy;
+tau_xy=nu.*uyvx;
+
+%compute principal properties of stress
+for i=1:numberofelements,
+
+	%compute stress and strainrate matrices
+	stress=[tau_xx(i) tau_xy(i)
+	tau_xy(i)  tau_yy(i)];
+	strain=[ux(i) uyvx(i)
+	uyvx(i)  vy(i)];
+
+	%eigen values and vectors
+	[directions,value]=eig(stress);
+	valuesstress(i,:)=[value(1,1) value(2,2)];
+	directionsstress(i,:)=directions(:)';
+	[directions,value]=eig(strain);
+	valuesstrain(i,:)=[value(1,1) value(2,2)];
+	directionsstrain(i,:)=directions(:)';
+end
+
+%plug onto the model
+%NB: Matlab sorts the eigen value in increasing order, we want the reverse
+stress=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
+stress.xx=tau_xx;
+stress.yy=tau_yy;
+stress.xy=tau_xy;
+stress.principalvalue2=valuesstress(:,1);
+stress.principalaxis2=directionsstress(:,1:2);
+stress.principalvalue1=valuesstress(:,2);
+stress.principalaxis1=directionsstress(:,3:4);
+stress.effectivevalue=1/sqrt(2)*sqrt(stress.xx.^2+stress.yy.^2+2*stress.xy.^2);
+md.results.stress=stress;
+
+strainrate=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
+strainrate.xx=ux;
+strainrate.yy=vy;
+strainrate.xy=uyvx;
+strainrate.principalvalue2=valuesstrain(:,1)*(365.25*24*3600); %strain rate in 1/a instead of 1/s
+strainrate.principalaxis2=directionsstrain(:,1:2);
+strainrate.principalvalue1=valuesstrain(:,2)*(365.25*24*3600); %strain rate in 1/a instead of 1/s
+strainrate.principalaxis1=directionsstrain(:,3:4);
+strainrate.effectivevalue=1/sqrt(2)*sqrt(strainrate.xx.^2+strainrate.yy.^2+2*strainrate.xy.^2);
+md.results.strainrate=strainrate;
+
+deviatoricstress=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalaxis1',[],'principalvalue2',[],'principalaxis2',[],'effectivevalue',[]);
+deviatoricstress.xx=tau_xx;
+deviatoricstress.yy=tau_yy;
+deviatoricstress.xy=tau_xy;
+deviatoricstress.principalvalue2=valuesstress(:,1);
+deviatoricstress.principalaxis2=directionsstress(:,1:2);
+deviatoricstress.principalvalue1=valuesstress(:,2);
+deviatoricstress.principalaxis1=directionsstress(:,3:4);
+deviatoricstress.effectivevalue=1/sqrt(2)*sqrt(stress.xx.^2+stress.yy.^2+2*stress.xy.^2);
+md.results.deviatoricstress=deviatoricstress;
Index: /issm/trunk/src/m/mech/shear2d.m
===================================================================
--- /issm/trunk/src/m/mech/shear2d.m	(revision 13395)
+++ /issm/trunk/src/m/mech/shear2d.m	(revision 13395)
@@ -0,0 +1,23 @@
+function [sx,sy,sxy,s]=shear2d(md)
+%SHEAR2D - computes 2d strain rate
+%
+%   This routine computes the strain rate of 2d models
+%
+%   Usage:
+%      [sx,sy,sxy,s]=shear2d(md);
+%      s=shear2d(md);
+
+[alpha beta]=GetNodalFunctionsCoeff(md.mesh.elements,md.mesh.x,md.mesh.y); 
+
+summation=[1;1;1];
+sx=(md.initialization.vx(md.mesh.elements).*alpha)*summation;
+uy=(md.initialization.vx(md.mesh.elements).*beta)*summation;
+vx=(md.initialization.vy(md.mesh.elements).*alpha)*summation;
+sy=(md.initialization.vy(md.mesh.elements).*beta)*summation;						
+sxy=(uy+vx)/2;
+s=sqrt(sx.^2+sy.^2+sxy.^2+sx.*sy);
+
+%if user requested only one output, it must be the norm
+if nargout==1,
+	sx=s;
+end
Index: /issm/trunk/src/m/mesh/ComputeHessian.m
===================================================================
--- /issm/trunk/src/m/mesh/ComputeHessian.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/ComputeHessian.m	(revision 13395)
@@ -0,0 +1,60 @@
+function hessian=ComputeHessian(index,x,y,field,type)
+%COMPUTEHESSIAN - compute hessian matrix from a field
+%
+%   Compute the hessian matrix of a given field
+%   return the three components Hxx Hxy Hyy
+%   for each element or each node
+%
+%   Usage:
+%      hessian=ComputeHessian(index,x,y,field,type)
+%
+%   Example:
+%      hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,md.inversion.vel_obs,'node')
+
+%some variables
+numberofnodes=length(x);
+numberofelements=size(index,1);
+
+%some checks
+if length(field)~=numberofnodes & length(field)~=numberofelements,
+	error('ComputeHessian error message: the given field size not supported yet');
+end
+if strcmpi(type,'node') & strcmpi(type,'element'),
+	error('ComputeHessian error message: only ''node'' or ''element'' type supported yet');
+end
+
+%initialization
+line=index(:);
+linesize=3*numberofelements;
+
+%get areas and  nodal functions coefficients N(x,y)=alpha x + beta y + gamma 
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+areas=GetAreas(index,x,y);
+
+%comput weights that holds the volume of all the element holding the node i
+weights=sparse(line,ones(linesize,1),repmat(areas,3,1),numberofnodes,1);
+
+%compute field on nodes if on elements
+if length(field)==numberofelements,
+	field=sparse(line,ones(linesize,1),repmat(areas.*field,3,1),numberofnodes,1)./weights ;
+end
+
+%Compute gradient for each element
+grad_elx=sum(field(index).*alpha,2); 
+grad_ely=sum(field(index).*beta,2);
+
+%Compute gradient for each node (average of the elements around)
+gradx=sparse(line,ones(linesize,1),repmat(areas.*grad_elx,3,1),numberofnodes,1);
+grady=sparse(line,ones(linesize,1),repmat(areas.*grad_ely,3,1),numberofnodes,1);
+gradx=gradx./weights;
+grady=grady./weights;
+
+%Compute hessian for each element
+hessian=[sum(gradx(index).*alpha,2) sum(grady(index).*alpha,2) sum(grady(index).*beta,2)];
+
+if strcmpi(type,'node')
+	%Compute Hessian on the nodes (average of the elements around)
+	hessian=[sparse(line,ones(linesize,1),repmat(areas.*hessian(:,1),3,1),numberofnodes,1)./weights ...
+		sparse(line,ones(linesize,1),repmat(areas.*hessian(:,2),3,1),numberofnodes,1)./weights ...
+		sparse(line,ones(linesize,1),repmat(areas.*hessian(:,3),3,1),numberofnodes,1)./weights ];
+end
Index: /issm/trunk/src/m/mesh/ComputeMetric.m
===================================================================
--- /issm/trunk/src/m/mesh/ComputeMetric.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/ComputeMetric.m	(revision 13395)
@@ -0,0 +1,66 @@
+function metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos)
+%COMPUTEMETRIC - compute metric from an Hessian
+%
+%   Usage:
+%      metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos)
+%      pos is contains the positions where the metric is wished to be maximized (water?)
+%
+%   Example:
+%      metric=ComputeMetric(hessian,2/9,10^-1,100,10^5,find(md.nodeonwater)
+
+%first, find the eigen values of eah line of H=[hessian(i,1) hessian(i,2); hessian(i,2)  hessian(i,3)]
+a=hessian(:,1); b=hessian(:,2); d=hessian(:,3);
+lambda1=0.5*((a+d)+sqrt(4*b.^2+(a-d).^2));
+lambda2=0.5*((a+d)-sqrt(4*b.^2+(a-d).^2));
+pos1=find(lambda1==0);
+pos2=find(lambda2==0);
+pos3=find(b==0 & lambda1==lambda2);
+
+%Modify the eigen values to control the shape of the elements
+lambda1=min(max(abs(lambda1)*scale/epsilon,1/hmax^2),1/hmin^2);
+lambda2=min(max(abs(lambda2)*scale/epsilon,1/hmax^2),1/hmin^2);
+
+%compute eigen vectors
+norm1=sqrt(8*b.^2+2*(d-a).^2+2*(d-a).*sqrt((a-d).^2+4*b.^2));
+v1x=2*b./norm1;
+v1y=((d-a)+sqrt((a-d).^2+4*b.^2))./norm1;
+norm2=sqrt(8*b.^2+2*(d-a).^2-2*(d-a).*sqrt((a-d).^2+4*b.^2));
+v2x=2*b./norm2;
+v2y=((d-a)-sqrt((a-d).^2+4*b.^2))./norm2;
+
+v1x(pos3)=1; v1y(pos3)=0;
+v2x(pos3)=0; v2y(pos3)=1;
+
+%Compute new metric (for each node M=V*Lambda*V^-1)
+metric=full([(v1x.*v2y-v1y.*v2x).^(-1).*(lambda1.*v2y.*v1x-lambda2.*v1y.*v2x) ...
+	(v1x.*v2y-v1y.*v2x).^(-1).*(lambda1.*v1y.*v2y-lambda2.*v1y.*v2y) ...
+	(v1x.*v2y-v1y.*v2x).^(-1).*(-lambda1.*v2x.*v1y+lambda2.*v1x.*v2y)]);
+
+%some corrections for 0 eigen values
+metric(pos1,:)=repmat([1/hmax^2 0 1/hmax^2],length(pos1),1);
+metric(pos2,:)=repmat([1/hmax^2 0 1/hmax^2],length(pos2),1);
+
+%take care of water elements
+metric(pos,:)=repmat([1/hmax^2 0 1/hmax^2],length(pos),1);
+
+%take care of NaNs if any (use Matlab eig in a loop)
+[pos posj]=find(isnan(metric)); clear posj;
+if ~isempty(pos),
+	fprintf(' %i %s',length(pos),'NaN found in the metric. Use Matlab routine...');
+	for i=1:length(pos)
+		H=[hessian(pos(i),1) hessian(pos(i),2)
+		hessian(pos(i),2) hessian(pos(i),3)];
+		[u,v]=eig(full(H));
+		lambda1=v(1,1);
+		lambda2=v(2,2);
+		v(1,1)=min(max(abs(lambda1)*scale/epsilon,1/hmax^2),1/hmin^2);
+		v(2,2)=min(max(abs(lambda2)*scale/epsilon,1/hmax^2),1/hmin^2);
+
+		metricTria=u*v*u^(-1);
+		metric(pos(i),:)=[metricTria(1,1) metricTria(1,2) metricTria(2,2)];
+	end
+end
+
+if any(isnan(metric)),
+	error('ComputeMetric error message: NaN in the metric despite our efforts...')
+end
Index: /issm/trunk/src/m/mesh/ElementsFromEdge.m
===================================================================
--- /issm/trunk/src/m/mesh/ElementsFromEdge.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/ElementsFromEdge.m	(revision 13395)
@@ -0,0 +1,15 @@
+function edgeelements=ElementsFromEdge(elements,A,B) 
+%ELEMENTSFROMEDGE: find elements connected to one edge defined by nodes A and B
+%
+% Usage: edgeelements=ElementsFromEdge(elements,A,B) 
+%
+% Eg:    edgeelements=ElementsFromEdge(md.mesh.elements,tip1,tip2)
+%
+%
+edgeelements=find(...
+(elements(:,1)==A & elements(:,2)==B )| ...
+(elements(:,1)==A & elements(:,3)==B )| ...
+(elements(:,2)==A & elements(:,3)==B )| ...
+(elements(:,2)==A & elements(:,1)==B )| ...
+(elements(:,3)==A & elements(:,1)==B )| ...
+(elements(:,3)==A & elements(:,2)==B ));
Index: /issm/trunk/src/m/mesh/FixMesh.m
===================================================================
--- /issm/trunk/src/m/mesh/FixMesh.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/FixMesh.m	(revision 13395)
@@ -0,0 +1,45 @@
+function  [index2 x2 y2 value2]=FixMesh(index,x,y,value)
+% FIXMESH - FixMesh fix mesh with broken triangles, orphan vertices, etc ...
+%
+%   Usage: 
+%      [index2 x2 y2 value2]=FixMesh(index,x,y,value)
+%      where index,x,y is a delaunay triangulation, 
+%      value is a field on the input triangulation, with values at the vertices
+%      index2,x2,y2,value2 is the repaired triangulation, with new values on new vertices
+%
+%
+
+%duplicate inputs
+index2=index;
+x2=x;
+y2=y;
+value2=value;
+
+%First, look for orphan vertices, and take them out.
+flags=zeros(length(x2),1); flags(index2)=1;
+orphans=find(flags==0);
+
+while ~isempty(orphans),
+
+	%take the first orphan, the lower numbered, and take it out
+	orphan=orphans(1);
+
+	%first x,y,value
+	x2(orphan)=[];
+	y2(orphan)=[];
+	value2(orphan)=[];
+
+	%now, the index:
+	pos=find(index2>orphan); index2(pos)=index2(pos)-1;
+	
+	%look again for orphans on new mesh
+	flags=zeros(length(x2),1);flags(index2)=1;
+	orphans=find(flags==0);
+end
+
+%Check all triangles are well oriented.
+aires=GetAreas(index2,x2,y2);
+pos=find(aires<0);
+temp=index2(pos,1);
+index2(pos,1)=index2(pos,2);
+index2(pos,2)=temp;
Index: /issm/trunk/src/m/mesh/GetNodalFunctionsCoeff.m
===================================================================
--- /issm/trunk/src/m/mesh/GetNodalFunctionsCoeff.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/GetNodalFunctionsCoeff.m	(revision 13395)
@@ -0,0 +1,56 @@
+function [alpha beta varargout]=GetNodalFunctionsCoeff(index,x,y)
+%GETNODELFUNCTIONSCOEFF - compute nodal functions coefficients
+%
+%   Compute the coefficients alpha beta and optionaly gamma of
+%   2d triangular elements. For each element, the nodal function
+%   is defined as:
+%   N(x,y)=sum(i=1:3) alpha_i * x + beta_i * y + gamma_i
+%
+%   Usage:
+%      [alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+%      [alpha beta gamma]=GetNodalFunctionsCoeff(index,x,y);
+%
+%   Example:
+%      [alpha beta gamma]=GetNodalFunctionsCoeff(md.mesh.elements,md.mesh.x,md.mesh.y);
+
+%make columns out of x and y
+x=x(:); y=y(:);
+
+%get nels and nods
+nels=size(index,1);
+nods=length(x);
+
+%some checks
+if nargin~=3 | (nargout~=2 & nargout~=3),
+	help GetNodalFunctionsCoeff
+	error('GetNodalFunctionsCoeff error message: bad usage')
+end
+if length(y)~=nods,
+	error('GetNodalFunctionsCoeff error message: x and y do not have the same length')
+end
+if max(index(:))>nods,
+	error(['GetNodalFunctionsCoeff error message: index should not have values above ' num2str(nods) ])
+end
+if size(index,2)~=3,
+	error('GetNodalFunctionsCoeff error message: only 2d meshes supported. index should have 3 columns.')
+end
+
+%initialize output
+alpha=zeros(nels,3);
+beta=zeros(nels,3);
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
+x1=x(index(:,1)); x2=x(index(:,2)); x3=x(index(:,3));
+y1=y(index(:,1)); y2=y(index(:,2)); y3=y(index(:,3));
+invdet=1./(x1.*(y2-y3)-x2.*(y1-y3)+x3.*(y1-y2));
+
+%get alpha and beta
+alpha=[invdet.*(y2-y3) invdet.*(y3-y1) invdet.*(y1-y2)];
+beta =[invdet.*(x3-x2) invdet.*(x1-x3) invdet.*(x2-x1)];
+
+%get gamma if requested
+if nargout==3,
+	gamma=zeros(nels,3);
+	gamma=[invdet.*(x2.*y3-x3.*y2) invdet.*(y1.*x3-y3.*x1) invdet.*(x1.*y2-x2.*y1)];
+	varargout{1}=gamma;
+end
Index: /issm/trunk/src/m/mesh/MergeMetrics.m
===================================================================
--- /issm/trunk/src/m/mesh/MergeMetrics.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/MergeMetrics.m	(revision 13395)
@@ -0,0 +1,15 @@
+function metric=MergeMetrics(metric1,metric2)
+
+M1xx=metric1(:,1); M1xy=metric1(:,2); M1yy=metric1(:,3);
+M1lambda1=0.5*((M1xx+M1yy)+sqrt(4*M1xy.^2+(M1xx-M1yy).^2));
+M1lambda2=0.5*((M1xx+M1yy)-sqrt(4*M1xy.^2+(M1xx-M1yy).^2));
+lambda1=min(M1lambda1,M1lambda2);
+
+M2xx=metric1(:,1); M2xy=metric1(:,2); M2yy=metric1(:,3);
+M2lambda1=0.5*((M2xx+M2yy)+sqrt(4*M2xy.^2+(M2xx-M2yy).^2));
+M2lambda2=0.5*((M2xx+M2yy)-sqrt(4*M2xy.^2+(M2xx-M2yy).^2));
+lambda2=min(M2lambda2,M2lambda2);
+
+metric=metric1;
+pos=find(lambda2<lambda1);
+metric(pos,:)=metric2(pos,:);
Index: /issm/trunk/src/m/mesh/MeshQuality.m
===================================================================
--- /issm/trunk/src/m/mesh/MeshQuality.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/MeshQuality.m	(revision 13395)
@@ -0,0 +1,82 @@
+function quality=MeshQuality(md,epsilon,hmin,hmax);
+%MESHQUALITY - compute mesh quality
+%
+%   Usage:
+%      MeshQuality(md,epsilon,hmin,hmax);
+
+%Get some variables from the model
+index=md.mesh.elements;
+x=md.mesh.x;
+y=md.mesh.y;
+
+%2d geometric parameter (do not change)
+scale=2/9; 
+
+%Compute Hessian
+hessian=ComputeHessian(index,x,y,md.inversion.vel_obs,'node');
+
+%Compute metric
+if length(md.nodeonwater)==md.mesh.numberofvertices,
+	pos=find(md.nodeonwater);
+else
+	pos=[];
+end
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos);
+
+%Get Areas
+areas=GetAreas(index,x,y);
+
+%length edges vectors
+e1x=[x(index(:,2))-x(index(:,1))];
+e1y=[y(index(:,2))-y(index(:,1))];
+e2x=[x(index(:,3))-x(index(:,2))];
+e2y=[y(index(:,3))-y(index(:,2))];
+e3x=[x(index(:,1))-x(index(:,3))];
+e3y=[y(index(:,1))-y(index(:,3))];
+
+%metric of each the 3 nodes for each element
+M1=metric(index(:,1),:);
+M2=metric(index(:,2),:);
+M3=metric(index(:,3),:);
+
+%Get edge length in the metric
+L1=1/2*(sqrt(e2x.*(M2(:,1).*e2x+M2(:,2).*e2y)+e2y.*(M2(:,2).*e2x+M2(:,3).*e2y))+sqrt(e1x.*(M1(:,1).*e1x+M1(:,2).*e1y)+e1y.*(M1(:,2).*e1x+M1(:,3).*e1y)));
+L2=1/2*(sqrt(e3x.*(M3(:,1).*e3x+M3(:,2).*e3y)+e3y.*(M3(:,2).*e3x+M3(:,3).*e3y))+sqrt(e2x.*(M2(:,1).*e2x+M2(:,2).*e2y)+e2y.*(M2(:,2).*e2x+M2(:,3).*e2y)));
+L3=1/2*(sqrt(e1x.*(M1(:,1).*e1x+M1(:,2).*e1y)+e1y.*(M1(:,2).*e1x+M1(:,3).*e1y))+sqrt(e3x.*(M3(:,1).*e3x+M3(:,2).*e3y)+e3y.*(M3(:,2).*e3x+M3(:,3).*e3y)));
+
+%area in the metric
+V=1/3*areas.*(sqrt(M1(:,1).*M1(:,3)-M1(:,2).^2)+sqrt(M2(:,1).*M2(:,3)-M2(:,2).^2)+sqrt(M3(:,1).*M3(:,3)-M3(:,2).^2));
+
+%compute quality:
+quality=4*sqrt(3)*V./(L1+L2+L3);
+
+%compute error
+a=hessian(:,1); b=hessian(:,2); d=hessian(:,3);
+a=a(index)*[1;1;1]/3;
+b=b(index)*[1;1;1]/3;
+d=d(index)*[1;1;1]/3;
+lambda1=0.5*((a+d)+sqrt(4*b.^2+(a-d).^2));
+lambda2=0.5*((a+d)-sqrt(4*b.^2+(a-d).^2));
+lambda1=min(max(abs(lambda1)*scale/epsilon,1/hmax^2),1/hmin^2);
+lambda2=min(max(abs(lambda2)*scale/epsilon,1/hmax^2),1/hmin^2);
+if length(md.nodeonwater)==md.mesh.numberofvertices;
+	pos=find(md.nodeonwater);
+	lambda1(pos)=0;
+	lambda2(pos)=0;
+end
+lambda1=lambda1(index)*[1;1;1]/3;
+lambda2=lambda2(index)*[1;1;1]/3;
+
+lambdamax=max(lambda1,lambda2);
+hmax=max(max(sqrt(e1x.^2+e1y.^2),sqrt(e2x.^2+e2y.^2)),sqrt(e3x.^2+e3y.^2));
+epsilon=scale*hmax.^2.*lambdamax;
+
+%display
+%X=0:0.1:4; hist(quality,X); xlim([0 3]); title('mesh quality distribution','FontSize',14);
+%plotmodel(md,'data',epsilon,'title','Interpolation error','figure',2)
+disp(sprintf('\n%s','Mesh Quality'));
+disp(sprintf('   %s %g','Average Mesh quality: ',mean(quality)));
+disp(sprintf('   %s %g','Worst Element quality:',max(quality)));
+disp(sprintf('\n%s','Interpolation Error'));
+disp(sprintf('   %s %g %s','Average interpolation error:',mean(epsilon),'m/yr'));
+disp(sprintf('   %s %g %s','Maximum interpolation error:',max(epsilon),'m/yr'));
Index: /issm/trunk/src/m/mesh/NodeInElement.m
===================================================================
--- /issm/trunk/src/m/mesh/NodeInElement.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/NodeInElement.m	(revision 13395)
@@ -0,0 +1,42 @@
+function node_in_element=NodeInElement(newx,newy,elements,x,y,nodeconnectivity);
+% NODEINELEMENT - find for a list of nodes (in newx,newy), which elements in the mesh (elements,x,y) they belong to.
+%
+%    Usage:
+%      node_in_element=NodeInElement(newx,newy,elements,x,y,md.mesh.vertexconnectivity);
+%
+%  See also Nodeconnectivity
+%
+epsilon=10^-10;
+
+%compute some quantities that will speed up the process
+x3x1=x(elements(:,1))-x(elements(:,3));
+y3y1=y(elements(:,1))-y(elements(:,3));
+x3x2=x(elements(:,2))-x(elements(:,3));
+y3y2=y(elements(:,2))-y(elements(:,3));
+x3=x(elements(:,3));
+y3=y(elements(:,3));
+delta=x(elements(:,2)).*y(elements(:,3))-y(elements(:,2)).*x(elements(:,3))-x(elements(:,1)).*y(elements(:,3))+y(elements(:,1)).*x(elements(:,3))+x(elements(:,1)).*y(elements(:,2))-y(elements(:,1)).*x(elements(:,2));
+
+%max connectivity:
+max_connectivity=max(nodeconnectivity(:,end));
+node_in_element=zeros(length(newx),max_connectivity+1); %last column is the number of elements to which the row node is connected.
+
+for i=1:length(newx),
+	x0=newx(i);
+	y0=newy(i);
+	
+	%first area coordinate
+	area_1=(y3y2.*(x0-x3)-x3x2.*(y0-y3))./delta;
+	%second area coordinate
+	area_2=(x3x1.*(y0-y3)-y3y1.*(x0-x3))./delta;
+	%third area coordinate
+	area_3=1-area_1-area_2;
+	
+	%get elements for which all area coordinates are positive (meaning (x0,y0) belongs to these elements
+	pos=find((area_1>=0-epsilon) & (area_2>=0-epsilon) & (area_3>=0-epsilon));
+
+	num_elements=length(pos);
+
+	node_in_element(i,1:num_elements)=pos;
+	node_in_element(i,end)=num_elements;
+end
Index: /issm/trunk/src/m/mesh/ProfileProjectOntoMesh.m
===================================================================
--- /issm/trunk/src/m/mesh/ProfileProjectOntoMesh.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/ProfileProjectOntoMesh.m	(revision 13395)
@@ -0,0 +1,66 @@
+function mesh_profile=ProfileProjectOntoMesh(md,profile)
+%PROFILEPROJECTONTOMESH: project a profile (made of arbitrary points) onto a mesh, so that we end 
+%                        up with a list of segments self contained onto elements.
+%
+% Usage: mesh_profile=ProfileProjectOntoMesh(md,profile)
+%
+% See also intersections.m
+
+%make a curve out of the mesh, to use the intersections routine.
+rows=[md.mesh.elements md.mesh.elements(:,1)]'; rows=rows(:);
+x=md.mesh.x(rows);
+y=md.mesh.y(rows);
+
+%[x0,y0] = intersections(profile.x,profile.y,x,y,1);
+[x0,y0,indices,j] = intersections(profile.x,profile.y,x,y);
+
+%  sort intersections to create segments in order and continuous along profile
+[indices,isort]=sort(indices);
+j =j (isort);
+x0=x0(isort);
+y0=y0(isort);
+
+%process x0,y0 so they do not include profile.x or profile.y
+processed_indices=[];
+processed_x=[];
+processed_y=[];
+for i=1:numel(indices),
+	if(((indices(i)-floor(indices(i)))~=0) && ((ceil(indices(i))-indices(i))~=0))
+		processed_indices=[processed_indices;floor(indices(i))];
+		processed_x=[processed_x;x0(i)];
+		processed_y=[processed_y;y0(i)];
+	end
+end
+
+%now merge profile.x,profile.y with processed_x,processed_y, at locations processed_indices:
+newx=profile.x;
+newy=profile.y;
+
+count=1;
+for i=1:numel(profile.x),
+	pos=find(processed_indices==i);
+	if ~isempty(pos),
+		newx=[newx(1:count); processed_x(pos); newx(count+1:end)];
+		newy=[newy(1:count); processed_y(pos); newy(count+1:end)];
+		count=count+length(pos)+1;
+	end
+end
+
+%now, for each node, figure out which element it belongs to.
+node_in_element=NodeInElement(newx,newy,md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.vertexconnectivity);
+
+% eliminate nodes that don't fall in any element
+% (profile may start and/or end externally and/or cross holes in the model)
+
+ind=find(node_in_element(:,9)>0);
+newx=newx(ind,:);
+newy=newy(ind,:);
+node_in_element=node_in_element(ind,:);
+
+mesh_profile=[newx(1:end-1) newy(1:end-1) newx(2:end) newy(2:end) zeros(length(newy(2:end)),1)];
+
+%find which element each segment belongs to.
+for i=1:length(newx)-1,
+	common=intersect(node_in_element(i,1:node_in_element(i,end)), node_in_element(i+1,1:node_in_element(i+1,end)));
+	mesh_profile(i,end)=common(1);
+end
Index: /issm/trunk/src/m/mesh/argusmesh.m
===================================================================
--- /issm/trunk/src/m/mesh/argusmesh.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/argusmesh.m	(revision 13395)
@@ -0,0 +1,96 @@
+function md=argusmesh(md,infile)
+%ARGUSMESH - load an Argus mesh onto a model
+%
+%   Convert an Argus mesh contained in a file into
+%   fields needed for the mesh in a model md.
+%
+%   Usage:
+%      md=argusmesh(md,infile)
+%
+%   Example:
+%     md=argusmesh(md,'TriMesh.exp')
+
+%some argument check: 
+if nargin~=2 | nargout~=1,
+	help argustomodel;
+	error('argustomodel error message: bad usage');
+end
+
+%determine root of infile: strip extension
+[a,root,b,c]=fileparts(infile);
+
+%inform user we start the script: 
+disp(['   Translating argus file ''' infile ''' into matlab model object']);
+
+%open infile: 
+fileid=fopen(infile,'r');
+if fileid==-1,
+	error(['Could not open file ' infile  ' for reading']);
+end
+
+%Read first line of the argus mesh: node and element parameters
+[buffer,bytecount]=fscanf(fileid,'%i %i %i %i',[1 4]);
+if bytecount~=4, 
+	error(['Problem reading ' infile ' file at line #1']);
+end
+nel=buffer(1);
+nods=buffer(2);
+num_element_parameters=buffer(3);
+num_node_parameters=buffer(4);
+disp(['      argus model '''   root ''' contains ' num2str(nel) ' elements and ' num2str(nods) ' nodes.']);
+
+%initialize elements and nodes
+elements=zeros(nel,3);
+element_parameters=zeros(nel,num_element_parameters);
+x=zeros(nods,1);
+y=zeros(nods,1);
+z=zeros(nods,1);
+node_parameters=zeros(nods,num_node_parameters);
+
+%read nodes:
+format_string='%s %i %f %f ';
+for n=1:num_node_parameters,
+	format_string=[format_string ' %i '];
+end
+
+for n=1:nods,
+	[buffer,bytecount]=fscanf(fileid,format_string,[1,num_node_parameters+4]);
+	x(n)=buffer(3);
+	y(n)=buffer(4);
+	node_parameters(n,:)=buffer(5:length(buffer));
+end
+
+%read elements: 
+format_string='%s %i %i %i %i';
+for n=1:num_element_parameters,
+	format_string=[format_string ' %i '];
+end
+for n=1:nel,
+	[buffer,bytecount]=fscanf(fileid,format_string,[1,num_element_parameters+5]);
+	elements(n,:)=buffer(3:5);
+	element_parameters(n,:)=buffer(6:length(buffer));
+end
+
+%Create a name and a note for this model: 
+notes=['Model created by Argus from input file: ' infile ' and parameter file: ' root '.par on: ' date];
+name=root;
+
+%Finally, use model constructor to build a complete model: 
+md.mesh.elements=elements;
+md.mesh.x=x;
+md.mesh.y=y;
+md.z=z;
+md.mesh.numberofvertices=size(md.mesh.x,1);
+md.mesh.numberofelements=size(md.mesh.elements,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+md.mesh.dimension=2;
+md=addnote(md,notes);
+
+%Add segments and nodes on boundary
+md.mesh.segments=findsegments(md);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary(md.mesh.segments(:,1))=1;
+md.mesh.vertexonboundary(md.mesh.segments(:,2))=1;
Index: /issm/trunk/src/m/mesh/bamg.m
===================================================================
--- /issm/trunk/src/m/mesh/bamg.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/bamg.m	(revision 13395)
@@ -0,0 +1,483 @@
+function md=bamg(md,varargin)
+%BAMG - mesh generation
+%
+%   Available options (for more details see ISSM website http://issm.jpl.nasa.gov/):
+%
+%   - domain :            followed by an ARGUS file that prescribes the domain outline
+%   - hmin :              minimum edge length (default is 10^-100)
+%   - hmax :              maximum edge length (default is 10^100)
+%   - hVertices :         imposed edge length for each vertex (geometry or mesh)
+%   - hminVertices :      minimum edge length for each vertex (mesh)
+%   - hmaxVertices :      maximum edge length for each vertex (mesh)
+%
+%   - anisomax :          maximum ratio between the smallest and largest edges (default is 10^30)
+%   - coeff :             coefficient applied to the metric (2-> twice as many elements, default is 1)
+%   - cutoff :            scalar used to compute the metric when metric type 2 or 3 are applied
+%   - err :               error used to generate the metric from a field
+%   - errg :              geometric error (default is 0.1)
+%   - field :             field of the model that will be used to compute the metric
+%                         to apply several fields, use one column per field
+%   - gradation :         maximum ratio between two adjacent edges
+%   - Hessiantype :       0 -> use double P2 projection (default)
+%                         1 -> use Green formula
+%   - KeepVertices :      try to keep initial vertices when adaptation is done on an existing mesh (default 1)
+%   - MaxCornerAngle :    maximum angle of corners in degree (default is 10)
+%   - maxnbv :            maximum number of vertices used to allocate memory (default is 10^6)
+%   - maxsubdiv :         maximum subdivision of exisiting elements (default is 10)
+%   - metric :            matrix (numberofnodes x 3) used as a metric
+%   - Metrictype :        1 -> absolute error          c/(err coeff^2) * Abs(H)        (default)
+%                         2 -> relative error          c/(err coeff^2) * Abs(H)/max(s,cutoff*max(s))
+%                         3 -> rescaled absolute error c/(err coeff^2) * Abs(H)/(smax-smin)
+%   - nbjacoby :          correction used by Hessiantype=1 (default is 1)
+%   - nbsmooth :          number of metric smoothing procedure (default is 3)
+%   - omega :             relaxation parameter of the smoothing procedure (default is 1.8)
+%   - power :             power applied to the metric (default is 1)
+%   - splitcorners :      split triangles whuch have 3 vertices on the outline (default is 1)
+%   - geometricalmetric : take the geometry into account to generate the metric (default is 0)
+%   - verbose :           level of verbosity (default is 1)
+%
+%   - rifts :             followed by an ARGUS file that prescribes the rifts
+%   - toltip :            tolerance to move tip on an existing point of the domain outline
+%   - tracks :            followed by an ARGUS file that prescribes the tracks that the mesh will stick to
+%   - RequiredVertices :  mesh vertices that are required. [x,y,ref]; ref is optional
+%   - tol :               if the distance between 2 points of the domain outline is less than tol, they
+%                         will be merged
+%
+%   Examples:
+%      md=bamg(md,'domain','DomainOutline.exp','hmax',3000);
+%      md=bamg(md,'field',[md.inversion.vel_obs md.geometry.thickness],'hmax',20000,'hmin',1000);
+%      md=bamg(md,'metric',A,'hmin',1000,'hmax',20000,'gradation',3,'anisomax',1);
+
+%process options
+options=pairoptions(varargin{:});
+options=deleteduplicates(options,1);
+
+%initialize the structures required as input of Bamg
+bamg_options=struct();
+bamg_geometry=bamggeom;
+bamg_mesh=bamgmesh;
+
+% Bamg Geometry parameters {{{
+if exist(options,'domain'),
+
+	%Check that file exists
+	domainfile=getfieldvalue(options,'domain');
+	if ~exist(domainfile,'file') error(['bamg error message: file ' domainfile ' not found ']); end
+	domain=expread(domainfile);
+
+	%Build geometry 
+	count=0;
+	for i=1:length(domain),
+
+		%Check that the domain is closed
+		if (domain(i).x(1)~=domain(i).x(end) | domain(i).y(1)~=domain(i).y(end)),
+			error('bamg error message: all contours provided in ''domain'' should be closed');
+		end
+
+		%Checks that all holes are INSIDE the principle domain outline
+		if i>1,
+			flags=ContourToNodes(domain(i).x,domain(i).y,domain(1),0);
+			if any(~flags),
+				error('bamg error message: All holes should be stricly inside the principal domain');
+			end
+		end
+
+		%Add all points to bamg_geometry
+		nods=domain(i).nods-1; %the domain are closed 1=end;
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; [domain(i).x(1:nods) domain(i).y(1:nods) ones(nods,1)]];
+		bamg_geometry.Edges   =[bamg_geometry.Edges;    [transpose(count+1:count+nods) transpose([count+2:count+nods count+1])  1*ones(nods,1)]];
+		if i>1, bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 1]; end
+
+		%update counter
+		count=count+nods;
+	end
+
+	%take care of rifts
+	if exist(options,'rifts'),
+
+		%Check that file exists
+		riftfile=getfieldvalue(options,'rifts');
+		if ~exist(riftfile,'file')
+			error(['bamg error message: file ' riftfile ' not found ']);
+		end
+		rift=expread(riftfile);
+
+		for i=1:length(rift),
+
+			%detect wether all points of the rift are inside the domain
+			flags=ContourToNodes(rift(i).x,rift(i).y,domain(1),0);
+			if ~flags,
+				error('one Rift has all his points outside of the domain outline'),
+
+			elseif any(~flags),
+				%We LOTS of work to do
+				disp('Rift tip outside of or on the domain has been detected and is being processed...');
+
+				%check that only one point is outsie (for now)
+				if sum(~flags)~=1,
+					error('bamg error message: only one point outside of the domain is supported yet');
+				end
+
+				%Move tip outside to the first position
+				if flags(1)==0,
+					%OK, first point is outside (do nothing),
+				elseif (flags(end)==0),
+					rift(i).x=flipud(rift(i).x);
+					rift(i).y=flipud(rift(i).y);
+				else
+					error('bamg error message: only a rift tip can be outside of the domain');
+				end
+
+				%Get cordinate of intersection point
+				x1=rift(i).x(1); y1=rift(i).y(1);
+				x2=rift(i).x(2); y2=rift(i).y(2);
+				for j=1:length(domain(1).x)-1;
+					if SegIntersect([x1 y1; x2 y2],[domain(1).x(j) domain(1).y(j); domain(1).x(j+1) domain(1).y(j+1)]),
+
+						%Get position of the two nodes of the edge in domain
+						i1=j;
+						i2=mod(j+1,domain(1).nods);
+
+						%rift is crossing edge [i1 i2] of the domain
+						%Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html)
+						x3=domain(1).x(i1); y3=domain(1).y(i1);
+						x4=domain(1).x(i2); y4=domain(1).y(i2);
+						x=det([det([x1 y1; x2 y2])  x1-x2;det([x3 y3; x4 y4])  x3-x4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+						y=det([det([x1 y1; x2 y2])  y1-y2;det([x3 y3; x4 y4])  y3-y4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+
+						segdis= sqrt((x4-x3)^2+(y4-y3)^2);
+						tipdis=[sqrt((x-x3)^2+(y-y3)^2)  sqrt((x-x4)^2+(y-y4)^2)];
+
+						if (min(tipdis)/segdis) < getfieldvalue(options,'toltip',0),
+							disp('moving tip-domain intersection point');
+
+							%Get position of the closest point
+							if tipdis(1)>tipdis(2),
+								pos=i2;
+							else
+								pos=i1;
+							end
+
+							%This point is only in Vertices (number pos).
+							%OK, no we can add our own rift
+							nods=rift(i).nods-1;
+							bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(2:end) rift(i).y(2:end) ones(nods,1)]];
+							bamg_geometry.Edges=[bamg_geometry.Edges;...
+								pos count+1  (1+i);...
+								[transpose(count+1:count+nods-1) transpose([count+2:count+nods])  (1+i)*ones(nods-1,1)]];
+							count=count+nods;
+
+							break;
+
+						else
+							%Add intersection point to Vertices
+							bamg_geometry.Vertices=[bamg_geometry.Vertices; x y 1];
+							count=count+1;
+
+							%Decompose the crossing edge in 2 subedges
+							pos=find(bamg_geometry.Edges(:,1)==i1 & bamg_geometry.Edges(:,2)==i2);
+							if isempty(pos) error('bamg error message: a problem occured...'); end
+							bamg_geometry.Edges=[bamg_geometry.Edges(1:pos-1,:);...
+								bamg_geometry.Edges(pos,1) count                           bamg_geometry.Edges(pos,3);...
+								count                      bamg_geometry.Edges(pos,2)   bamg_geometry.Edges(pos,3);...
+								bamg_geometry.Edges(pos+1:end,:)];
+
+							%OK, no we can add our own rift
+							nods=rift(i).nods-1;
+							bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(2:end) rift(i).y(2:end) ones(nods,1)]];
+							bamg_geometry.Edges=[bamg_geometry.Edges;...
+								count  count+1  2 ;...
+								[transpose(count+1:count+nods-1) transpose([count+2:count+nods])  (1+i)*ones(nods-1,1)]];
+							count=count+nods;
+
+							break;
+						end
+					end
+				end
+			else
+				nods=rift(i).nods-1;
+				bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(:) rift(i).y(:) ones(nods+1,1)]];
+				bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods) transpose([count+2:count+nods+1])  (1+i)*ones(nods,1)]];
+				count=count+nods+1;
+			end
+		end
+	end
+
+	%Deal with tracks
+	if exist(options,'tracks'),
+
+		%read tracks
+		track=getfieldvalue(options,'tracks');
+		if all(ischar(track)),
+			A=expread(track); 
+			track=[A.x A.y];
+		else
+			track=double(track); %for some reason, it is of class "single"
+		end
+		if(size(track,2)==2), track=[track 3*ones(size(track,1),1)]; end
+
+		%only keep those inside
+		flags=ContourToNodes(track(:,1),track(:,2),domainfile,0);
+		track=track(find(flags),:);
+
+		%Add all points to bamg_geometry
+		nods=size(track,1);
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; track];
+		bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods-1) transpose([count+2:count+nods])  3*ones(nods-1,1)]];
+
+		%update counter
+		count=count+nods;
+	end
+
+	%Deal with vertices that need to be kept by mesher
+	if exist(options,'RequiredVertices'),
+
+		%recover RequiredVertices
+		requiredvertices=double(getfieldvalue(options,'RequiredVertices')); %for some reason, it is of class "single"
+		if(size(requiredvertices,2)==2), requiredvertices=[requiredvertices 4*ones(size(requiredvertices,1),1)]; end
+	
+		%only keep those inside
+		flags=ContourToNodes(requiredvertices(:,1),requiredvertices(:,2),domain(1),0);
+		requiredvertices=requiredvertices(find(flags),:);
+
+		%Add all points to bamg_geometry
+		nods=size(requiredvertices,1);
+		bamg_geometry.Vertices=[bamg_geometry.Vertices; requiredvertices];
+
+		%update counter
+		count=count+nods;
+
+	end
+
+	%process geom
+	%bamg_geometry=processgeometry(bamg_geometry,getfieldvalue(options,'tol',NaN),domain(1));
+
+elseif isstruct(md.private.bamg) & isfield(md.private.bamg,'geometry'),
+	bamg_geometry=bamggeom(md.private.bamg.geometry); 
+else
+	%do nothing...
+end
+%}}}
+% Bamg Mesh parameters {{{
+if (~exist(options,'domain') & md.mesh.numberofvertices~=0 & md.mesh.dimension==2),
+
+	if isstruct(md.private.bamg) & isfield(md.private.bamg,'mesh'),
+		bamg_mesh=bamgmesh(md.private.bamg.mesh);
+	else
+		bamg_mesh.Vertices=[md.mesh.x md.mesh.y ones(md.mesh.numberofvertices,1)];
+		bamg_mesh.Triangles=[md.mesh.elements ones(md.mesh.numberofelements,1)];
+	end
+
+	if isstruct(md.rifts.riftstruct)
+		error('bamg error message: rifts not supported yet. Do meshprocessrift AFTER bamg');
+	end
+end
+%}}}
+% Bamg Options {{{
+bamg_options.Crack=getfieldvalue(options,'Crack',0);
+bamg_options.anisomax=getfieldvalue(options,'anisomax',10^30);
+bamg_options.coeff=getfieldvalue(options,'coeff',1);
+bamg_options.cutoff=getfieldvalue(options,'cutoff',10^-5);
+bamg_options.err=getfieldvalue(options,'err',0.01);
+bamg_options.errg=getfieldvalue(options,'errg',0.1);
+bamg_options.field=getfieldvalue(options,'field',[]);
+bamg_options.gradation=getfieldvalue(options,'gradation',1.5);
+bamg_options.Hessiantype=getfieldvalue(options,'Hessiantype',0);
+bamg_options.hmin=getfieldvalue(options,'hmin',10^-100);
+bamg_options.hmax=getfieldvalue(options,'hmax',10^100);
+bamg_options.hminVertices=getfieldvalue(options,'hminVertices',[]);
+bamg_options.hmaxVertices=getfieldvalue(options,'hmaxVertices',[]);
+bamg_options.hVertices=getfieldvalue(options,'hVertices',[]);
+bamg_options.KeepVertices=getfieldvalue(options,'KeepVertices',1);
+bamg_options.MaxCornerAngle=getfieldvalue(options,'MaxCornerAngle',10);
+bamg_options.maxnbv=getfieldvalue(options,'maxnbv',10^6);
+bamg_options.maxsubdiv=getfieldvalue(options,'maxsubdiv',10);
+bamg_options.metric=getfieldvalue(options,'metric',[]);
+bamg_options.Metrictype=getfieldvalue(options,'Metrictype',0);
+bamg_options.nbjacobi=getfieldvalue(options,'nbjacobi',1);
+bamg_options.nbsmooth=getfieldvalue(options,'nbsmooth',3);
+bamg_options.omega=getfieldvalue(options,'omega',1.8);
+bamg_options.power=getfieldvalue(options,'power',1);
+bamg_options.splitcorners=getfieldvalue(options,'splitcorners',1);
+bamg_options.geometricalmetric=getfieldvalue(options,'geometricalmetric',0);
+bamg_options.verbose=getfieldvalue(options,'verbose',1);
+%}}}
+
+%call Bamg
+[bamgmesh_out bamggeom_out]=BamgMesher(bamg_mesh,bamg_geometry,bamg_options);
+
+% plug results onto model
+md.private.bamg=struct();
+md.private.bamg.mesh=bamgmesh(bamgmesh_out);
+md.private.bamg.geometry=bamggeom(bamggeom_out);
+md.mesh.x=bamgmesh_out.Vertices(:,1);
+md.mesh.y=bamgmesh_out.Vertices(:,2);
+md.mesh.elements=bamgmesh_out.Triangles(:,1:3);
+md.mesh.edges=bamgmesh_out.IssmEdges;
+md.mesh.segments=bamgmesh_out.IssmSegments(:,1:3);
+md.mesh.segmentmarkers=bamgmesh_out.IssmSegments(:,4);
+
+%Fill in rest of fields:
+md.mesh.dimension=2;
+md.mesh.numberofelements=size(md.mesh.elements,1);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.numberofedges=size(md.mesh.edges,1);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.elementconnectivity=md.private.bamg.mesh.ElementConnectivity;
+md.mesh.elementconnectivity(find(isnan(md.mesh.elementconnectivity)))=0;
+
+%Check for orphan
+reshape(md.mesh.elements,3*md.mesh.numberofelements,1);
+(~ismember(1:md.mesh.numberofvertices,sort(unique(reshape(md.mesh.elements,3*md.mesh.numberofelements,1)))));
+if any(~ismember(1:md.mesh.numberofvertices,sort(unique(reshape(md.mesh.elements,3*md.mesh.numberofelements,1)))))
+	error('Output mesh has orphans. Decrease MaxCornerAngle to prevent outside points (ex: 0.01)');
+end
+end 
+
+function geom=processgeometry(geom,tol,outline); % {{{
+
+%Deal with edges
+disp('Checking Edge crossing...');
+i=0;
+while (i<size(geom.Edges,1)),
+
+	%edge counter
+	i=i+1;
+
+	%Get coordinates
+	x1=geom.Vertices(geom.Edges(i,1),1);
+	y1=geom.Vertices(geom.Edges(i,1),2);
+	x2=geom.Vertices(geom.Edges(i,2),1);
+	y2=geom.Vertices(geom.Edges(i,2),2);
+	color1=geom.Edges(i,3);
+
+	j=i; %test edges located AFTER i only
+	while (j<size(geom.Edges,1)),
+
+		%edge counter
+		j=j+1;
+
+		%Skip if the two edges already have a vertex in common
+		if any(ismember(geom.Edges(i,1:2),geom.Edges(j,1:2))),
+			continue
+		end
+
+		%Get coordinates
+		x3=geom.Vertices(geom.Edges(j,1),1);
+		y3=geom.Vertices(geom.Edges(j,1),2);
+		x4=geom.Vertices(geom.Edges(j,2),1);
+		y4=geom.Vertices(geom.Edges(j,2),2);
+		color2=geom.Edges(j,3);
+
+		%Check if the two edges are crossing one another
+		if SegIntersect([x1 y1; x2 y2],[x3 y3; x4 y4]),
+
+			%Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html)
+			x=det([det([x1 y1; x2 y2])  x1-x2;det([x3 y3; x4 y4])  x3-x4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+			y=det([det([x1 y1; x2 y2])  y1-y2;det([x3 y3; x4 y4])  y3-y4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
+
+			%Add vertex to the list of vertices
+			geom.Vertices(end+1,:)=[x y min(color1,color2)];
+			id=size(geom.Vertices,1);
+
+			%Update edges i and j
+			edgei=geom.Edges(i,:);
+			edgej=geom.Edges(j,:);
+			geom.Edges(i,:)    =[edgei(1) id       edgei(3)];
+			geom.Edges(end+1,:)=[id       edgei(2) edgei(3)];
+			geom.Edges(j,:)    =[edgej(1) id       edgej(3)];
+			geom.Edges(end+1,:)=[id       edgej(2) edgej(3)];
+
+			%update current edge second tip
+			x2=x; y2=y;
+		end
+	end
+
+end
+
+%Check point outside
+disp('Checking for points outside the domain...');
+i=0;
+num=0;
+while (i<size(geom.Vertices,1)),
+
+	%vertex counter
+	i=i+1;
+
+	%Get coordinates
+	x=geom.Vertices(i,1);
+	y=geom.Vertices(i,2);
+	color=geom.Vertices(i,3);
+
+	%Check that the point is inside the domain
+	if (color~=1 & ~ContourToNodes(x,y,outline(1),1)),
+
+		%Remove points from list of Vertices
+		num=num+1;
+		geom.Vertices(i,:)=[];
+
+		%update edges
+		[posedges dummy]=find(geom.Edges==i);
+		geom.Edges(posedges,:)=[];
+		posedges=find(geom.Edges>i);
+		geom.Edges(posedges)=geom.Edges(posedges)-1;
+
+		%update counter
+		i=i-1;
+	end
+end
+if num,
+	disp(['WARNING: ' num2str(num) ' points outside the domain outline have been removed']);
+end
+
+%Check point spacing
+if ~isnan(tol),
+	disp('Checking point spacing...');
+	i=0;
+	while (i<size(geom.Vertices,1)),
+
+		%vertex counter
+		i=i+1;
+
+		%Get coordinates
+		x1=geom.Vertices(i,1);
+		y1=geom.Vertices(i,2);
+
+		j=i; %test edges located AFTER i only
+		while (j<size(geom.Vertices,1)),
+
+			%vertex counter
+			j=j+1;
+
+			%Get coordinates
+			x2=geom.Vertices(j,1);
+			y2=geom.Vertices(j,2);
+
+			%Check whether the two vertices are too close
+			if ((x2-x1)^2+(y2-y1)^2<tol^2)
+
+				%Remove points from list of Vertices
+				geom.Vertices(j,:)=[];
+
+				%update edges
+				posedges=find(ismember(geom.Edges,j));
+				geom.Edges(posedges)=i;
+				posedges=find(geom.Edges>j);
+				geom.Edges(posedges)=geom.Edges(posedges)-1;
+
+				%update counter
+				j=j-1;
+
+			end
+		end
+	end
+end
+%remove empty edges
+geom.Edges(find(geom.Edges(:,1)==geom.Edges(:,2)),:)=[];
+end % }}}
Index: /issm/trunk/src/m/mesh/findsegments.m
===================================================================
--- /issm/trunk/src/m/mesh/findsegments.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/findsegments.m	(revision 13395)
@@ -0,0 +1,92 @@
+function segments=findsegments(md,varargin)
+%FINDSEGMENTS - build segments model field
+%
+%   Optional inputs:
+%      'mesh.elementconnectivity'
+%
+%   Usage:
+%      segments=findsegments(md,varargin);
+
+%get options
+options=pairoptions(varargin{:});
+
+%Get connectivity
+mesh.elementconnectivity=getfieldvalue(options,'mesh.elementconnectivity',md.mesh.elementconnectivity);
+
+%Now, build the connectivity tables for this mesh if not correclty done
+if size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements,
+	if exist(options,'mesh.elementconnectivity'),
+		error(' ''mesh.elementconnectivity'' option does not have thge right size.');
+	else
+		mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+	end
+end
+
+%Recreate the segments
+elementonboundary=double(mesh.elementconnectivity(:,3)==0);
+pos=find(elementonboundary);
+num_segments=length(pos);
+segments=zeros(num_segments,3);
+count=1;
+
+%loop over the segments
+for i=1:num_segments,
+
+	%get current element on boundary
+	el1=pos(i);
+
+	%get elements connected to el1
+	els2=mesh.elementconnectivity(el1,find(mesh.elementconnectivity(el1,:)));
+
+	%el1 is connected to 2 other elements
+	if length(els2)>1,
+
+		%get nodes of el1
+		nods1=md.mesh.elements(el1,:);
+
+		%find the common vertices to the two elements connected to el1 (1 or 2)
+		flag=intersect(md.mesh.elements(els2(1),:),md.mesh.elements(els2(2),:));
+
+		%get the vertices on the boundary and build segment
+		nods1(find(ismember(nods1,flag)))=[];
+		segments(count,:)=[nods1 el1];
+
+		%swap segment nodes if necessary
+		ord1=find(nods1(1)==md.mesh.elements(el1,:));
+		ord2=find(nods1(2)==md.mesh.elements(el1,:));
+		if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+			temp=segments(count,1);
+			segments(count,1)=segments(count,2);
+			segments(count,2)=temp;
+		end
+		segments(count,1:2)=fliplr(segments(count,1:2));
+		count=count+1;
+
+	%el1 is connected to only one element
+	else
+		%get nodes of el1
+		nods1=md.mesh.elements(el1,:);
+
+		%find the vertex  the el1 to not share with els2
+		flag=setdiff(nods1,md.mesh.elements(els2,:));
+
+		for j=1:3,
+			nods=nods1; nods(j)=[];
+			if any(ismember(flag,nods)),
+
+				segments(count,:)=[nods el1];
+
+				%swap segment nodes if necessary
+				ord1=find(nods(1)==md.mesh.elements(el1,:));
+				ord2=find(nods(2)==md.mesh.elements(el1,:));
+				if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+					temp=segments(count,1);
+					segments(count,1)=segments(count,2);
+					segments(count,2)=temp;
+				end
+				segments(count,1:2)=fliplr(segments(count,1:2));
+				count=count+1;
+			end
+		end
+	end
+end
Index: /issm/trunk/src/m/mesh/intersections.m
===================================================================
--- /issm/trunk/src/m/mesh/intersections.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/intersections.m	(revision 13395)
@@ -0,0 +1,279 @@
+function [x0,y0,iout,jout] = intersections(x1,y1,x2,y2,robust)
+%INTERSECTIONS Intersections of curves.
+%   Computes the (x,y) locations where two curves intersect.  The curves
+%   can be broken with NaNs or have vertical segments.
+%
+% Example:
+%   [X0,Y0] = intersections(X1,Y1,X2,Y2,ROBUST);
+%
+% where X1 and Y1 are equal-length vectors of at least two points and
+% represent curve 1.  Similarly, X2 and Y2 represent curve 2.
+% X0 and Y0 are column vectors containing the points at which the two
+% curves intersect.
+%
+% ROBUST (optional) set to 1 or true means to use a slight variation of the
+% algorithm that might return duplicates of some intersection points, and
+% then remove those duplicates.  The default is true, but since the
+% algorithm is slightly slower you can set it to false if you know that
+% your curves don't intersect at any segment boundaries.  Also, the robust
+% version properly handles parallel and overlapping segments.
+%
+% The algorithm can return two additional vectors that indicate which
+% segment pairs contain intersections and where they are:
+%
+%   [X0,Y0,I,J] = intersections(X1,Y1,X2,Y2,ROBUST);
+%
+% For each element of the vector I, I(k) = (segment number of (X1,Y1)) +
+% (how far along this segment the intersection is).  For example, if I(k) =
+% 45.25 then the intersection lies a quarter of the way between the line
+% segment connecting (X1(45),Y1(45)) and (X1(46),Y1(46)).  Similarly for
+% the vector J and the segments in (X2,Y2).
+%
+% You can also get intersections of a curve with itself.  Simply pass in
+% only one curve, i.e.,
+%
+%   [X0,Y0] = intersections(X1,Y1,ROBUST);
+%
+% where, as before, ROBUST is optional.
+
+% Version: 1.10, 25 February 2008
+% Author:  Douglas M. Schwarz
+% Email:   dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu
+% Real_email = regexprep(Email,{'=','*'},{'@','.'})
+
+
+% Theory of operation:
+%
+% Given two line segments, L1 and L2,
+%
+%   L1 endpoints:  (x1(1),y1(1)) and (x1(2),y1(2))
+%   L2 endpoints:  (x2(1),y2(1)) and (x2(2),y2(2))
+%
+% we can write four equations with four unknowns and then solve them.  The
+% four unknowns are t1, t2, x0 and y0, where (x0,y0) is the intersection of
+% L1 and L2, t1 is the distance from the starting point of L1 to the
+% intersection relative to the length of L1 and t2 is the distance from the
+% starting point of L2 to the intersection relative to the length of L2.
+%
+% So, the four equations are
+%
+%    (x1(2) - x1(1))*t1 = x0 - x1(1)
+%    (x2(2) - x2(1))*t2 = x0 - x2(1)
+%    (y1(2) - y1(1))*t1 = y0 - y1(1)
+%    (y2(2) - y2(1))*t2 = y0 - y2(1)
+%
+% Rearranging and writing in matrix form,
+%
+%  [x1(2)-x1(1)       0       -1   0;      [t1;      [-x1(1);
+%        0       x2(2)-x2(1)  -1   0;   *   t2;   =   -x2(1);
+%   y1(2)-y1(1)       0        0  -1;       x0;       -y1(1);
+%        0       y2(2)-y2(1)   0  -1]       y0]       -y2(1)]
+%
+% Let's call that A*T = B.  We can solve for T with T = A\B.
+%
+% Once we have our solution we just have to look at t1 and t2 to determine
+% whether L1 and L2 intersect.  If 0 <= t1 < 1 and 0 <= t2 < 1 then the two
+% line segments cross and we can include (x0,y0) in the output.
+%
+% In principle, we have to perform this computation on every pair of line
+% segments in the input data.  This can be quite a large number of pairs so
+% we will reduce it by doing a simple preliminary check to eliminate line
+% segment pairs that could not possibly cross.  The check is to look at the
+% smallest enclosing rectangles (with sides parallel to the axes) for each
+% line segment pair and see if they overlap.  If they do then we have to
+% compute t1 and t2 (via the A\B computation) to see if the line segments
+% cross, but if they don't then the line segments cannot cross.  In a
+% typical application, this technique will eliminate most of the potential
+% line segment pairs.
+
+
+% Input checks.
+error(nargchk(2,5,nargin))
+
+% Adjustments when fewer than five arguments are supplied.
+switch nargin
+	case 2
+		robust = true;
+		x2 = x1;
+		y2 = y1;
+		self_intersect = true;
+	case 3
+		robust = x2;
+		x2 = x1;
+		y2 = y1;
+		self_intersect = true;
+	case 4
+		robust = true;
+		self_intersect = false;
+	case 5
+		self_intersect = false;
+end
+
+% x1 and y1 must be vectors with same number of points (at least 2).
+if sum(size(x1) > 1) ~= 1 || sum(size(y1) > 1) ~= 1 || ...
+		length(x1) ~= length(y1)
+	error('X1 and Y1 must be equal-length vectors of at least 2 points.')
+end
+% x2 and y2 must be vectors with same number of points (at least 2).
+if sum(size(x2) > 1) ~= 1 || sum(size(y2) > 1) ~= 1 || ...
+		length(x2) ~= length(y2)
+	error('X2 and Y2 must be equal-length vectors of at least 2 points.')
+end
+
+
+% Force all inputs to be column vectors.
+x1 = x1(:);
+y1 = y1(:);
+x2 = x2(:);
+y2 = y2(:);
+
+% Compute number of line segments in each curve and some differences we'll
+% need later.
+n1 = length(x1) - 1;
+n2 = length(x2) - 1;
+xy1 = [x1 y1];
+xy2 = [x2 y2];
+dxy1 = diff(xy1);
+dxy2 = diff(xy2);
+
+% Determine the combinations of i and j where the rectangle enclosing the
+% i'th line segment of curve 1 overlaps with the rectangle enclosing the
+% j'th line segment of curve 2.
+[i,j] = find(repmat(min(x1(1:end-1),x1(2:end)),1,n2) <= ...
+	repmat(max(x2(1:end-1),x2(2:end)).',n1,1) & ...
+	repmat(max(x1(1:end-1),x1(2:end)),1,n2) >= ...
+	repmat(min(x2(1:end-1),x2(2:end)).',n1,1) & ...
+	repmat(min(y1(1:end-1),y1(2:end)),1,n2) <= ...
+	repmat(max(y2(1:end-1),y2(2:end)).',n1,1) & ...
+	repmat(max(y1(1:end-1),y1(2:end)),1,n2) >= ...
+	repmat(min(y2(1:end-1),y2(2:end)).',n1,1));
+
+% For one segment in x1,y1, i and j are returned as row vectors.  They
+% need to be column vectors, or iout and jout below will err out.
+% (jes, 6/11/10)
+
+if (size(i,1) == 1)
+    i=i';
+end
+if (size(j,1) == 1)
+    j=j';
+end
+
+% Find segments pairs which have at least one vertex = NaN and remove them.
+% This line is a fast way of finding such segment pairs.  We take
+% advantage of the fact that NaNs propagate through calculations, in
+% particular subtraction (in the calculation of dxy1 and dxy2, which we
+% need anyway) and addition.
+% At the same time we can remove redundant combinations of i and j in the
+% case of finding intersections of a line with itself.
+if self_intersect
+	remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2)) | j <= i + 1;
+else
+	remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2));
+end
+i(remove) = [];
+j(remove) = [];
+
+% Initialize matrices.  We'll put the T's and B's in matrices and use them
+% one column at a time.  AA is a 3-D extension of A where we'll use one
+% plane at a time.
+n = length(i);
+T = zeros(4,n);
+AA = zeros(4,4,n);
+AA([1 2],3,:) = -1;
+AA([3 4],4,:) = -1;
+AA([1 3],1,:) = dxy1(i,:).';
+AA([2 4],2,:) = dxy2(j,:).';
+B = -[x1(i) x2(j) y1(i) y2(j)].';
+
+% Loop through possibilities.  Trap singularity warning and then use
+% lastwarn to see if that plane of AA is near singular.  Process any such
+% segment pairs to determine if they are colinear (overlap) or merely
+% parallel.  That test consists of checking to see if one of the endpoints
+% of the curve 2 segment lies on the curve 1 segment.  This is done by
+% checking the cross product
+%
+%   (x1(2),y1(2)) - (x1(1),y1(1)) x (x2(2),y2(2)) - (x1(1),y1(1)).
+%
+% If this is close to zero then the segments overlap.
+
+% If the robust option is false then we assume no two segment pairs are
+% parallel and just go ahead and do the computation.  If A is ever singular
+% a warning will appear.  This is faster and obviously you should use it
+% only when you know you will never have overlapping or parallel segment
+% pairs.
+
+if robust
+	overlap = false(1,n);
+	warning_state = warning('off','MATLAB:singularMatrix');
+	% Use try-catch to guarantee original warning state is restored.
+	try
+		lastwarn('')
+		for k = 1:n
+			T(:,k) = AA(:,:,k)\B(:,k);
+			[unused,last_warn] = lastwarn;
+			lastwarn('')
+			if strcmp(last_warn,'MATLAB:singularMatrix')
+				% Force in_range(k) to be false.
+				T(1,k) = NaN;
+				% Determine if these segments overlap or are just parallel.
+				overlap(k) = rcond([dxy1(i(k),:);xy2(j(k),:) - xy1(i(k),:)]) < eps;
+			end
+		end
+		warning(warning_state)
+	catch
+		warning(warning_state)
+		rethrow(lasterror)
+	end
+	% Find where t1 and t2 are between 0 and 1 and return the corresponding
+	% x0 and y0 values.
+	in_range = T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) <= 1 & T(2,:) <= 1;
+	% For overlapping segment pairs the algorithm will return an
+	% intersection point that is at the center of the overlapping region.
+	if any(overlap)
+		ia = i(overlap);
+		ja = j(overlap);
+		% set x0 and y0 to middle of overlapping region.
+		T(3,overlap) = (max(min(x1(ia),x1(ia+1)),min(x2(ja),x2(ja+1))) + ...
+			min(max(x1(ia),x1(ia+1)),max(x2(ja),x2(ja+1)))).'/2;
+		T(4,overlap) = (max(min(y1(ia),y1(ia+1)),min(y2(ja),y2(ja+1))) + ...
+			min(max(y1(ia),y1(ia+1)),max(y2(ja),y2(ja+1)))).'/2;
+		selected = in_range | overlap;
+	else
+		selected = in_range;
+	end
+	xy0 = T(3:4,selected).';
+	
+	% Remove duplicate intersection points.
+	[xy0,index] = unique(xy0,'rows');
+	x0 = xy0(:,1);
+	y0 = xy0(:,2);
+	
+	% Compute how far along each line segment the intersections are.
+	if nargout > 2
+		sel_index = find(selected);
+		sel = sel_index(index);
+		iout = i(sel) + T(1,sel).';
+		jout = j(sel) + T(2,sel).';
+	end
+else % non-robust option
+	for k = 1:n
+		[L,U] = lu(AA(:,:,k));
+		T(:,k) = U\(L\B(:,k));
+	end
+	
+	% Find where t1 and t2 are between 0 and 1 and return the corresponding
+	% x0 and y0 values.
+	in_range = T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) < 1 & T(2,:) < 1;
+	x0 = T(3,in_range).';
+	y0 = T(4,in_range).';
+	
+	% Compute how far along each line segment the intersections are.
+	if nargout > 2
+		iout = i(in_range) + T(1,in_range).';
+		jout = j(in_range) + T(2,in_range).';
+	end
+end
+
+% Plot the results (useful for debugging).
+% plot(x1,y1,x2,y2,x0,y0,'ok');
Index: /issm/trunk/src/m/mesh/meshconvert.m
===================================================================
--- /issm/trunk/src/m/mesh/meshconvert.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/meshconvert.m	(revision 13395)
@@ -0,0 +1,48 @@
+function md=meshconvert(md,varargin)
+%CONVERTMESH - convert mesh to bamg mesh
+%
+%   Usage:
+%      md=meshconvert(md);
+%      md=meshconvert(md,index,x,y);
+
+if nargin~=1 & nargin~=4,
+	help meshconvert
+	error('meshconvert error message: bad usage');
+end
+
+if nargin==1,
+	x=md.mesh.x;
+	y=md.mesh.y;
+	index=md.mesh.elements;
+else
+	x=varargin{1};
+	y=varargin{2};
+	index=varargin{3};
+end
+
+%call Bamg
+[bamgmesh_out bamggeom_out]=BamgConvertMesh(index,x,y);
+
+% plug results onto model
+md.private.bamg=struct();
+md.private.bamg.mesh=bamgmesh(bamgmesh_out);
+md.private.bamg.geometry=bamggeom(bamggeom_out);
+md.mesh.x=bamgmesh_out.Vertices(:,1);
+md.mesh.y=bamgmesh_out.Vertices(:,2);
+md.mesh.elements=bamgmesh_out.Triangles(:,1:3);
+md.mesh.edges=bamgmesh_out.IssmEdges;
+md.mesh.segments=bamgmesh_out.IssmSegments(:,1:3);
+md.mesh.segmentmarkers=bamgmesh_out.IssmSegments(:,4);
+
+%Fill in rest of fields:
+md.mesh.dimension=2;
+md.mesh.numberofelements=size(md.mesh.elements,1);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.numberofedges=size(md.mesh.edges,1);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
Index: /issm/trunk/src/m/mesh/meshconvert.py
===================================================================
--- /issm/trunk/src/m/mesh/meshconvert.py	(revision 13395)
+++ /issm/trunk/src/m/mesh/meshconvert.py	(revision 13395)
@@ -0,0 +1,57 @@
+import numpy
+from collections import OrderedDict
+from BamgConvertMesh import *
+from bamgmesh import *
+from bamggeom import *
+
+def meshconvert(md,*args):
+	"""
+	CONVERTMESH - convert mesh to bamg mesh
+
+	   Usage:
+	      md=meshconvert(md);
+	      md=meshconvert(md,index,x,y);
+	"""
+
+	if not len(args)==0 and not len(args)==3:
+		raise TypeError("meshconvert error message: bad usage")
+
+	if not len(args):
+		x=md.mesh.x
+		y=md.mesh.y
+		index=md.mesh.elements
+	else:
+		x=args[0]
+		y=args[1]
+		index=args[2]
+
+	#call Bamg
+	bamgmesh_out,bamggeom_out=BamgConvertMesh(index,x,y)
+
+	# plug results onto model
+	md.private.bamg=OrderedDict()
+	md.private.bamg['mesh']=bamgmesh(bamgmesh_out)
+	md.private.bamg['geometry']=bamggeom(bamggeom_out)
+	md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()
+	md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()
+	md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].copy()
+	md.mesh.edges=bamgmesh_out['IssmEdges'].copy()
+	md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].copy()
+	md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].copy()
+
+	#Fill in rest of fields:
+	md.mesh.dimension=2
+	md.mesh.numberofelements=numpy.size(md.mesh.elements,axis=0)
+	md.mesh.numberofvertices=numpy.size(md.mesh.x)
+	md.mesh.numberofedges=numpy.size(md.mesh.edges,axis=0)
+	md.mesh.z=numpy.zeros(md.mesh.numberofvertices)
+	md.mesh.vertexonbed=numpy.ones(md.mesh.numberofvertices)
+	md.mask.vertexonwater=numpy.zeros(md.mesh.numberofvertices)
+	md.mesh.vertexonsurface=numpy.ones(md.mesh.numberofvertices)
+	md.mesh.elementonbed=numpy.ones(md.mesh.numberofelements)
+	md.mesh.elementonsurface=numpy.ones(md.mesh.numberofelements)
+	md.mesh.vertexonboundary=numpy.zeros(md.mesh.numberofvertices)
+	md.mesh.vertexonboundary[md.mesh.segments[:,0:1].astype(int)-1]=1
+
+	return md
+
Index: /issm/trunk/src/m/mesh/planet/mesh_refine_tri4.m
===================================================================
--- /issm/trunk/src/m/mesh/planet/mesh_refine_tri4.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/planet/mesh_refine_tri4.m	(revision 13395)
@@ -0,0 +1,146 @@
+function [ FV ] = mesh_refine_tri4(FV)
+
+% mesh_refine_tri4 - creates 4 triangle from each triangle of a mesh
+%
+% [ FV ] = mesh_refine_tri4( FV )
+%
+% FV.vertices   - mesh vertices (Nx3 matrix)
+% FV.faces      - faces with indices into 3 rows
+%                 of FV.vertices (Mx3 matrix)
+% 
+% For each face, 3 new vertices are created at the 
+% triangle edge midpoints.  Each face is divided into 4
+% faces and returned in FV.
+%
+%        B
+%       /\
+%      /  \
+%    a/____\b       Construct new triangles
+%    /\    /\       [A,a,c]
+%   /  \  /  \      [a,B,b]
+%  /____\/____\     [c,b,C]
+% A	     c	   C    [a,b,c]
+% 
+% It is assumed that the vertices are listed in clockwise order in
+% FV.faces (A,B,C above), as viewed from the outside in a RHS coordinate
+% system.
+% 
+% See also: mesh_refine, sphere_tri, sphere_project
+% 
+
+
+% ---this method is not implemented, but the idea here remains...
+% This can be done until some minimal distance (D) of the mean 
+% distance between vertices of all triangles is achieved.  If
+% no D argument is given, the function refines the mesh once.
+% Alternatively, it could be done until some minimum mean 
+% area of faces is achieved.  As is, it just refines once.
+
+
+% $Revision: 1.1 $ $Date: 2004/11/12 01:32:35 $
+
+% Licence:  GNU GPL, no implied or express warranties
+% History:  05/2002, Darren.Weber_at_radiology.ucsf.edu, created
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+tic;
+fprintf('...refining mesh (tri4)...')
+
+% NOTE
+% The centroid is located one third of the way from each vertex to 
+% the midpoint of the opposite side. Each median divides the triangle 
+% into two equal areas; all the medians together divide it into six 
+% equal parts, and the lines from the median point to the vertices 
+% divide the whole into three equivalent triangles.
+
+% Each input triangle with vertices labelled [A,B,C] as shown
+% below will be turned into four new triangles:
+%
+% Make new midpoints
+% a = (A+B)/2
+% b = (B+C)/2
+% c = (C+A)/2
+%
+%        B
+%       /\
+%      /  \
+%    a/____\b       Construct new triangles
+%    /\    /\       [A,a,c]
+%   /  \  /  \      [a,B,b]
+%  /____\/____\     [c,b,C]
+% A	     c	   C    [a,b,c]
+%
+
+% Initialise a new vertices and faces matrix
+Nvert = size(FV.vertices,1);
+Nface = size(FV.faces,1);
+V2 = zeros(Nface*3,3);
+F2 = zeros(Nface*4,3);
+
+for f = 1:Nface,
+    
+    % Get the triangle vertex indices
+    NA = FV.faces(f,1);
+    NB = FV.faces(f,2);
+    NC = FV.faces(f,3);
+    
+    % Get the triangle vertex coordinates
+    A = FV.vertices(NA,:);
+    B = FV.vertices(NB,:);
+    C = FV.vertices(NC,:);
+    
+    % Now find the midpoints between vertices
+    a = (A + B) ./ 2;
+    b = (B + C) ./ 2;
+    c = (C + A) ./ 2;
+    
+    % Find the length of each median
+    %A2blen = sqrt ( sum( (A - b).^2, 2 ) );
+    %B2clen = sqrt ( sum( (B - c).^2, 2 ) );
+    %C2alen = sqrt ( sum( (C - a).^2, 2 ) );
+    
+    % Store the midpoint vertices, while
+    % checking if midpoint vertex already exists
+    [FV, Na] = mesh_find_vertex(FV,a);
+    [FV, Nb] = mesh_find_vertex(FV,b);
+    [FV, Nc] = mesh_find_vertex(FV,c);
+    
+    % Create new faces with orig vertices plus midpoints
+    F2(f*4-3,:) = [ NA, Na, Nc ];
+    F2(f*4-2,:) = [ Na, NB, Nb ];
+    F2(f*4-1,:) = [ Nc, Nb, NC ];
+    F2(f*4-0,:) = [ Na, Nb, Nc ];
+    
+end
+
+% Replace the faces matrix
+FV.faces = F2;
+
+t=toc; fprintf('done (%5.2f sec)\n',t);
+
+return
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function [FV, N] = mesh_find_vertex(FV,vertex)
+
+    Vn = size(FV.vertices,1);
+    Va = repmat(vertex,Vn,1);
+    Vexist = find( FV.vertices(:,1) == Va(:,1) & ...
+                   FV.vertices(:,2) == Va(:,2) & ...
+                   FV.vertices(:,3) == Va(:,3) );
+    if Vexist,
+        if size(Vexist) == [1,1],
+            N = Vexist;
+        else,
+            msg = sprintf('replicated vertices');
+            error(msg);
+        end
+    else
+        FV.vertices(end+1,:) = vertex;
+        N = size(FV.vertices,1);
+    end
+
+return
Index: /issm/trunk/src/m/mesh/planet/planetmesher.m
===================================================================
--- /issm/trunk/src/m/mesh/planet/planetmesher.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/planet/planetmesher.m	(revision 13395)
@@ -0,0 +1,35 @@
+function md=planetmesher(md,varargin)
+%PLANETMESHER - create planet mesh using several packages
+%
+%   This routine creates a planet mesh using several packages: a custom made 
+%   ISSM mesher (called planetmixedmesh.m, method 'mixed') and the planettrimesh
+%   (method 'tria')
+%   where md is a @planet object, varargin is a list of options
+%
+% Usage: md=planetmesher(md,'method','mixed','radius',6378000,'angleresol',1);
+%        md=planetmesher(md,'method','tria','shape','iso','radius',6378000,'refinement',5);
+%
+%
+
+	%recover options
+	options=pairoptions(varargin{:});
+
+	method=getfieldvalue(options,'method','mixed');
+
+	if strcmpi(method,'mixed'),
+		%recover radius and angleresol: 
+		radius=getfieldvalue(options,'radius',6378000); %earth radius as default
+		angleresol=getfieldvalue(options,'angleresol',10); %10 degree resolution
+
+		%call mixed mesh 
+		md=planetmixedmesh(md,radius,angleresol);
+	else
+		%recover radius, shape and level of refinmenet
+		radius=getfieldvalue(options,'radius',6378000); %earth radius as default
+		refinement=getfieldvalue(options,'refinement',5); %refine 5 times
+		shape=getfieldvalue(options,'shape','ico'); 
+
+		%call triangular mesh
+		md=planettrimesh(md,shape,radius,refinement);
+	end
+end
Index: /issm/trunk/src/m/mesh/planet/planetmixedmesh.m
===================================================================
--- /issm/trunk/src/m/mesh/planet/planetmixedmesh.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/planet/planetmixedmesh.m	(revision 13395)
@@ -0,0 +1,99 @@
+function md=planetmixedmesh(md,radius,angleresol)
+%PLANETMIXEDMESH: build 2d shell mesh
+%
+% Usage: md=planetmixedshell(md,radius,angleresol)
+%
+
+conv=pi/180;
+
+r=radius;
+theta=(0:angleresol:360)';
+theta=theta*conv;
+phi=(0:angleresol:180)';
+phi=phi(2:end-1)*conv;
+
+nphi=length(phi);
+nthetha=length(theta);
+
+x=zeros(nphi*nthetha,1);
+y=zeros(nphi*nthetha,1);
+z=zeros(nphi*nthetha,1);
+
+for i=1:nphi,
+	phii=phi(i);
+	x((i-1)*nthetha+1:i*nthetha)=r.*cos(theta).*sin(phii);
+	y((i-1)*nthetha+1:i*nthetha)=r.*sin(theta).*sin(phii);
+	z((i-1)*nthetha+1:i*nthetha)=r.*cos(phii);
+end
+
+quads=zeros((nthetha-1)*(nphi-1),4);
+
+%build elements
+for i=1:nphi-1,
+	for j=1:nthetha-1,
+		count=(i-1)*(nthetha-1)+j;
+	
+		A=(i-1)*nthetha+j;
+		B=(i-1)*nthetha+j+1;
+		C=(i)*nthetha+j+1;
+		D=(i)*nthetha+j;
+		
+		quads(count,:)=[A B C D];
+	end
+end
+
+%now, add polar elements:
+%first north: phi = 0;
+x=[r.*cos(0).*sin(0);x];
+y=[r.*sin(0).*sin(0);y];
+z=[r.*cos(0);z];
+
+%add 1 to quads: 
+quads=quads+1;
+
+%add tria elements:
+trias=zeros(nthetha-1,4);
+
+for i=1:nthetha-1,
+	A=1;
+	B=i+1;
+	C=i+2;
+	trias(i,:)=[A B C NaN];
+end
+
+quads=[trias;quads];
+
+
+% now add south pole: 
+phii=180*conv;
+x=[x;r.*cos(phii).*sin(phii)];
+y=[y;r.*sin(phii).*sin(phii)];
+z=[z;r.*cos(phii)];
+nods=length(x);
+
+%add tria elements:
+trias=zeros(nthetha-1,4);
+
+start=nods-nthetha;
+for i=1:nthetha-1,
+	A=start+i-1;
+	B=start+i;
+	C=nods;
+	trias(i,:)=[A B C NaN];
+end
+
+quads=[quads;trias];
+
+
+md.mesh.elements=quads;
+md.mesh.x=x;
+md.mesh.y=y;
+md.mesh.z=z;
+md.mesh.r=sqrt(x.^2+y.^2+z.^2);
+md.mesh.theta=acos(z./md.mesh.r);
+md.mesh.phi=atan2(y,x);
+
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.numberofelements=size(md.mesh.elements,1);
+
+md.mesh.dimension=3;
Index: /issm/trunk/src/m/mesh/planet/planettrimesh.m
===================================================================
--- /issm/trunk/src/m/mesh/planet/planettrimesh.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/planet/planettrimesh.m	(revision 13395)
@@ -0,0 +1,20 @@
+function md=planettrimesh(md,shape,radius,refinement)
+%PLANETTRIMESH: build 2d shell mesh
+%
+% Usage: md=planettrimesh(md,shape,radius,refinement)
+%
+
+results = sphere_tri(shape,refinement,radius);
+md.mesh.x=results.vertices(:,1);
+md.mesh.y=results.vertices(:,2);
+md.mesh.z=results.vertices(:,3);
+md.mesh.elements=results.faces;
+
+md.mesh.r=sqrt(md.mesh.x.^2+md.mesh.y.^2+md.mesh.z.^2);
+md.mesh.theta=acos(md.mesh.z./md.mesh.r);
+md.mesh.phi=atan2(md.mesh.y,md.mesh.x);
+
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.numberofelements=size(md.mesh.elements,1);
+
+md.mesh.dimension=3;
Index: /issm/trunk/src/m/mesh/planet/sphere_project.m
===================================================================
--- /issm/trunk/src/m/mesh/planet/sphere_project.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/planet/sphere_project.m	(revision 13395)
@@ -0,0 +1,66 @@
+function V = sphere_project(v,r,c)
+
+% sphere_project - project point X,Y,Z to the surface of sphere radius r
+% 
+% V = sphere_project(v,r,c)
+% 
+% Cartesian inputs:
+% v is the vertex matrix, Nx3 (XYZ)
+% r is the sphere radius, 1x1 (default 1)
+% c is the sphere centroid, 1x3 (default 0,0,0)
+%
+% XYZ are converted to spherical coordinates and their radius is
+% adjusted according to r, from c toward XYZ (defined with theta,phi)
+% 
+% V is returned as Cartesian 3D coordinates
+% 
+
+% $Revision: 1.1 $ $Date: 2004/11/12 01:32:36 $
+
+% Licence:  GNU GPL, no implied or express warranties
+% History:  06/2002, Darren.Weber_at_radiology.ucsf.edu, created
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if ~exist('v','var'),
+    msg = sprintf('SPHERE_PROJECT: No input vertices (X,Y,Z)\n');
+    error(msg);
+end
+
+X = v(:,1);
+Y = v(:,2);
+Z = v(:,3);
+
+if ~exist('c','var'),
+    xo = 0;
+    yo = 0;
+    zo = 0;
+else
+    xo = c(1);
+    yo = c(2);
+    zo = c(3);
+end
+
+if ~exist('r','var'), r = 1; end
+
+% alternate method is to use unit vector of V
+% [ n = 'magnitude(V)'; unitV = V ./ n; ]
+% to change the radius, multiply the unitV
+% by the radius required.  This avoids the
+% use of arctan functions, which have branches.
+
+
+% Convert Cartesian X,Y,Z to spherical (radians)
+theta = atan2( (Y-yo), (X-xo) );
+phi   = atan2( sqrt( (X-xo).^2 + (Y-yo).^2 ), (Z-zo) );
+% do not calc: r = sqrt( (X-xo).^2 + (Y-yo).^2 + (Z-zo).^2);
+
+%   Recalculate X,Y,Z for constant r, given theta & phi.
+R = ones(size(phi)) * r;
+x = R .* sin(phi) .* cos(theta);
+y = R .* sin(phi) .* sin(theta);
+z = R .* cos(phi);
+
+V = [x y z];
+
+return
Index: /issm/trunk/src/m/mesh/planet/sphere_tri.m
===================================================================
--- /issm/trunk/src/m/mesh/planet/sphere_tri.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/planet/sphere_tri.m	(revision 13395)
@@ -0,0 +1,204 @@
+function [FV] = sphere_tri(shape,maxlevel,r,winding)
+
+% sphere_tri - generate a triangle mesh approximating a sphere
+% 
+% Usage: FV = sphere_tri(shape,Nrecurse,r,winding)
+% 
+%   shape is a string, either of the following:
+%   'ico'   starts with icosahedron (most even, default)
+%   'oct'   starts with octahedron
+%   'tetra' starts with tetrahedron (least even)
+%
+%   Nrecurse is int >= 0, setting the recursions (default 0)
+%
+%   r is the radius of the sphere (default 1)
+%
+%   winding is 0 for clockwise, 1 for counterclockwise (default 0).  The
+%   matlab patch command gives outward surface normals for clockwise
+%   order of vertices in the faces (viewed from outside the surface).
+%
+%   FV has fields FV.vertices and FV.faces.  The vertices 
+%   are listed in clockwise order in FV.faces, as viewed 
+%   from the outside in a RHS coordinate system.
+% 
+% The function uses recursive subdivision.  The first
+% approximation is an platonic solid, either an  icosahedron,
+% octahedron or a tetrahedron.  Each level of refinement 
+% subdivides each triangle face by a factor of 4 (see also 
+% mesh_refine).  At each refinement, the vertices are 
+% projected to the sphere surface (see sphere_project).
+% 
+% A recursion level of 3 or 4 is a good sphere surface, if
+% gouraud shading is used for rendering.
+% 
+% The returned struct can be used in the patch command, eg:
+% 
+% % create and plot, vertices: [2562x3] and faces: [5120x3]
+% FV = sphere_tri('ico',4,1);
+% lighting phong; shading interp; figure;
+% patch('vertices',FV.vertices,'faces',FV.faces,...
+%       'facecolor',[1 0 0],'edgecolor',[.2 .2 .6]);
+% axis off; camlight infinite; camproj('perspective');
+% 
+% See also: mesh_refine, sphere_project
+%
+
+
+
+% $Revision: 1.2 $ $Date: 2005/07/20 23:07:03 $
+
+% Licence:  GNU GPL, no implied or express warranties
+% Jon Leech (leech @ cs.unc.edu) 3/24/89
+% icosahedral code added by Jim Buddenhagen (jb1556@daditz.sbc.com) 5/93
+% 06/2002, adapted from c to matlab by Darren.Weber_at_radiology.ucsf.edu
+% 05/2004, reorder of the faces for the 'ico' surface so they are indeed
+% clockwise!  Now the surface normals are directed outward.  Also reset the
+% default recursions to zero, so we can get out just the platonic solids.
+%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+eegversion = '$Revision: 1.2 $';
+fprintf('SPHERE_TRI [v %s]\n',eegversion(11:15)); tic
+
+if ~exist('shape','var') || isempty(shape),
+    shape = 'ico';
+end
+fprintf('...creating sphere tesselation based on %s\n',shape);
+
+% default maximum subdivision level
+if ~exist('maxlevel','var') || isempty(maxlevel) || maxlevel < 0,
+    maxlevel = 0;
+end
+
+% default radius
+if ~exist('r','var') || isempty(r),
+    r = 1;
+end
+
+if ~exist('winding','var') || isempty(winding),
+    winding = 0;
+end
+
+
+% -----------------
+% define the starting shapes
+
+shape = lower(shape);
+
+switch shape,
+case 'tetra',
+    
+    % Vertices of a tetrahedron
+    sqrt_3 = 0.5773502692;
+    
+    tetra.v = [  sqrt_3,  sqrt_3,  sqrt_3 ;   % +X, +Y, +Z  - PPP
+                -sqrt_3, -sqrt_3,  sqrt_3 ;   % -X, -Y, +Z  - MMP
+                -sqrt_3,  sqrt_3, -sqrt_3 ;   % -X, +Y, -Z  - MPM
+                 sqrt_3, -sqrt_3, -sqrt_3 ];  % +X, -Y, -Z  - PMM
+	
+    % Structure describing a tetrahedron
+    tetra.f = [ 1, 2, 3;
+                1, 4, 2;
+                3, 2, 4;
+                4, 1, 3 ];
+    
+    FV.vertices = tetra.v;
+    FV.faces    = tetra.f;
+    
+case 'oct',
+    
+    % Six equidistant points lying on the unit sphere
+    oct.v = [  1,  0,  0 ;  %  X
+              -1,  0,  0 ; 	% -X
+               0,  1,  0 ;  %  Y
+               0, -1,  0 ; 	% -Y
+               0,  0,  1 ; 	%  Z
+               0,  0, -1 ];	% -Z
+	
+    % Join vertices to create a unit octahedron
+    oct.f = [ 1 5 3 ;    %  X  Z  Y  -  First the top half
+              3 5 2 ;    %  Y  Z -X
+              2 5 4 ;    % -X  Z -Y
+              4 5 1 ;    % -Y  Z  X
+              1 3 6 ;    %  X  Y -Z  -  Now the bottom half
+              3 2 6 ;    %  Y  Z -Z
+              2 4 6 ;    % -X  Z -Z
+              4 1 6 ];   % -Y  Z -Z
+    
+    FV.vertices = oct.v;
+    FV.faces    = oct.f;
+    
+case 'ico',
+    
+    % Twelve vertices of icosahedron on unit sphere
+    tau = 0.8506508084; % t=(1+sqrt(5))/2, tau=t/sqrt(1+t^2)
+    one = 0.5257311121; % one=1/sqrt(1+t^2) , unit sphere
+    
+    ico.v( 1,:) = [  tau,  one,    0 ]; % ZA
+    ico.v( 2,:) = [ -tau,  one,    0 ]; % ZB
+    ico.v( 3,:) = [ -tau, -one,    0 ]; % ZC
+    ico.v( 4,:) = [  tau, -one,    0 ]; % ZD
+    ico.v( 5,:) = [  one,   0 ,  tau ]; % YA
+    ico.v( 6,:) = [  one,   0 , -tau ]; % YB
+    ico.v( 7,:) = [ -one,   0 , -tau ]; % YC
+    ico.v( 8,:) = [ -one,   0 ,  tau ]; % YD
+    ico.v( 9,:) = [   0 ,  tau,  one ]; % XA
+    ico.v(10,:) = [   0 , -tau,  one ]; % XB
+    ico.v(11,:) = [   0 , -tau, -one ]; % XC
+    ico.v(12,:) = [   0 ,  tau, -one ]; % XD
+    
+    % Structure for unit icosahedron
+    ico.f = [  5,  8,  9 ;
+               5, 10,  8 ;
+               6, 12,  7 ;
+               6,  7, 11 ;
+               1,  4,  5 ;
+               1,  6,  4 ;
+               3,  2,  8 ;
+               3,  7,  2 ;
+               9, 12,  1 ;
+               9,  2, 12 ;
+              10,  4, 11 ;
+              10, 11,  3 ;
+               9,  1,  5 ;
+              12,  6,  1 ;
+               5,  4, 10 ;
+               6, 11,  4 ;
+               8,  2,  9 ;
+               7, 12,  2 ;
+               8, 10,  3 ;
+               7,  3, 11 ];
+	
+    FV.vertices = ico.v;
+    FV.faces    = ico.f;
+end
+
+
+% -----------------
+% refine the starting shapes with subdivisions
+if maxlevel,
+    
+    % Subdivide each starting triangle (maxlevel) times
+    for level = 1:maxlevel,
+        
+        % Subdivide each triangle and normalize the new points thus
+        % generated to lie on the surface of a sphere radius r.
+        FV = mesh_refine_tri4(FV);
+        FV.vertices = sphere_project(FV.vertices,r);
+        
+        % An alternative might be to define a min distance
+        % between vertices and recurse or use fminsearch
+        
+    end
+end
+
+if winding,
+    fprintf('...returning counterclockwise vertex order (viewed from outside)\n');
+    FV.faces = FV.faces(:,[1 3 2]);
+else
+    fprintf('...returning clockwise vertex order (viewed from outside)\n');
+end
+
+t=toc; fprintf('...done (%6.2f sec)\n\n',t);
+
+return
Index: /issm/trunk/src/m/mesh/rifts/meshaddrifts.m
===================================================================
--- /issm/trunk/src/m/mesh/rifts/meshaddrifts.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/rifts/meshaddrifts.m	(revision 13395)
@@ -0,0 +1,93 @@
+function md=meshaddrifts(md,riftname);
+%MESHADDRIFTS - add rifts to a preloaded mesh (typically, an argus mesh)
+%
+%   Usage:
+%      md=meshaddrifts(md,riftname);
+%
+%        where md is a model with a preexisting mesh, and riftname is the name of an .exp file.
+%        The format of the riftname file is as follows: a list of pairs of closed and open contours. 
+%        The closed contour defines the envelop of the rift, the open contour that follows in the 
+%        file defines the rift. The density of the rift should be chosen carefully in the file, as it 
+%        will be used to define the rift contour density of the mesh. The open contour density will 
+%        be preserved. There can be as many pairs of closed contour and rift contour as wished.
+
+
+%read rift: 
+domains=expread(riftname,1);
+contours=domains(1:2:end);
+rifts=domains(2:2:end);
+
+%now loop over rifts: 
+for rift_i=1:length(rifts),
+	
+	%refine rift to desired resolution: 
+	contour=contours(rift_i);
+	rift=rifts(rift_i);
+	
+	delete('Meshaddrifts.Rift.exp');
+	expwrite(rift,'Meshaddrifts.Rift.Coarse.exp');
+	expcoarsen('Meshaddrifts.Rift.exp','Meshaddrifts.Rift.Coarse.exp',rift.density);
+	delete('Meshaddrifts.Rift.Coarse.exp');
+	
+	%extract model:
+	expwrite(contour,'Meshaddrifts.Contour.exp');
+	md2=modelextract(md,'Meshaddrifts.Contour.exp');
+	
+	%create domain of md2 model: 
+	md2.mesh.segments=contourenvelope(md2,'Meshaddrifts.Contour.exp');
+	domain_index=md2.mesh.segments(1,1:2);
+	while (domain_index(end)~=domain_index(1)),
+		pos=find(md2.mesh.segments(:,1)==domain_index(end));
+		domain_index(end+1)=md2.mesh.segments(pos,2);
+	end
+	
+	domain.x=md2.mesh.x(domain_index);
+	domain.y=md2.mesh.y(domain_index);
+	domain.name='Meshaddrifts.Domain.exp';
+	domain.density=1;
+	expwrite(domain,'Meshaddrifts.Domain.exp');
+	
+	%unloop domain index: used for later.
+	domain_index=domain_index(1:end-1);
+	
+	%remesh md2 using new domain outline, and rift profile: 
+	md2=meshnodensity(md2,'Meshaddrifts.Domain.exp','Meshaddrifts.Rift.exp');
+	md2=meshprocessrifts(md2);
+	
+	%plug md2 mesh into md mesh: 
+	[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,md.mesh.numberofelements,md.mesh.numberofvertices,elconv,nodeconv,elconv2,nodeconv2]=meshplug(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,...
+								md2.mesh.elements,md2.mesh.x,md2.mesh.y,md2.mesh.z,md2.extractednodes,md2.extractedelements,domain_index);
+
+	%update md2 rifts using elconv and nodeconv, and plug them into md: 
+	md2.rifts=updateriftindexing(md2.rifts,elconv2,nodeconv2);
+	
+	for i=1:md.rifts.numrifts,
+		md.rifts.riftstruct(i)=updateriftindexing(md.rifts.riftstruct(i),elconv,nodeconv);
+	end
+	
+	if md.rifts.numrifts==0,
+		md.rifts.riftstruct=md2.rifts;
+		md.rifts.numrifts=1;
+	else
+		md.rifts.riftstruct(end+1,1)=md2.rifts;
+		md.rifts.numrifts=md.rifts.numrifts+1;
+	end
+	
+	md.mesh.segments(:,1:2)=nodeconv(md.mesh.segments(:,1:2));
+	md.mesh.segments(:,3)=elconv(md.mesh.segments(:,3));
+
+end
+
+%finish up "a la" mesh.h
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%type of model
+md.mesh.dimension=2;
Index: /issm/trunk/src/m/mesh/rifts/meshplug.m
===================================================================
--- /issm/trunk/src/m/mesh/rifts/meshplug.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/rifts/meshplug.m	(revision 13395)
@@ -0,0 +1,89 @@
+function [elements,x,y,z,numberofelements,numberofnodes,elconv,nodeconv,elconv2,nodeconv2]=meshplug(elements,x,y,z,elements2,x2,y2,z2,extractednodes,extractedelements,domain);
+%MESHPLUG - embed mesh into another one
+%     See also meshaddrifts
+
+
+%initialize elconv,nodeconv conversion tables from md mesh to new md mesh
+elconv=1:size(elements,1); elconv=elconv';
+nodeconv=1:size(x,1); nodeconv=nodeconv';
+
+%take away old elements in area of interest: 
+elements(extractedelements,:)=[];
+element_offset=size(elements,1);
+
+%update elconv after having extracted the area of interest elements
+temp_elconv=elconv; temp_elconv(extractedelements)=[];
+temp_elconvnum=1:length(temp_elconv);
+elconv(temp_elconv)=temp_elconvnum;
+elconv(extractedelements)=NaN;
+
+%initialize elconv2 and nodeconv2, conversion tables from md2 mesh to new md mesh
+elconv2=1:size(elements2,1);elconv2=elconv2'+element_offset;
+nodeconv2=(size(x,1)+1):(size(x,1)+size(x2,1)); nodeconv2=nodeconv2';
+
+extractednodes_minusborder=extractednodes;
+extractednodes_minusborder(domain)=[];
+
+x(extractednodes_minusborder)=NaN;
+y(extractednodes_minusborder)=NaN;
+
+%now, plug md2 mesh: 
+
+%first, offset all ids of md2 mesh
+elements2=elements2+length(x);
+
+%NaN border nodes in second mesh
+x2(1:length(domain))=NaN;
+y2(1:length(domain))=NaN;
+
+%redirect border nodes in elements2  to elements
+for i=1:length(domain),
+	pos=find(elements2==(i+length(x)));
+	elements2(pos)=extractednodes(domain(i));
+end
+
+%same deal for nodeconv2:
+for i=1:length(domain),
+	nodeconv2(i)=extractednodes(domain(i));
+end
+
+
+%plug elements
+elements=[elements;elements2];
+
+
+%now, increase number of nodes
+x=[x; x2];
+y=[y; y2];
+z=[z; z2];
+
+%now, get rid of NaN in x:
+while  ~isempty(find(isnan(x))),
+
+	pos=find(isnan(x));
+	node=pos(1);
+
+	%collapse node
+	x(node)=[];
+	y(node)=[];
+	z(node)=[];
+
+	%renumber all nodes > node in elements
+	pos=find(elements>node);
+	elements(pos)=elements(pos)-1;
+
+	%same deal for nodeconv2: 
+	pos=find(nodeconv2>node);
+	nodeconv2(pos)=nodeconv2(pos)-1;
+
+end
+
+numberofnodes=length(x);
+numberofelements=length(elements);
+
+%finish nodeconv: 
+temp_nodeconv=nodeconv;  temp_nodeconv(extractednodes_minusborder)=[];
+temp_nodeconvnum=1:length(temp_nodeconv);
+nodeconv(temp_nodeconv)=temp_nodeconvnum;
+nodeconv(extractednodes_minusborder)=NaN;
+
Index: /issm/trunk/src/m/mesh/rifts/meshprocessoutsiderifts.m
===================================================================
--- /issm/trunk/src/m/mesh/rifts/meshprocessoutsiderifts.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/rifts/meshprocessoutsiderifts.m	(revision 13395)
@@ -0,0 +1,110 @@
+function md=meshprocessoutsiderifts(md,domainoutline)
+%MESHPROCESSOUTSIDERIFTS - process rifts when they touch the domain outline
+%
+%   Usage:
+%      md=meshprocessoutsiderifts(md,domain)
+%
+
+
+
+%go through rifts, and figure out which ones touch the domain outline
+for i=1:md.rifts.numrifts,
+	
+	%first, flag nodes that belong to the domain outline
+	flags=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0);
+
+	rift=md.rifts.riftstruct(i);
+	tips=rift.tips;
+	outsidetips=tips(find(flags(rift.tips)==0));
+
+	%we have found outsidetips, tips that touch the domain outline. go through them
+	for j=1:length(outsidetips),
+		
+		tip=outsidetips(j);
+		%find tip in the segments, take first segment (there should be 2) that holds tip, 
+		%and node_connected_to_tip is the other node on this segment:
+		tipindex=find(rift.segments(:,1)==tip); 
+		if length(tipindex),
+			tipindex=tipindex(1);
+			node_connected_to_tip=rift.segments(tipindex,2);
+		else
+			tipindex=find(rift.segments(:,2)==tip); tipindex=tipindex(1);
+			node_connected_to_tip=rift.segments(tipindex,1);
+		end
+
+		%ok, we have the tip node, and the first node connected to it, on the rift. Now, 
+		%identify all the elements that are connected to the tip, and that are on the same 
+		%side of the rift.
+		A=tip;
+		B=node_connected_to_tip;
+
+		elements=[];
+
+		while  flags(B), %as long as B does not belong to the domain outline, keep looking.
+			%detect elements on edge A,B:
+			edgeelements=ElementsFromEdge(md.mesh.elements,A,B);
+			%rule out those we already detected
+			already_detected=ismember(edgeelements,elements);
+			nextelement=edgeelements(find(~already_detected));
+			%add new detected element to the list of elements we are looking for.
+			elements=[elements;nextelement];
+			%new B:
+			B=md.mesh.elements(nextelement,find(~ismember(md.mesh.elements(nextelement,:),[A B])));
+		end
+		
+		%take the list of elements on one side of the rift that connect to the tip, 
+		%and duplicate the tip on them, so as to open the rift to the outside.
+		num=length(md.mesh.x)+1;
+		md.mesh.x=[md.mesh.x;md.mesh.x(tip)];
+		md.mesh.y=[md.mesh.y;md.mesh.y(tip)];
+		md.mesh.numberofvertices=num;
+		
+		%replace tip in elements
+		newelements=md.mesh.elements(elements,:);
+		pos=find(newelements==tip);
+		newelements(pos)=num;
+		md.mesh.elements(elements,:)=newelements;
+		md.rifts.riftstruct(i).tips=[md.rifts.riftstruct(i).tips num];
+
+		%deal with segments
+		tipsegments=find((md.mesh.segments(:,1)==tip) | (md.mesh.segments(:,2)==tip));
+		for  k=1:length(tipsegments),
+			segment_index=tipsegments(k);
+			pos=find(md.mesh.segments(segment_index,1:2)~=tip);
+			other_node=md.mesh.segments(segment_index,pos);
+			if ~isconnected(md.mesh.elements,other_node,tip),
+				pos=find(md.mesh.segments(segment_index,1:2)==tip);
+				md.mesh.segments(segment_index,pos)=num;
+			end
+		end
+	end
+end
+
+
+%Fill in rest of fields:
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary=zeros(length(md.mesh.x),1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.rifts.numrifts=length(md.rifts.riftstruct);
+md.flowequation.element_equation=3*ones(md.mesh.numberofelements,1);
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+end
+
+function flag=isconnected(elements,A,B)% {{{
+	%ISCONNECTED: are two nodes connected by a triangulation?
+	%
+	%   Usage: flag=isconnected(elements,A,B)
+	%
+	%
+
+	elements=ElementsFromEdge(elements,A,B);
+	if isempty(elements),
+		flag=0;
+	else
+		flag=1;
+	end
+end % }}}
Index: /issm/trunk/src/m/mesh/rifts/meshprocessrifts.m
===================================================================
--- /issm/trunk/src/m/mesh/rifts/meshprocessrifts.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/rifts/meshprocessrifts.m	(revision 13395)
@@ -0,0 +1,69 @@
+function md=meshprocessrifts(md,domainoutline)
+%MESHPROCESSRIFTS - process mesh when rifts are present
+%
+%   split rifts inside mesh (rifts are defined by presence of
+%   segments inside the domain outline)
+%   if domain outline is provided, check for rifts that could touch it, and open them up.
+%
+%   Usage:
+%      md=meshprocessrifts(md,domainoutline)
+%
+%   Ex: 
+%      md=meshprocessrifts(md,'DomainOutline.exp');
+%
+
+%some checks on arguments: 
+if nargout~=1,
+	help meshprocessrifts
+	error('meshprocessrifts usage error:');
+end
+
+if nargin~=2,
+	help meshprocessrifts
+	error('meshprocessrifts usage error:');
+end
+
+%Call MEX file
+[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,md.rifts.riftstruct]=TriMeshProcessRifts(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers);
+if ~isstruct(md.rifts.riftstruct),
+	error('TriMeshProcessRifts did not find any rift');
+end
+
+%Fill in rest of fields:
+numrifts=length(md.rifts.riftstruct);
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary=zeros(length(md.mesh.x),1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+
+%get coordinates of rift tips
+for i=1:numrifts,
+	md.rifts.riftstruct(i).tip1coordinates=[md.mesh.x(md.rifts.riftstruct(i).tips(1)) md.mesh.y(md.rifts.riftstruct(i).tips(1))];
+	md.rifts.riftstruct(i).tip2coordinates=[md.mesh.x(md.rifts.riftstruct(i).tips(2)) md.mesh.y(md.rifts.riftstruct(i).tips(2))];
+end
+
+%In case we have rifts that open up the domain outline, we need to open them: 
+flags=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0);
+found=0;
+for i=1:numrifts,
+	if flags(md.rifts.riftstruct(i).tips(1))==0,
+		found=1;
+		break;
+	end
+	if flags(md.rifts.riftstruct(i).tips(2))==0,
+		found=1;
+		break;
+	end
+end
+if found,
+	md=meshprocessoutsiderifts(md,domainoutline);
+end
+
+%get elements that are not correctly oriented in the correct direction:
+aires=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+pos=find(aires<0);
+md.mesh.elements(pos,:)=[md.mesh.elements(pos,2) md.mesh.elements(pos,1) md.mesh.elements(pos,3)];
Index: /issm/trunk/src/m/mesh/rifts/meshyamsrecreateriftsegments.m
===================================================================
--- /issm/trunk/src/m/mesh/rifts/meshyamsrecreateriftsegments.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/rifts/meshyamsrecreateriftsegments.m	(revision 13395)
@@ -0,0 +1,90 @@
+function md=meshyamsrecreateriftsegments(md)
+
+	%recreate rift segments: just used for yams. temporaroy routine.
+	pos_record=[];
+	if md.rifts.numrifts,
+		for i=1:md.rifts.numrifts,
+			rift=md.rifts.riftstruct(i);
+
+			%closed rifts first:
+			if length(rift.tips)==2,
+
+				%find tip1 and tip2 for this rift, in the new mesh created by yams.
+				pos=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip1coordinates(1),rift.tip1coordinates(2));
+				tip1=md.mesh.segments(pos,1);
+				pos=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip2coordinates(1),rift.tip2coordinates(2));
+				tip2=md.mesh.segments(pos,1);
+
+				%start from tip1, and build segments of this rift. 
+				pos=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip1coordinates(1),rift.tip1coordinates(2));
+				pos_record=[pos_record; pos];
+				riftsegs=md.mesh.segments(pos,:);
+				while 1,
+					A=riftsegs(end,1); B=riftsegs(end,2); el=riftsegs(end,3);
+					%find other segment that holds B.
+					pos=find(md.mesh.segments(:,1)==B);
+					pos_record=[pos_record; pos];
+					riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+					if riftsegs(end,2)==tip1, 
+						break;
+					end
+				end
+				md.rifts.riftstruct(i).segments=riftsegs;
+				md.rifts.riftstruct(i).tips=[tip1 tip2];
+
+			else
+				%ok, this is a rift that opens up to the domain outline.  One tip is going to be 
+				%double, the other one, single. We are going to start from the single tip, towards the two 
+				%other doubles
+
+				%find tip1 and tip2 for this rift, in the new mesh created by yams.
+				pos1=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip1coordinates(1),rift.tip1coordinates(2));
+				tip1=md.mesh.segments(pos1,1);
+				pos2=find_point(md.mesh.x(md.mesh.segments(:,1)),md.mesh.y(md.mesh.segments(:,1)),rift.tip2coordinates(1),rift.tip2coordinates(2));
+				tip2=md.mesh.segments(pos2,1);
+				if length(tip1)==2,
+					%swap.
+					temp=tip1; tip1=tip2; tip2=temp;
+					temp=pos1; pos1=pos2; pos2=temp;
+					pos=pos1;
+				else
+					pos=pos1;
+				end
+
+				pos_record=[pos_record; pos];
+				riftsegs=md.mesh.segments(pos,:);
+				while 1,
+					A=riftsegs(end,1); B=riftsegs(end,2); el=riftsegs(end,3);
+					%find other segment that holds B.
+					pos=find(md.mesh.segments(:,1)==B);
+					pos_record=[pos_record; pos];
+					riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+					if ((riftsegs(end,2)==tip2(1)) | (riftsegs(end,2)==tip2(2))), 
+						%figure out which tip we reached
+						if riftsegs(end,2)==tip2(1), index=2; else index=1; end
+						break;
+					end
+				end
+
+				%ok, now, we start from the other tip2, towards tip1
+				pos=pos2(index);
+				pos_record=[pos_record; pos];
+				riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+				while 1,
+					A=riftsegs(end,1); B=riftsegs(end,2); el=riftsegs(end,3);
+					%find other segment that holds B.
+					pos=find(md.mesh.segments(:,1)==B);
+					pos_record=[pos_record; pos];
+					riftsegs=[riftsegs; md.mesh.segments(pos,:)];
+					if riftsegs(end,2)==tip1, 
+						break;
+					end
+				end
+				md.rifts.riftstruct(i).segments=riftsegs;
+				md.rifts.riftstruct(i).tips=[tip1 tip2(1) tip2(2)];
+
+			end
+		end
+	end
+	%take out rift segments from segments
+	md.mesh.segments(pos_record,:)=[];
Index: /issm/trunk/src/m/mesh/rifts/rifttipsonmesh.m
===================================================================
--- /issm/trunk/src/m/mesh/rifts/rifttipsonmesh.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/rifts/rifttipsonmesh.m	(revision 13395)
@@ -0,0 +1,26 @@
+function tips=rifttipsonmesh(md,riftoutline)
+%RIFTTIPSONMESH: identify, using a rift outline, the nodes that are tips of 
+%                rifts.
+
+%read rifts from outline file
+rifts=expread(riftoutline,1);
+
+tips=[];
+
+for i=1:length(rifts),
+	rift=rifts(i);
+
+	x_tip=rift.x(1);
+	y_tip=rift.y(1);
+	
+	index=find_point(md.mesh.x,md.mesh.y,x_tip,y_tip);
+	tips(end+1)=index;
+
+	x_tip=rift.x(end);
+	y_tip=rift.y(end);
+	
+	index=find_point(md.mesh.x,md.mesh.y,x_tip,y_tip);
+	tips(end+1)=index;
+
+end
+
Index: /issm/trunk/src/m/mesh/rifts/rifttipsrefine.m
===================================================================
--- /issm/trunk/src/m/mesh/rifts/rifttipsrefine.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/rifts/rifttipsrefine.m	(revision 13395)
@@ -0,0 +1,26 @@
+function md=rifttipsrefine(md,filename,resolution,circleradius);
+%RIFTTIPSREFINE - refine mesh near rift tips
+%
+%   Usage:
+%      md=rifttipsrefine(md,filename,resolution,circleradius);
+
+numberofnodes=50;
+
+%take rifts, and create refinement circles around tips
+rifts=expread(filename,1);
+
+!echo -n "" > Circles.exp
+for i=1:length(rifts),
+	tip1=[rifts(i).x(1) rifts(i).y(1)];
+	tip2=[rifts(i).x(end) rifts(i).y(end)];
+	%create circle around tip
+	expcreatecircle('Circle1.exp',tip1(1),tip1(2),circleradius,numberofnodes);
+	expcreatecircle('Circle2.exp',tip2(1),tip2(2),circleradius,numberofnodes);
+	!cat Circles.exp Circle1.exp Circle2.exp > Circles2.exp
+	!mv Circles2.exp Circles.exp
+	!rm -rf Circle1.exp Circle2.exp
+end
+
+md=meshexprefine(md,'Circles.exp',resolution);
+
+system('rm -rf Circles.exp');
Index: /issm/trunk/src/m/mesh/rifts/updateriftindexing.m
===================================================================
--- /issm/trunk/src/m/mesh/rifts/updateriftindexing.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/rifts/updateriftindexing.m	(revision 13395)
@@ -0,0 +1,11 @@
+function rift=updateriftindexing(rift,elconv,nodeconv)
+%UPDATERIFTINDEXING - update rift indexing, using mesh to new mesh conversion tables
+%     See also meshaddrift
+
+rift.segments(:,1:2)=nodeconv(rift.segments(:,1:2));
+rift.segments(:,3)=elconv(rift.segments(:,3));
+rift.pairs=elconv(rift.pairs);
+rift.tips=nodeconv(rift.tips);
+
+rift.penaltypairs(:,1:2)=nodeconv(rift.penaltypairs(:,1:2));
+rift.penaltypairs(:,3:4)=elconv(rift.penaltypairs(:,3:4));
Index: /issm/trunk/src/m/mesh/roundmesh.m
===================================================================
--- /issm/trunk/src/m/mesh/roundmesh.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/roundmesh.m	(revision 13395)
@@ -0,0 +1,34 @@
+function md=roundmesh(md,radius,resolution)
+%ROUNDMESH - create an unstructured round mesh 
+%
+%   This script will generate a structured round mesh
+%   - radius     : specifies the radius of the circle in meters
+%   - resolution : specifies the resolution in meters
+%
+%   Usage:
+%      md=roundmesh(md,radius,resolution)
+
+%First we have to create the domain outline 
+
+%Get number of points on the circle
+pointsonedge=floor((2*pi*radius) / resolution);
+
+%Calculate the cartesians coordinates of the points
+x_list=ones(pointsonedge,1); y_list=ones(pointsonedge,1);
+theta=(0:2*pi/pointsonedge:2*pi*(1-1/pointsonedge))';
+x_list=radius*x_list.*cos(theta);
+y_list=radius*y_list.*sin(theta);
+A=struct('x',x_list,'y',y_list,'density',1);
+expwrite(A,'RoundDomainOutline.exp');
+
+%Call Bamg
+md=triangle(md,'RoundDomainOutline.exp',resolution);
+%md=bamg(md,'domain','RoundDomainOutline.exp','hmin',resolution);
+
+%move the closest node to the center
+[mini pos]=min(md.mesh.x.^2+md.mesh.y.^2);
+md.mesh.x(pos)=0;
+md.mesh.y(pos)=0;
+
+%delete domain
+delete('RoundDomainOutline.exp')
Index: /issm/trunk/src/m/mesh/squaremesh.m
===================================================================
--- /issm/trunk/src/m/mesh/squaremesh.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/squaremesh.m	(revision 13395)
@@ -0,0 +1,78 @@
+function md=squaremesh(md,Lx,Ly,nx,ny)
+%SQUAREMESH - create a structured square mesh 
+%
+%   This script will generate a structured square mesh
+%   Lx and Ly are the dimension of the domain (in meters)
+%   nx anx ny are the number of nodes in the x and y direction
+%   The coordinates x and y returned are in meters.
+%
+%   Usage:
+%      [md]=squaremesh(md,Lx,Ly,nx,ny)
+
+%get number of elements and number of nodes
+nel=(nx-1)*(ny-1)*2;
+nods=nx*ny;
+
+%initialization
+segments=zeros(0,3);
+index=zeros(nel,3);
+x=zeros(nx*ny,1);
+y=zeros(nx*ny,1);
+
+%create coordinates
+for n=1:nx,
+	for m=1:ny,
+		x((n-1)*ny+m)=(n-1);
+		y((n-1)*ny+m)=(m-1);
+	end
+end
+
+%create index
+for n=1:(nx-1)
+	for m=1:(ny-1),
+		A=(n-1)*ny+m;
+		B=A+1;
+		C=n*ny+m;
+		D=C+1;
+		index((n-1)*(ny-1)*2+2*(m-1)+1,:)=[A C B];
+		index((n-1)*(ny-1)*2+2*m,:)=[B C D];
+	end
+end
+
+%Scale  x and y
+x=x/max(x)*Lx;
+y=y/max(y)*Ly;
+
+%create segments
+segments=zeros(2*(nx-1)+2*(ny-1),3);
+%left edge:
+segments(1:ny-1,:)=[[2:ny]' [1:ny-1]' 2*[1:ny-1]'-1];
+%right edge:
+segments(ny:2*(ny-1),:)=[[ny*(nx-1)+1:nx*ny-1]' [ny*(nx-1)+2:nx*ny]' 2*[(ny-1)*(nx-2)+1:(nx-1)*(ny-1)]'];
+%front edge:
+segments(2*(ny-1)+1:2*(ny-1)+(nx-1),:)=[[2*ny:ny:ny*nx]' [ny:ny:ny*(nx-1)]' [2*(ny-1):2*(ny-1):2*(nx-1)*(ny-1)]'];
+%back edge
+segments(2*(ny-1)+(nx-1)+1:2*(nx-1)+2*(ny-1),:)=[[1:ny:(nx-2)*ny+1]' [ny+1:ny:ny*(nx-1)+1]' [1:2*(ny-1):2*(nx-2)*(ny-1)+1]'];
+
+%plug coordinates and nodes
+md.mesh.x=x;
+md.mesh.y=y;
+md.mesh.z=zeros(nods,1);
+md.mesh.numberofvertices=nods;
+md.mesh.vertexonboundary=zeros(nods,1);md.mesh.vertexonboundary(segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(nods,1);
+md.mesh.vertexonsurface=ones(nods,1);
+
+%plug elements
+md.mesh.elements=index;
+md.mesh.segments=segments;
+md.mesh.numberofelements=nel;
+md.mesh.elementonbed=ones(nel,1);
+md.mesh.elementonsurface=ones(nel,1);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%plug other field
+md.mesh.dimension=2;
Index: /issm/trunk/src/m/mesh/triangle.m
===================================================================
--- /issm/trunk/src/m/mesh/triangle.m	(revision 13395)
+++ /issm/trunk/src/m/mesh/triangle.m	(revision 13395)
@@ -0,0 +1,82 @@
+function md=triangle(md,domainname,varargin)
+%TRIANGLE - create model mesh using the triangle package
+%
+%   This routine creates a model mesh using TriMesh and a domain outline, to within a certain resolution
+%   where md is a @model object, domainname is the name of an Argus domain outline file, 
+%   and resolution is a characteristic length for the mesh (same unit as the domain outline
+%   unit). Riftname is an optional argument (Argus domain outline) describing rifts.
+%
+%   Usage:
+%      md=triangle(md,domainname,resolution)
+%   or md=triangle(md,domainname,riftname, resolution)
+%
+%   Examples:
+%      md=triangle(md,'DomainOutline.exp',1000);
+%      md=triangle(md,'DomainOutline.exp','Rifts.exp',1500);
+
+%Figure out a characteristic area. Resolution is a node oriented concept (ex a 1000m  resolution node would 
+%be made of 1000*1000 area squares). 
+if (nargin==3),
+	resolution=varargin{1};
+	riftname='';
+end
+if (nargin==4),
+	riftname=varargin{1};
+	resolution=varargin{2};
+end
+
+%Check that mesh was not already run, and warn user: 
+if md.mesh.numberofelements~=0,
+	choice=input('This model already has a mesh. Are you sure you want to go ahead? (y/n)','s');
+	if ~strcmp(choice,'y')
+		disp('no meshing done ... exiting');
+		return
+	end
+end
+
+area=resolution^2;
+
+%Mesh using TriMesh
+[elements,x,y,segments,segmentmarkers]=TriMesh(domainname,riftname,area);
+
+%check that all the created nodes belong to at least one element
+orphan=find(~ismember([1:length(x)],sort(unique(elements(:)))));
+for i=1:length(orphan),
+	disp('WARNING: removing orphans');
+	%get rid of the orphan node i
+	%update x and y
+	x=[x(1:orphan(i)-(i-1)-1); x(orphan(i)-(i-1)+1:end)];
+	y=[y(1:orphan(i)-(i-1)-1); y(orphan(i)-(i-1)+1:end)];
+	%update elements
+	pos=find(elements>orphan(i)-(i-1));
+	elements(pos)=elements(pos)-1;
+	%update segments
+	pos1=find(segments(:,1)>orphan(i)-(i-1));
+	pos2=find(segments(:,2)>orphan(i)-(i-1));
+	segments(pos1,1)=segments(pos1,1)-1;
+	segments(pos2,2)=segments(pos2,2)-1;
+end
+
+%plug into md
+md.mesh.x=x;
+md.mesh.y=y;
+md.mesh.elements=elements;
+md.mesh.segments=segments;
+md.mesh.segmentmarkers=segmentmarkers;
+
+%Fill in rest of fields:
+md.mesh.numberofelements=length(md.mesh.elements);
+md.mesh.numberofvertices=length(md.mesh.x);
+md.mesh.z=zeros(md.mesh.numberofvertices,1);
+md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
+md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
+md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
+md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
+
+%Now, build the connectivity tables for this mesh.
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+
+%type of model
+md.mesh.dimension=2;
Index: /issm/trunk/src/m/mesh/triangle.py
===================================================================
--- /issm/trunk/src/m/mesh/triangle.py	(revision 13395)
+++ /issm/trunk/src/m/mesh/triangle.py	(revision 13395)
@@ -0,0 +1,56 @@
+from numpy import *
+import TriMesh as tm
+import NodeConnectivity as nc
+import ElementConnectivity as ec
+
+def triangle(md, domainname, resolution,riftname=''):
+	#TRIANGLE - create model mesh using the triangle package
+	#
+	#   This routine creates a model mesh using TriMesh and a domain outline, to within a certain resolution
+	#   where md is a @model object, domainname is the name of an Argus domain outline file, 
+	#   and resolution is a characteristic length for the mesh (same unit as the domain outline
+	#   unit). Riftname is an optional argument (Argus domain outline) describing rifts.
+	#
+	#   Usage:
+	#      md=triangle(md,domainname,resolution)
+	#   or md=triangle(md,domainname, resolution, riftname)
+	#
+	#   Examples:
+	#      md=triangle(md,'DomainOutline.exp',1000);
+	#      md=triangle(md,'DomainOutline.exp',1000,'Rifts.exp');
+
+
+	#Figure out a characteristic area. Resolution is a node oriented concept (ex a 1000m  resolution node would 
+	#be made of 1000*1000 area squares). 
+
+	#Check that mesh was not already run, and warn user: 
+	if md.mesh.numberofelements != 0.:
+		choice = input('This model already has a mesh. Are you sure you want to go ahead? (y/n)')
+		if choice != 'y':
+			print 'no meshing done ... exiting'
+			return []
+		
+	area = resolution**2.
+
+	#Mesh using TriMesh
+	[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers]=tm.TriMesh(domainname,riftname,area)
+
+
+	#Fill in rest of fields:
+	md.mesh.numberofelements = len(md.mesh.elements)
+	md.mesh.numberofvertices = len(md.mesh.x)
+	md.mesh.z = zeros(md.mesh.numberofvertices)
+	md.mesh.vertexonboundary = zeros(md.mesh.numberofvertices)
+	md.mesh.vertexonboundary[md.mesh.segments[:,0:2].astype(int)-1] = 1.
+	md.mesh.vertexonbed = ones(md.mesh.numberofvertices)
+	md.mesh.vertexonsurface = ones(md.mesh.numberofvertices)
+	md.mesh.elementonbed = ones(md.mesh.numberofelements)
+	md.mesh.elementonsurface = ones(md.mesh.numberofelements)
+
+	#Now, build the connectivity tables for this mesh.
+	[md.mesh.vertexconnectivity]= nc.NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices)
+	[md.mesh.elementconnectivity] = ec.ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity)
+	
+	#type of model
+	md.mesh.dimension = 2.
+	return md
Index: /issm/trunk/src/m/miscellaneous/BinRead.py
===================================================================
--- /issm/trunk/src/m/miscellaneous/BinRead.py	(revision 13395)
+++ /issm/trunk/src/m/miscellaneous/BinRead.py	(revision 13395)
@@ -0,0 +1,168 @@
+#! /usr/bin/env python
+
+import os
+import sys
+import numpy
+import math
+import struct
+
+def BinRead(filin,filout=''):
+
+	from MatlabFuncs import *
+	from EnumDefinitions import *
+	from EnumToString import EnumToString
+
+	print "reading binary file."
+	f=open(filin,'rb')
+
+	if filout:
+		sys.stdout=open(filout,'w')
+
+	while True:
+		try:
+			#Step 1: read the enum to identify this record uniquely
+			enum=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+		except struct.error as e:
+			print "probable EOF: %s" % e
+			break
+		print "\nenum = %d (%s)" % (enum,EnumToString(enum)[0])
+
+		#Step 2: read the data itself.
+		#first read length of record
+		reclen=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+		print "reclen = %d" % reclen
+
+		#read data code: 
+		code=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+		print "code = %d" % code
+
+		if   code == FormatToCode('Boolean'):
+#			bval=struct.unpack('b',f.read(reclen-struct.calcsize('i')))[0]
+			bval=struct.unpack('i',f.read(reclen-struct.calcsize('i')))[0]
+			print "bval = %d" % bval
+
+		elif code == FormatToCode('Integer'):
+			ival=struct.unpack('i',f.read(reclen-struct.calcsize('i')))[0]
+			print "ival = %d" % ival
+
+		elif code == FormatToCode('Double'):
+			dval=struct.unpack('d',f.read(reclen-struct.calcsize('i')))[0]
+			print "dval = %f" % dval
+
+		elif code == FormatToCode('String'):
+			strlen=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+			print "strlen = %d" % strlen
+			sval=struct.unpack('%ds' % strlen,f.read(strlen))[0]
+			print "sval = '%s'" % sval
+
+		elif code == FormatToCode('BooleanMat'):
+			#read matrix type: 
+			mattype=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+			print "mattype = %d" % mattype
+
+			#now read matrix
+			s=[0,0]
+			s[0]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+			s[1]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+			print "s = [%dx%d]" % (s[0],s[1])
+			data=numpy.zeros((s[0],s[1]))
+			for i in xrange(s[0]):
+				for j in xrange(s[1]):
+					data[i][j]=struct.unpack('d',f.read(struct.calcsize('d')))[0]    #get to the "c" convention, hence the transpose
+					print "data[%d,%d] = %f" % (i,j,data[i][j])
+
+		elif code == FormatToCode('IntMat'):
+			#read matrix type: 
+			mattype=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+			print "mattype = %d" % mattype
+
+			#now read matrix
+			s=[0,0]
+			s[0]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+			s[1]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+			print "s = [%dx%d]" % (s[0],s[1])
+			data=numpy.zeros((s[0],s[1]))
+			for i in xrange(s[0]):
+				for j in xrange(s[1]):
+					data[i][j]=struct.unpack('d',f.read(struct.calcsize('d')))[0]    #get to the "c" convention, hence the transpose
+					print "data[%d,%d] = %f" % (i,j,data[i][j])
+
+		elif code == FormatToCode('DoubleMat'):
+			#read matrix type: 
+			mattype=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+			print "mattype = %d" % mattype
+
+			#now read matrix
+			s=[0,0]
+			s[0]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+			s[1]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
+			print "s = [%dx%d]" % (s[0],s[1])
+			data=numpy.zeros((s[0],s[1]))
+			for i in xrange(s[0]):
+				for j in xrange(s[1]):
+					data[i][j]=struct.unpack('d',f.read(struct.calcsize('d')))[0]    #get to the "c" convention, hence the transpose
+					print "data[%d,%d] = %f" % (i,j,data[i][j])
+
+		elif code == FormatToCode('MatArray'):
+			fid.seek(reclen-4,1)
+			print "skipping %d bytes for code %d." % (code, reclen-4)
+
+		elif code == FormatToCode('StringArray'):
+			fid.seek(reclen-4,1)
+			print "skipping %d bytes for code %d." % (code, reclen-4)
+
+		else:
+			raise TypeError('BinRead error message: data type: %d not supported yet! (%s)' % (code,EnumToString(enum)[0]))
+
+	f.close()
+
+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
+# }}}
+
+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='BinRead - function to read binary input file.')
+	parser.add_argument('-f','--filin', help='name of binary input file', default='')
+	args = parser.parse_args()
+
+	BinRead(args.filin)
+
Index: /issm/trunk/src/m/miscellaneous/MatlabFuncs.py
===================================================================
--- /issm/trunk/src/m/miscellaneous/MatlabFuncs.py	(revision 13395)
+++ /issm/trunk/src/m/miscellaneous/MatlabFuncs.py	(revision 13395)
@@ -0,0 +1,60 @@
+def oshostname():
+	import socket
+
+	return socket.gethostname().lower().split('.')[0]
+
+def ispc():
+	import platform
+
+	if 'Windows' in platform.system():
+		return True
+	else:
+		return False
+
+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/trunk/src/m/miscellaneous/fielddisplay.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/fielddisplay.m	(revision 13395)
+++ /issm/trunk/src/m/miscellaneous/fielddisplay.m	(revision 13395)
@@ -0,0 +1,151 @@
+function fielddisplay(md,name,comment)
+%FIELDDISPLAY - display model field
+%
+%   Usage:
+%      fielddisplay(md,name,comment)
+
+	%get field
+	field=md.(name);
+
+	%disp corresponding line as a function of field type (offset set as 9 spaces)
+	parsedisplay('         ',name,field,comment);
+
+end %function
+
+function parsedisplay(offset,name,field,comment); %{{{
+
+	%string
+	if ischar(field),
+
+		if length(field)>30;
+			displayunit(offset,name,'not displayed',comment),
+		else
+			displayunit(offset,name,['''' field ''''],comment),
+		end
+
+	%numeric
+	elseif isnumeric(field)
+
+		%get size
+		fieldsize=size(field);
+
+		%double
+		if max(fieldsize)==1,
+			displayunit(offset,name,num2str(field),comment),
+		%matrix
+		else
+			displayunit(offset,name,['(' num2str(fieldsize(1)) 'x' num2str(fieldsize(2)) ')'],comment),
+		end
+
+	%logical
+	elseif islogical(field)
+
+		%get size
+		fieldsize=size(field);
+
+		%single value
+		if max(fieldsize)==1,
+			if (field)
+				displayunit(offset,name,'true',comment),
+			else
+				displayunit(offset,name,'false',comment),
+			end
+		%matrix
+		else
+			displayunit(offset,name,['(' num2str(fieldsize(1)) 'x' num2str(fieldsize(2)) ')'],comment),
+		end
+
+	%structure
+	elseif isstruct(field),
+		struct_display(offset,name,field,comment),
+
+	%cell
+	elseif iscell(field),
+		cell_display(offset,name,field,comment),
+
+	else
+		displayunit(offset,name,'not displayed',comment),
+
+	end
+end%}}}
+
+function struct_display(offset,name,field,comment) % {{{
+
+	if ~isempty(fields(field))
+		displayunit(offset,name,'(structure)',comment),
+		offset=[offset '   '];
+
+		structure_fields=fields(field);
+
+		for i=1:length(structure_fields),
+
+			%get current field
+			sfield=field.(structure_fields{i});
+
+			%display value
+			parsedisplay(offset,structure_fields{i},sfield,'');
+		end
+
+	else
+		displayunit(offset,name,'N/A',comment),
+
+	end
+end% }}}
+function cell_display(offset,name,field,comment) % {{{
+
+	%initialization
+	string='{';
+
+	%go through the cell and fill string
+	if length(field)<5;
+		for i=1:length(field),
+			if ischar(field{i}),
+				string=[string ''''  field{i} ''','];
+			elseif (isnumeric(field{i}) & length(field{i})==1)
+				string=[string num2str(field{i}) ',' ];
+			else
+				string='{';
+				break
+			end
+		end
+	end
+	if strcmp(string,'{'),
+		string=['(' num2str(size(field,1)) 'x' num2str(size(field,2)) ')'];
+	else
+		string=[string(1:end-1) '}'];
+	end
+
+	%call displayunit
+	displayunit(offset,name,string,comment);
+end% }}}
+function displayunit(offset,name,characterization,comment),% {{{
+
+	%take care of name
+	if length(name)>23,
+		name=[name(1:20) '...'];
+	end
+
+	%take care of characterization
+	if (strcmp(characterization,['''' '''']) | strcmp(characterization,'NaN')),
+		characterization='N/A';
+	end
+	if length(characterization)>15,
+		characterization=[characterization(1:12) '...'];
+	end
+
+	%print
+	if isempty(comment)
+		disp(sprintf('%s%-23s: %-15s',offset,name,characterization));
+	else
+		if ischar(comment),
+			disp(sprintf('%s%-23s: %-15s -- %s',offset,name,characterization,comment));
+		elseif iscell(comment),
+			disp(sprintf('%s%-23s: %-15s -- %s',offset,name,characterization,comment{1}));
+			for i=2:length(comment),
+				disp(sprintf('%s%-23s  %-15s    %s',offset,'','',comment{i}));
+			end
+		else
+			error('fielddisplay error message: format for comment not supported yet');
+		end
+	end
+end% }}}
Index: /issm/trunk/src/m/miscellaneous/fielddisplay.py
===================================================================
--- /issm/trunk/src/m/miscellaneous/fielddisplay.py	(revision 13395)
+++ /issm/trunk/src/m/miscellaneous/fielddisplay.py	(revision 13395)
@@ -0,0 +1,136 @@
+#Module import 
+import numpy
+from math import isnan
+from MatlabFuncs import *
+
+def fielddisplay(md,name,comment):
+	"""
+	FIELDDISPLAY - display model field
+
+	   Usage:
+	      fielddisplay(md,name,comment)
+	"""
+
+	#get field
+	field=getattr(md,name)
+
+	#disp corresponding line as a function of field type (offset set as 9 spaces)
+	return parsedisplay("         ",name,field,comment);
+
+def parsedisplay(offset,name,field,comment):    # {{{ 
+
+	#string
+	if isinstance(field,(str,unicode)):
+
+		if len(field)>30:
+			string=displayunit(offset,name,"not displayed",comment)
+		else:
+			string=displayunit(offset,name,"'%s'" % field,comment)
+
+	#numeric
+	elif isinstance(field,(int,long,float)):
+		string=displayunit(offset,name,str(field),comment) 
+
+	#matrix
+	elif isinstance(field,numpy.ndarray):
+		string=displayunit(offset,name,str(field.shape),comment)
+
+	#logical
+	elif isinstance(field,bool):
+		if field:
+			string=displayunit(offset,name,"True",comment)
+		else:
+			string=displayunit(offset,name,"False",comment)
+	
+	#dictionary
+	elif isinstance(field,dict):
+		string=dict_display(offset,name,field,comment)
+
+	#list or tuple
+	elif isinstance(field,(list,tuple)):
+		string=list_display(offset,name,field,comment)
+
+	else:
+		string=displayunit(offset,name,"not displayed",comment)
+		
+	return string
+	# }}}
+
+def dict_display(offset,name,field,comment):    # {{{
+
+	if field:
+		string =displayunit(offset,name,'{dictionary}',comment)+'\n'
+		offset+='   '
+
+		for structure_field,sfield in field.iteritems():
+			string+=parsedisplay(offset,str(structure_field),sfield,'')+'\n'
+
+		if string and string[-1]=='\n':
+			string=string[:-1]
+
+	else:
+		string=displayunit(offset,name,'N/A',comment)
+
+	return string
+	# }}}
+
+def list_display(offset,name,field,comment):    # {{{
+
+	#initialization
+	if   isinstance(field,list):
+		sbeg='['
+		send=']'
+	elif isinstance(field,tuple):
+		sbeg='('
+		send=')'
+	string=sbeg
+
+	#go through the cell and fill string
+	if len(field)<5:
+		for fieldi in field:
+			if   isinstance(fieldi,(str,unicode)):
+				string+="'%s'," % fieldi
+			elif isinstance(fieldi,(bool,int,long,float)):
+				string+="%s," % str(fieldi)
+			else:
+				string=sbeg
+				break
+
+	if strcmp(string,sbeg):
+		string="%s%dx1%s" % (sbeg,len(field),send)
+	else:
+		string=string[:-1]+send
+
+	#call displayunit
+	return displayunit(offset,name,string,comment)
+	# }}}
+
+def displayunit(offset,name,characterization,comment):    # {{{
+
+	#take care of name
+	if len(name)>23:
+		name="%s..." % name[:20]
+	
+	#take care of characterization
+	if strcmp(characterization,"''") or strcmp(characterization,'""') or strcmpi(characterization,'nan'):
+		characterization="N/A"
+	
+	if len(characterization)>15:
+		characterization="%s..." % characterization[:12]
+	
+	#print
+	if not comment:
+		string="%s%-23s: %-15s" % (offset,name,characterization)
+	else:
+		if   isinstance(comment,(str,unicode)):
+			string="%s%-23s: %-15s -- %s" % (offset,name,characterization,comment)
+		elif isinstance(comment,list):
+			string="%s%-23s: %-15s -- %s" % (offset,name,characterization,comment[0])
+			for commenti in comment:
+				string+="\n%s%-23s  %-15s    %s" % (offset,'','',comment[i])
+		else:
+			raise RuntimeError("fielddisplay error message: format for comment not supported yet")
+
+	return string
+	# }}}
+
Index: /issm/trunk/src/m/miscellaneous/isnans.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/isnans.m	(revision 13395)
+++ /issm/trunk/src/m/miscellaneous/isnans.m	(revision 13395)
@@ -0,0 +1,15 @@
+function returnvalue=isnans(array)
+%ISNANS: figure out if an array is nan. wrapper to isnan from matlab which stupidly does not allow this test  for structures!
+%
+%  Usage:    isnans(array)
+%
+%  See also : ISNAN 
+
+
+if isstruct(array), 
+	returnvalue=0;
+elseif iscell(array)
+	returnvalue=0;
+else
+	returnvalue=isnan(array);
+end
Index: /issm/trunk/src/m/miscellaneous/isnans.py
===================================================================
--- /issm/trunk/src/m/miscellaneous/isnans.py	(revision 13395)
+++ /issm/trunk/src/m/miscellaneous/isnans.py	(revision 13395)
@@ -0,0 +1,18 @@
+import numpy
+
+def isnans(array):
+	"""
+	ISNANS: figure out if an array is nan. wrapper to isnan from matlab which stupidly does not allow this test  for structures!
+
+	   Usage:    isnans(array)
+
+	      See also : ISNAN 
+	"""
+
+	if   isinstance(array,(tuple,list,dict)): 
+		returnvalue=0
+	else:
+		returnvalue=numpy.isnan(array)
+
+	return returnvalue
+
Index: /issm/trunk/src/m/miscellaneous/issmdoc.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/issmdoc.m	(revision 13395)
+++ /issm/trunk/src/m/miscellaneous/issmdoc.m	(revision 13395)
@@ -0,0 +1,15 @@
+%Quick documentation for ISSM
+
+%First get ISSM tier: 
+ISSM_DIR=issmdir();
+
+disp(sprintf('\n%s','  A comprehensive documentation is available on http://issm.jpl.nasa.gov'));
+disp(sprintf('\n%s','  Example: how to create a square ice shelf'));
+disp(sprintf('%s','	   go to ',ISSM_DIR,'/examples/SquareIceshelf'));
+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=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=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/trunk/src/m/miscellaneous/netcdf2struct.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/netcdf2struct.m	(revision 13395)
+++ /issm/trunk/src/m/miscellaneous/netcdf2struct.m	(revision 13395)
@@ -0,0 +1,166 @@
+function S=netcdf2struct(File)
+%NETCDF2STRUCT - load netcdf file and convert to a matlab structure
+%
+%   Usage:
+%      S=netcdf2struct(File);
+
+%Read netcdf file
+data=readnetcdf(File);
+
+%initialize output
+S=struct();
+
+%All the variables are in VarArray field
+variables=data.VarArray;
+for i=1:size(variables,2),
+	fieldname=deblank(variables(i).Str);
+	fieldvalue=double(squeeze(variables(i).Data));
+	S.(fieldname)=fieldvalue;
+end
+
+%All the variables are in AttArray field
+variables=data.AttArray;
+for i=1:size(variables,2),
+	fieldname=deblank(variables(i).Str);
+	fieldvalue=double(variables(i).Val);
+	S.(fieldname)=fieldvalue;
+end
+end
+
+function S = readnetcdf(File,varargin)
+% Function to read NetCDF files
+%   S = netcdf(File)
+% Input Arguments
+%   File = NetCDF file to read
+% Optional Input Arguments:
+%   'Var',Var - Read data for VarArray(Var), default [1:length(S.VarArray)]
+%   'Rec',Rec - Read data for Record(Rec), default [1:S.NumRecs]
+% Output Arguments:
+%   S    = Structure of NetCDF data organised as per NetCDF definition
+% Notes:
+%   Only version 1, classic 32bit, NetCDF files are supported. By default
+% data are extracted into the S.VarArray().Data field for all variables.
+% To read the header only call S = netcdf(File,'Var',[]);
+%
+% SEE ALSO
+% ---------------------------------------------------------------------------
+S = [];
+
+try
+   if exist(File,'file') fp = fopen(File,'r','b');
+   else fp = []; error('File not found'); end
+   if fp == -1   error('Unable to open file'); end
+
+% Read header
+   Magic = fread(fp,4,'uint8=>char');
+   if strcmp(Magic(1:3),'CDF') error('Not a NetCDF file'); end
+   if uint8(Magic(4))~=1       error('Version not supported'); end
+   S.NumRecs  = fread(fp,1,'uint32=>uint32');
+   S.DimArray = DimArray(fp);
+   S.AttArray = AttArray(fp);
+   S.VarArray = VarArray(fp);
+
+% Setup indexing to arrays and records
+   Var = ones(1,length(S.VarArray));
+   Rec = ones(1,S.NumRecs);
+   for i = 1:2:length(varargin)
+      if     strcmp(upper(varargin{i}),'VAR') Var=Var*0; Var(varargin{i+1})=1;
+      elseif strcmp(upper(varargin{i}),'REC') Rec=Rec*0; Rec(varargin{i+1})=1;
+      else error('Optional input argument not recognised'); end
+   end
+   if sum(Var)==0 fclose(fp); return; end
+
+% Read non-record variables
+   Dim = double(cat(2,S.DimArray.Dim));
+   ID  = double(cat(2,S.VarArray.Type));
+
+   for i = 1:length(S.VarArray)
+      D = Dim(S.VarArray(i).DimID+1); N = prod(D); RecID{i}=find(D==0);
+      if isempty(RecID{i})
+         if length(D)==0 D = [1,1]; N = 1; elseif length(D)==1 D=[D,1]; end
+         if Var(i)
+            S.VarArray(i).Data = ReOrder(fread(fp,N,[Type(ID(i)),'=>',Type(ID(i))]),D);
+            fread(fp,(Pad(N,ID(i))-N)*Size(ID(i)),'uint8=>uint8');
+         else fseek(fp,Pad(N,ID(i))*Size(ID(i)),'cof'); end
+      else S.VarArray(i).Data = []; end
+   end
+
+% Read record variables
+   for k = 1:S.NumRecs
+      for i = 1:length(S.VarArray)
+         if ~isempty(RecID{i})
+            D = Dim(S.VarArray(i).DimID+1); D(RecID{i}) = 1; N = prod(D);
+            if length(D)==1 D=[D,1]; end
+            if Var(i) & Rec(k)
+               S.VarArray(i).Data = cat(RecID{i},S.VarArray(i).Data,...
+                  ReOrder(fread(fp,N,[Type(ID(i)),'=>',Type(ID(i))]),D));
+               if N > 1 fread(fp,(Pad(N,ID(i))-N)*Size(ID(i)),'uint8=>uint8'); end
+            else fseek(fp,Pad(N,ID(i))*Size(ID(i)),'cof'); end
+         end
+      end
+   end
+
+   fclose(fp);
+catch
+   Err = lasterror; fprintf('%s\n',Err.message);
+   if ~isempty(fp) && fp ~= -1 fclose(fp); end
+end
+
+% ---------------------------------------------------------------------------------------
+% Utility functions
+
+function S = Size(ID)
+% Size of NetCDF data type, ID, in bytes
+   S = subsref([1,1,2,4,4,8],struct('type','()','subs',{{ID}}));
+
+function T = Type(ID)
+% Matlab string for CDF data type, ID
+   T = subsref({'int8','char','int16','int32','single','double'},...
+               struct('type','{}','subs',{{ID}}));
+
+function N = Pad(Num,ID)
+% Number of elements to read after padding to 4 bytes for type ID
+   N = (double(Num) + mod(4-double(Num)*Size(ID),4)/Size(ID)).*(Num~=0);
+
+function S = String(fp)
+% Read a CDF string; Size,[String,[Padding]]
+   S = fread(fp,Pad(fread(fp,1,'uint32=>uint32'),1),'uint8=>char').';
+
+function A = ReOrder(A,S)
+% Rearrange CDF array A to size S with matlab ordering
+   A = permute(reshape(A,fliplr(S)),fliplr(1:length(S)));
+
+function S = DimArray(fp)
+% Read DimArray into structure
+   if fread(fp,1,'uint32=>uint32') == 10 % NC_DIMENSION
+      for i = 1:fread(fp,1,'uint32=>uint32')
+         S(i).Str = String(fp);
+         S(i).Dim = fread(fp,1,'uint32=>uint32');
+      end
+   else fread(fp,1,'uint32=>uint32'); S = []; end
+
+function S = AttArray(fp)
+% Read AttArray into structure
+   if fread(fp,1,'uint32=>uint32') == 12 % NC_ATTRIBUTE
+      for i = 1:fread(fp,1,'uint32=>uint32')
+         S(i).Str = String(fp);
+         ID       = fread(fp,1,'uint32=>uint32');
+         Num      = fread(fp,1,'uint32=>uint32');
+         S(i).Val = fread(fp,Pad(Num,ID),[Type(ID),'=>',Type(ID)]).';
+      end
+   else fread(fp,1,'uint32=>uint32'); S = []; end
+
+function S = VarArray(fp)
+% Read VarArray into structure
+   if fread(fp,1,'uint32=>uint32') == 11 % NC_VARIABLE
+      for i = 1:fread(fp,1,'uint32=>uint32')
+         S(i).Str      = String(fp);
+         Num           = double(fread(fp,1,'uint32=>uint32'));
+         S(i).DimID    = double(fread(fp,Num,'uint32=>uint32'));
+         S(i).AttArray = AttArray(fp);
+         S(i).Type     = fread(fp,1,'uint32=>uint32');
+         S(i).VSize    = fread(fp,1,'uint32=>uint32');
+         S(i).Begin    = fread(fp,1,'uint32=>uint32'); % Classic 32 bit format only
+      end
+   else fread(fp,1,'uint32=>uint32'); S = []; end
+end
Index: /issm/trunk/src/m/miscellaneous/parallelrange.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/parallelrange.m	(revision 13395)
+++ /issm/trunk/src/m/miscellaneous/parallelrange.m	(revision 13395)
@@ -0,0 +1,23 @@
+function [i1,i2]=parallelrange(rank,numprocs,globalsize)
+%PARALLELRANGE - from a rank, and a number of processors, figure out a range, for parallel tasks.
+%
+%   Usage: 
+%      [i1,i1]=parallelrange(rank,numprocs,globalsize)
+
+num_local_rows=zeros(numprocs,1);
+
+for i=1:numprocs,
+	%we use floor. we under distribute rows. The rows left  are then redistributed, therefore resulting in a more even distribution.
+	num_local_rows(i)=floor(globalsize/numprocs);
+end
+
+
+%There may be some rows left. Distribute evenly.
+row_rest=globalsize - numprocs*floor(globalsize/numprocs);
+
+for i=1:row_rest,
+	num_local_rows(i)=num_local_rows(i)+1;
+end
+
+i1=sum(num_local_rows(1:rank-1))+1;
+i2=i1+num_local_rows(rank)-1;
Index: /issm/trunk/src/m/miscellaneous/parallelrange.py
===================================================================
--- /issm/trunk/src/m/miscellaneous/parallelrange.py	(revision 13395)
+++ /issm/trunk/src/m/miscellaneous/parallelrange.py	(revision 13395)
@@ -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/trunk/src/m/miscellaneous/round_ice.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/round_ice.m	(revision 13395)
+++ /issm/trunk/src/m/miscellaneous/round_ice.m	(revision 13395)
@@ -0,0 +1,36 @@
+function new_x=round_ice(x,numnonzeros)
+%ROUND_ICE - rounds up x so that it has only numnonzeros non zero digits
+%
+%   numnonzeros must be an integer larger or equal to 1
+%
+%   Usage:
+%      new_x=round_ice(x,numnonzeros)
+
+%some checks
+if (nargin ~=2 | nargout>1),
+	error('round_ice usage: new_x=round_ice(x,numonzeros)');
+end
+if ~isnumeric(x)
+	error('round_ice error message: x must be a number and numzeros an integer');
+end
+if round(numnonzeros)~=numnonzeros
+	error('round_ice error message: numnonzeros must be an integer larger or equal to 1')
+end
+if any(numnonzeros<1)
+	error('round_ice error message: numnonzeros must be an integer larger or equal to 1')
+end
+if (length(numnonzeros)~=1 & size(numnonzeros)~=size(x))
+	error('round_ice error message: numnonzeros must be an integer larger or equal to 1 or a list of integers of length length(x)')
+end
+
+%figure out how long x is
+lengthx=ceil(log10(abs(x)));
+
+%if x contains 0, lengthx=-Inf
+lengthx(isinf(lengthx))=1;
+
+%get its sign
+si=sign(x);
+
+%rule out zeros
+new_x=si.*round(abs(x).*10.^(-lengthx+numnonzeros)).*10.^(lengthx-numnonzeros);
Index: /issm/trunk/src/m/miscellaneous/structtoobj.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/structtoobj.m	(revision 13395)
+++ /issm/trunk/src/m/miscellaneous/structtoobj.m	(revision 13395)
@@ -0,0 +1,16 @@
+function obj=structtoobj(obj,S),
+%Convert struct to object
+
+	%Get object and structure fields
+	structfields=fields(S);
+	objprops    =properties(class(obj));
+
+	%recover object properties
+	for i=1:length(structfields),
+		fieldname =structfields{i};
+		if ismember(fieldname,objprops),
+			fieldvalue=getfield(S,fieldname);
+			obj=setfield(obj,fieldname,fieldvalue);
+		end
+	end
+end
Index: /issm/trunk/src/m/os/flaimdir.m
===================================================================
--- /issm/trunk/src/m/os/flaimdir.m	(revision 13395)
+++ /issm/trunk/src/m/os/flaimdir.m	(revision 13395)
@@ -0,0 +1,7 @@
+function FLAIM_DIR=flaimdir()
+%ISSMDIR - Get FLAIM installation directory
+%
+%   Usage:
+%      FLAIM_DIR=flaimdir()
+
+FLAIM_DIR=[issmdir() '/externalpackages/flaim/install'];
Index: /issm/trunk/src/m/os/ismpi.m
===================================================================
--- /issm/trunk/src/m/os/ismpi.m	(revision 13395)
+++ /issm/trunk/src/m/os/ismpi.m	(revision 13395)
@@ -0,0 +1,33 @@
+function flag=ismpi()
+%ISMPI - figure out if MPI package was compiled with ISSM
+%
+%   Usage:
+%       flag=ismpi();
+
+
+configfile=[issmdir() '/bin/config.h']; %should find it in the install target
+if ~exist(configfile,'file'),
+	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
+end
+
+%go through the file, and recover the line we want
+flag=2;
+fid=fopen(configfile,'r');
+if(fid==-1), error(['could not open file: ' configfile]); end
+
+while(true),
+	tline=fgets(fid);
+	if ~ischar(tline), break, end
+	if strncmp(tline,'/* #undef _HAVE_MPI_ */',23),
+		flag=0;
+		break;
+	end
+	if  strncmp(tline,'#define _HAVE_MPI_',18),
+		flag=1;
+		break;
+	end
+end
+fclose(fid);
+if flag==2,
+	error('could not determine whether MPI was or was not compiled');
+end
Index: /issm/trunk/src/m/os/ismpi.py
===================================================================
--- /issm/trunk/src/m/os/ismpi.py	(revision 13395)
+++ /issm/trunk/src/m/os/ismpi.py	(revision 13395)
@@ -0,0 +1,37 @@
+import os
+from issmdir import *
+from MatlabFuncs import *
+
+def ismpi():
+	"""
+	ISMPI - figure out if MPI package was compiled with ISSM
+ 
+	   Usage:
+	      flag=ismpi();
+	"""
+
+	configfile=os.path.join(issmdir(),'bin','config.h')    #should find it in the install target
+	if not os.path.exists(configfile):
+		raise RuntimeError("File '%s' not found. ISSM has not been configured yet!" % configfile)
+
+	#go through the file, and recover the line we want
+	flag=2
+	try:
+		fid=open(configfile,'r')
+	except IOError as e:
+		raise IOError("could not open file: '%s'" % configfile)
+
+	for tline in fid:
+		if strncmp(tline,'/* #undef _HAVE_MPI_ */',23):
+			flag=0
+			break
+		if  strncmp(tline,'#define _HAVE_MPI_',18):
+			flag=1
+			break
+
+	fid.close()
+	if flag==2:
+		raise RuntimeError("could not determine whether MPI was or was not compiled.")
+
+	return flag
+
Index: /issm/trunk/src/m/os/ismumps.m
===================================================================
--- /issm/trunk/src/m/os/ismumps.m	(revision 13395)
+++ /issm/trunk/src/m/os/ismumps.m	(revision 13395)
@@ -0,0 +1,33 @@
+function flag=ismumps()
+%ISMUMPS - figure out if MUMPS package was compiled with ISSM
+%
+%   Usage:
+%       flag=ismumps();
+
+
+configfile=[issmdir() '/bin/config.h']; %should find it in the install target
+if ~exist(configfile,'file'),
+	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
+end
+
+%go through the file, and recover the line we want
+flag=2;
+fid=fopen(configfile,'r');
+if(fid==-1), error(['could not open file: ' configfile]); end
+
+while(true),
+	tline=fgets(fid);
+	if ~ischar(tline), break, end
+	if strncmp(tline,'/* #undef _HAVE_MUMPS_ */',25),
+		flag=0;
+		break;
+	end
+	if  strncmp(tline,'#define _HAVE_MUMPS_',20),
+		flag=1;
+		break;
+	end
+end
+fclose(fid);
+if flag==2,
+	error('could not determine whether MUMPS was or was not compiled');
+end
Index: /issm/trunk/src/m/os/ismumps.py
===================================================================
--- /issm/trunk/src/m/os/ismumps.py	(revision 13395)
+++ /issm/trunk/src/m/os/ismumps.py	(revision 13395)
@@ -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/trunk/src/m/os/ispetsc.m
===================================================================
--- /issm/trunk/src/m/os/ispetsc.m	(revision 13395)
+++ /issm/trunk/src/m/os/ispetsc.m	(revision 13395)
@@ -0,0 +1,33 @@
+function flag=ispetsc()
+%ISPETSC - figure out if PETSC package was compiled with ISSM
+%
+%   Usage:
+%       flag=ispetsc();
+
+
+configfile=[issmdir() '/bin/config.h']; %should find it in the install target
+if ~exist(configfile,'file'),
+	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
+end
+
+%go through the file, and recover the line we want
+flag=2;
+fid=fopen(configfile,'r');
+if(fid==-1), error(['could not open file: ' configfile]); end
+
+while(true),
+	tline=fgets(fid);
+	if ~ischar(tline), break, end
+	if strncmp(tline,'/* #undef _HAVE_PETSC_ */',25),
+		flag=0;
+		break;
+	end
+	if  strncmp(tline,'#define _HAVE_PETSC_',20),
+		flag=1;
+		break;
+	end
+end
+fclose(fid);
+if flag==2,
+	error('could not determine whether PETSC was or was not compiled');
+end
Index: /issm/trunk/src/m/os/ispetsc.py
===================================================================
--- /issm/trunk/src/m/os/ispetsc.py	(revision 13395)
+++ /issm/trunk/src/m/os/ispetsc.py	(revision 13395)
@@ -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/trunk/src/m/os/issmbbftpin.m
===================================================================
--- /issm/trunk/src/m/os/issmbbftpin.m	(revision 13395)
+++ /issm/trunk/src/m/os/issmbbftpin.m	(revision 13395)
@@ -0,0 +1,48 @@
+function issmbbftpin(host, login,port,numstreams,path, packages)
+%BBFTPIN get packages from host, using bbftp. assuming unix system here.
+%
+%   usage: scpin(host,packages,path)
+%
+%
+
+%first get hostname
+hostname=oshostname();
+
+%first be sure packages are not in the current directory, this could conflict with pscp on windows. 
+%get initial warning mode
+state=warning('query', 'all');
+%remove warnings in case the files do not exist
+warning off
+for i=1:numel(packages),
+	delete(packages{i});
+end
+%back to initial warning state
+warning(state);
+
+%if hostname and host are the same, do a simple copy
+if strcmpi(hostname,host),
+
+    for i=1:numel(packages),
+		success=copyfile([path '/' packages{i}]); %keep going, even if success=0
+	end
+
+else
+
+	%build a string of the type: bbftp -s -u elarour -e 'setnbstream 8; cd /nobackupp10/elarour/Testing/Interactive3/; get Antarctica.outbin' pfe1.nas.nasa.gov
+	command=['!bbftp -s -V -u ' login ' -e ''setnbstream 8; cd ' path '; '];
+	for i=1:length(packages),
+		command=[command 'get ' packages{i} ';'];
+	end
+	command=[command '''  pfe1.nas.nasa.gov'];
+	
+	eval(command);
+
+	%check bbftp worked
+	for i=1:numel(packages),
+		if ~exist(['./' packages{i}]),
+			error('scpin error message: could not call scp on *nix system');
+		end
+	end
+
+
+end
Index: /issm/trunk/src/m/os/issmbbftpout.m
===================================================================
--- /issm/trunk/src/m/os/issmbbftpout.m	(revision 13395)
+++ /issm/trunk/src/m/os/issmbbftpout.m	(revision 13395)
@@ -0,0 +1,30 @@
+function issmbbftpout(host,path,login,port,numstreams,packages)
+%BBFTPOUT put packages onto host, using bbftp. assuming unix system here.
+%
+%   usage: bbftpout(host,path,login,port,numstream,packages)
+%
+%
+
+%get hostname
+hostname=oshostname();
+
+%if hostname and host are the same, do a simple copy
+if strcmpi(host,hostname),
+	for i=1:numel(packages),
+		here=pwd;
+		eval(['cd ' path])
+		system(['rm -rf ' packages{i} ]);
+		system(['ln -s ' here '/' packages{i} ' .']);
+		eval(['cd ' here]);
+	end
+else 
+	
+	%build a string of the type: bbftp -s -u elarour -e 'setnbstream 8; cd /nobackupp10/elarour/Testing/Interactive3/; put Antarctica.tar.gz' pfe1.nas.nasa.gov
+	command=['!bbftp -s -V -u ' login ' -e ''setnbstream 8; cd ' path '; ']
+	for i=1:length(packages),
+		command=[command 'put ' packages{i} ';'];
+	end
+	command=[command '''  pfe1.nas.nasa.gov'];
+	
+	eval(command);
+end
Index: /issm/trunk/src/m/os/issmdir.m
===================================================================
--- /issm/trunk/src/m/os/issmdir.m	(revision 13395)
+++ /issm/trunk/src/m/os/issmdir.m	(revision 13395)
@@ -0,0 +1,18 @@
+function ISSM_DIR=issmdir()
+%ISSMDIR - Get ISSM_DIR environment variable
+%
+%   Usage:
+%      ISSM_DIR=issmdir()
+
+if ~ispc(),
+	ISSM_DIR =getenv('ISSM_DIR');
+else
+	ISSM_DIR =getenv('ISSM_DIR_WIN');
+	if strcmpi(ISSM_DIR(end),'/') | strcmpi(ISSM_DIR(end),'\'),
+		ISSM_DIR = ISSM_DIR(1:end-1); %shave off the last '/'
+	end
+end
+
+if (isempty(ISSM_DIR)),
+	error('issmdir error message: ''ISSM_DIR'' environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!');
+end
Index: /issm/trunk/src/m/os/issmdir.py
===================================================================
--- /issm/trunk/src/m/os/issmdir.py	(revision 13395)
+++ /issm/trunk/src/m/os/issmdir.py	(revision 13395)
@@ -0,0 +1,23 @@
+import os
+from MatlabFuncs import *
+
+def issmdir():
+	"""
+	ISSMDIR - Get ISSM_DIR environment variable
+ 
+	   Usage:
+	      ISSM_DIR=issmdir()
+	"""
+
+	if not ispc():
+		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/trunk/src/m/os/issmscpin.m
===================================================================
--- /issm/trunk/src/m/os/issmscpin.m	(revision 13395)
+++ /issm/trunk/src/m/os/issmscpin.m	(revision 13395)
@@ -0,0 +1,78 @@
+function issmscpin(host, login,port,path, packages)
+%ISSMSCPIN get packages from host, using scp on unix, and pscp on windows
+%
+%   usage: issmscpin(host,packages,path)
+%
+%
+
+%first get hostname
+hostname=oshostname();
+
+%first be sure packages are not in the current directory, this could conflict with pscp on windows. 
+%get initial warning mode
+state=warning('query', 'all');
+%remove warnings in case the files do not exist
+warning off
+for i=1:numel(packages),
+	delete(packages{i});
+end
+%back to initial warning state
+warning(state);
+
+%if hostname and host are the same, do a simple copy
+if strcmpi(hostname,host),
+
+    for i=1:numel(packages),
+		success=copyfile([path '/' packages{i}]); %keep going, even if success=0
+	end
+
+else
+
+	if ispc(),
+		%use the putty project pscp.exe: it should be in the path.
+		
+		%get ISSM_DIR variable
+		[status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
+		if status, 
+			error('issmscpin error message: could not find ISSM_DIR_WIN environment variable');
+		end
+		ISSM_DIR=ISSM_DIR(2:end-2);
+
+		username=input('Username: (quoted string) ');
+		key=input('Key: (quoted string) ');
+
+		for i=1:numel(packages),
+			[status,result]=system([ISSM_DIR '/externalpackages/ssh/pscp.exe -l "' username '" -pw "' key '" ' host ':' path '/' packages{i} ' ./']);
+			if status, 
+				error('issmscpin error message: could not call putty pscp');
+			end
+		end
+
+	else
+		%just use standard unix scp
+		%string to copy multiple files using scp: 
+		if numel(packages)==1,
+			string=packages{1};
+		else
+			string='\{';
+			for i=1:numel(packages)-1,
+				string=[string packages{i} ','];
+			end
+			string=[string packages{end} '\}'];
+		end
+
+
+		if port,
+			eval(['!scp -P ' num2str(port) ' ' login '@localhost:' path '/' string ' ./']);
+		else
+			eval(['!scp ' login '@' host ':' path '/' string ' ./']);
+		end
+		
+		%check scp worked
+		for i=1:numel(packages),
+			if ~exist(['./' packages{i}]),
+				error('issmscpin error message: could not call scp on *nix system');
+			end
+		end
+	end
+end
Index: /issm/trunk/src/m/os/issmscpin.py
===================================================================
--- /issm/trunk/src/m/os/issmscpin.py	(revision 13395)
+++ /issm/trunk/src/m/os/issmscpin.py	(revision 13395)
@@ -0,0 +1,74 @@
+import socket
+import subprocess
+import os
+import shutil
+from MatlabFuncs import *
+
+def issmscpin(host, login,port,path, packages):
+	"""
+	ISSMSCPIN get packages from host, using scp on unix, and pscp on windows
+ 
+	   usage: issmscpin(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 ispc():
+			#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("issmscpin 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("issmscpin 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("issmscpin error message: could not call scp on *nix system.")
+
Index: /issm/trunk/src/m/os/issmscpout.m
===================================================================
--- /issm/trunk/src/m/os/issmscpout.m	(revision 13395)
+++ /issm/trunk/src/m/os/issmscpout.m	(revision 13395)
@@ -0,0 +1,57 @@
+function issmscpout(host,path,login,port,packages)
+%ISSMSCPOUT send packages to a host, using scp on unix, and pscp on windows
+%
+%   usage: issmscpout(host,path,packages)
+%
+%
+
+%get hostname
+hostname=oshostname();
+
+%if hostname and host are the same, do a simple copy
+
+if strcmpi(host,hostname),
+	for i=1:numel(packages),
+		here=pwd;
+		eval(['cd ' path])
+		system(['rm -rf ' packages{i} ]);
+		system(['ln -s ' here '/' packages{i} ' .']);
+		eval(['cd ' here]);
+	end
+else 
+	if ispc(),
+		%use the putty project pscp.exe: it should be in the path.
+		
+		%get ISSM_DIR variable
+		[status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
+		if status, 
+			error('issmscpout error message: could not find ISSM_DIR_WIN environment variable');
+		end
+		ISSM_DIR=ISSM_DIR(2:end-2);
+
+		username=input('Username: (quoted string) ');
+		key=input('Key: (quoted string) ');
+
+		for i=1:numel(packages),
+			[status,result]=system([ISSM_DIR '/externalpackages/ssh/pscp.exe -l "' username '" -pw "' key '" ' packages{i} ' ' host ':' path]);
+			if status, 
+				error('issmscpout error message: could not call putty pscp');
+			end
+		end
+
+	else
+		%just use standard unix scp
+		%create string of packages being sent
+		string='';
+		for i=1:numel(packages),
+			string=[string ' ' packages{i}];
+		end
+		string=[string ' '];
+		
+		if port,
+			eval(['!scp -P ' num2str(port) ' ' string ' ' login '@localhost:' path]);
+		else
+			eval(['!scp ' string ' ' login '@' host ':' path]);
+		end
+	end
+end
Index: /issm/trunk/src/m/os/issmscpout.py
===================================================================
--- /issm/trunk/src/m/os/issmscpout.py	(revision 13395)
+++ /issm/trunk/src/m/os/issmscpout.py	(revision 13395)
@@ -0,0 +1,59 @@
+import socket
+import subprocess
+import os
+from MatlabFuncs import *
+
+def issmscpout(host,path,login,port,packages):
+	"""
+	ISSMSCPOUT send packages to a host, using scp on unix, and pscp on windows
+ 
+	   usage: issmscpout(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)
+			try:
+				os.remove(package)
+			except OSError as e:
+				pass
+			subprocess.call('ln -s %s %s' % (os.path.join(here,package),path),shell=True)
+			os.chdir(here)
+	else:
+		if ispc():
+			#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("issmscpout 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("issmscpout 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/trunk/src/m/os/issmssh.m
===================================================================
--- /issm/trunk/src/m/os/issmssh.m	(revision 13395)
+++ /issm/trunk/src/m/os/issmssh.m	(revision 13395)
@@ -0,0 +1,37 @@
+function issmssh(host,login,port,command)
+%ISSMSSH - wrapper for OS independent ssh command.
+%
+%   usage: 
+%      issmssh(host,command)
+
+%first get hostname 
+hostname=oshostname();
+
+%if same as host, just run the command. 
+if strcmpi(host,hostname),
+	system(command);
+else
+	if ispc(),
+		%use the putty project plink.exe: it should be in the path.
+		
+		%get ISSM_DIR variable
+		[status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
+		if status, 
+			error('issmssh error message: could not find ISSM_DIR_WIN environment variable');
+		end
+		ISSM_DIR=ISSM_DIR(2:end-2);
+
+		username=input('Username: (quoted string) ');
+		key=input('Key: (quoted string) ');
+
+		system([ISSM_DIR '/externalpackages/ssh/plink.exe -ssh -l "' username '" -pw "' key '" ' host ' "' command '"']);
+
+	else
+		%just use standard unix ssh
+		if port,
+			eval(['!ssh -l ' login ' -p ' num2str(port) ' localhost "' command '"']);
+		else
+			eval(['!ssh -l ' login ' ' host ' "' command '"']);
+		end
+	end
+end
Index: /issm/trunk/src/m/os/issmssh.py
===================================================================
--- /issm/trunk/src/m/os/issmssh.py	(revision 13395)
+++ /issm/trunk/src/m/os/issmssh.py	(revision 13395)
@@ -0,0 +1,41 @@
+import socket
+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 ispc():
+			#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/trunk/src/m/os/jplsvn.m
===================================================================
--- /issm/trunk/src/m/os/jplsvn.m	(revision 13395)
+++ /issm/trunk/src/m/os/jplsvn.m	(revision 13395)
@@ -0,0 +1,15 @@
+function JPL_SVN=jplsvn()
+%ISSMDIR - Get JPL_SVN environment variable
+%
+%   Usage:
+%      JPL_SVN=jplsvn()
+
+if ~ispc(),
+	JPL_SVN =getenv('JPL_SVN');
+else
+	JPL_SVN =getenv('JPL_SVN_WIN');
+end
+
+if (isempty(JPL_SVN)),
+	error('jplsvn error message: ''JPL_SVN'' environment variable is empty! You should define JPL_SVN in your .cshrc or .bashrc');
+end
Index: /issm/trunk/src/m/os/listfiles.m
===================================================================
--- /issm/trunk/src/m/os/listfiles.m	(revision 13395)
+++ /issm/trunk/src/m/os/listfiles.m	(revision 13395)
@@ -0,0 +1,22 @@
+function list=listfiles()
+%LISTFILES list files inside a directory
+%        this is very OS dependent.
+%
+%   usage: list=listfiles;
+%
+%
+%   see also LS DIR
+
+%use dir, as it seems to act OS independent
+
+first_list=dir;
+list={};
+
+for i=1:numel(first_list),
+	if (  ~strcmpi(first_list(i).name,'.') &...
+			~strcmpi(first_list(i).name,'..') &...
+			~strcmpi(first_list(i).name,'NightlyRun') &...
+			~strcmpi(first_list(i).name,'.svn')),
+		list{end+1}=first_list(i).name;
+	end
+end
Index: /issm/trunk/src/m/os/listfilesparallel.m
===================================================================
--- /issm/trunk/src/m/os/listfilesparallel.m	(revision 13395)
+++ /issm/trunk/src/m/os/listfilesparallel.m	(revision 13395)
@@ -0,0 +1,15 @@
+function list=listfilesparallel(rank,numprocs)
+%LISTFILESPARALLEL list files inside a directory, depending on rank  and number of processors running this routine.
+%        this is very OS dependent.
+%
+%   usage: list=listfilesparallel(rank,numprocs);
+%
+%
+%   see also LS DIR LISTFILES
+
+list=listfiles';
+numfiles=numel(list);
+
+%we now have a list, split it between all the processors.
+[i1,i2]=parallelrange(rank,numprocs,numfiles);
+list=list(i1:i2);
Index: /issm/trunk/src/m/os/oshostname.m
===================================================================
--- /issm/trunk/src/m/os/oshostname.m	(revision 13395)
+++ /issm/trunk/src/m/os/oshostname.m	(revision 13395)
@@ -0,0 +1,22 @@
+function hostname=oshostname()
+%OSHOSTNAME figure out hostname, irrespective of os type
+%
+%   usage: hostname=oshostname();
+%
+%
+
+if ispc(),
+	[status,hostname]=system('hostname | sed ''s/-//g''');hostname=hostname(1:end-1);
+
+	if status, 
+		error('oshostname error message: could not run hostname command on windows os');
+	end
+
+else
+	[status,hostname]=system(['hostname -s | sed ''s/-//g''']);
+	if status, 
+		error('oshostname error message: could not run hostname command on *nix os');
+	end
+	hostname=hostname(1:end-1);
+	hostname=ddewhite(hostname);
+end
Index: /issm/trunk/src/m/os/petscversion.m
===================================================================
--- /issm/trunk/src/m/os/petscversion.m	(revision 13395)
+++ /issm/trunk/src/m/os/petscversion.m	(revision 13395)
@@ -0,0 +1,26 @@
+function PETSC_VERSION=petscversion()
+%PETSCVERSION - recover petsc version number, inside config.h file
+%
+%   Usage:
+%       PETSC_VERSION=petscversion();
+
+%default
+PETSC_VERSION=3;
+
+configfile=[issmdir() '/config.h'];
+if ~exist(configfile,'file'),
+	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
+end
+
+%go through the file, and recover the line we want
+fid=fopen(configfile,'r');
+if(fid==-1), error(['could not open file: ' configfile]); end
+
+while(true),
+	tline=fgets(fid);
+	if ~ischar(tline), break, end
+	if  strncmp(tline,'#define _PETSC_MAJOR_',21),
+		PETSC_VERSION=str2num(tline(23));
+	end
+end
+fclose(fid);
Index: /issm/trunk/src/m/os/petscversion.py
===================================================================
--- /issm/trunk/src/m/os/petscversion.py	(revision 13395)
+++ /issm/trunk/src/m/os/petscversion.py	(revision 13395)
@@ -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/trunk/src/m/os/recursivepath.m
===================================================================
--- /issm/trunk/src/m/os/recursivepath.m	(revision 13395)
+++ /issm/trunk/src/m/os/recursivepath.m	(revision 13395)
@@ -0,0 +1,39 @@
+function p = recursivepath(d)
+%RECURSIVEPATH - generate paths in a directory
+%
+%   this routine is equivalent to Matlab's genpath except that it skips CVS and
+%   .svn directories
+%
+%   Usage:
+%      p = recursivepath(d)
+
+%initialize path to be returned
+p = '';
+sep=pathsep;  %directory separator
+
+% Generate path based on given root directory
+files=dir(d);
+if isempty(files)
+	return
+end
+
+% Add d to the path even if it is empty.
+p = [p d sep];
+
+% set logical vector for subdirectory entries in d
+isdir = logical(cat(1,files.isdir));
+
+% Recursively goes through the subdirectories of d
+dirs=files(isdir); % select only directory entries from the current listing
+for i=1:length(dirs)
+	dirname=dirs(i).name;
+	if ~strcmp(dirname,'.')    & ...
+		~strcmp(dirname,'..')   & ...
+		~strcmp(dirname,'.svn') & ...
+		~strcmp(dirname,'CVS')  & ...
+		~strncmp(dirname,'@',1) & ... %Method directories not allowed in MATLAB path
+		~strcmp(dirname,'private')    %private directories not allowed in MATLAB path
+
+		p = [p recursivepath(fullfile(d,dirname))];
+	end
+end
Index: /issm/trunk/src/m/parameterization/contourenvelope.m
===================================================================
--- /issm/trunk/src/m/parameterization/contourenvelope.m	(revision 13395)
+++ /issm/trunk/src/m/parameterization/contourenvelope.m	(revision 13395)
@@ -0,0 +1,139 @@
+function segments=contourenvelope(md,varargin)
+%CONTOURENVELOPE - build a set of segments enveloping a contour .exp
+%
+%   Usage:
+%      segments=contourenvelope(md,varargin)
+%
+%   Example:
+%      segments=contourenvelope(md,'Stream.exp');
+%      segments=contourenvelope(md,md.mask.elementonfloatingice)
+%      segments=contourenvelope(md);
+
+%some checks
+if nargin>2,
+	help contourenvelope
+	error('contourenvelope error message: bad usage');
+end
+if nargin==2,
+	flags=varargin{1};
+
+	if ischar(flags),
+		file=flags;
+		file=varargin{1};
+		if ~exist(file),
+			error(['contourenvelope error message: file ' file ' not found']);
+		end
+		isfile=1;
+	elseif isnumeric(flags),
+		%do nothing for now
+		isfile=0;
+	else
+		error('contourenvelope error message:  second argument should a file or an elements flag');
+	end
+end
+
+%Now, build the connectivity tables for this mesh.
+%Computing connectivity
+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 & size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements2d),
+	md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+end
+
+%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(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);
+		mesh.elementconnectivity(elemout,:)=0;
+		mesh.elementconnectivity(find(ismember(mesh.elementconnectivity,elemout)))=0;
+	else
+		%get flag list of elements and nodes inside the contour
+		nodein=zeros(mesh.numberofvertices,1); 
+		elemin=zeros(mesh.numberofelements,1); 
+		
+		pos=find(flags); 
+		elemin(pos)=1;
+		nodein(mesh.elements(pos,:))=1;
+
+		%modify element connectivity
+		elemout=find(~elemin);
+		mesh.elementconnectivity(elemout,:)=0;
+		mesh.elementconnectivity(find(ismember(mesh.elementconnectivity,elemout)))=0;
+	end
+end
+
+%Find element on boundary
+%First: find elements on the boundary of the domain
+flag=mesh.elementconnectivity;
+if nargin==2,
+	flag(find(flag))=elemin(flag(find(flag)));
+end
+elementonboundary=double(prod(flag,2)==0 & sum(flag,2)>0);
+
+%Find segments on boundary
+pos=find(elementonboundary);
+num_segments=length(pos);
+segments=zeros(num_segments,3);
+count=1;
+
+for i=1:num_segments,
+	el1=pos(i);
+	els2=mesh.elementconnectivity(el1,find(mesh.elementconnectivity(el1,:)));
+	if length(els2)>1,
+		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)==mesh.elements(el1,:));
+		ord2=find(nods1(2)==mesh.elements(el1,:));
+
+		%swap segment nodes if necessary
+		if ( (ord1==1 & ord2==2) | (ord1==2 & ord2==3) | (ord1==3 & ord2==1) ),
+			temp=segments(count,1);
+			segments(count,1)=segments(count,2);
+			segments(count,2)=temp;
+		end
+		segments(count,1:2)=fliplr(segments(count,1:2));
+		count=count+1;
+	else
+		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)==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);
+					segments(count,1)=segments(count,2);
+					segments(count,2)=temp;
+				end
+				segments(count,1:2)=fliplr(segments(count,1:2));
+				count=count+1;
+			end
+		end
+	end
+end
Index: /issm/trunk/src/m/parameterization/parameterize.m
===================================================================
--- /issm/trunk/src/m/parameterization/parameterize.m	(revision 13395)
+++ /issm/trunk/src/m/parameterization/parameterize.m	(revision 13395)
@@ -0,0 +1,58 @@
+function md=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.m and mask.m @model methods.
+%   Warning: the parameter file must be able to be run in Matlab
+%
+%   Usage:
+%      md=parameterize(md,parametername)
+%
+%   Example:
+%      md=parameterize(md,'Square.par');
+
+%some checks
+if ~exist(parametername),
+	error(['parameterize error message: file ' parametername ' not found!']);
+end
+
+%Try and run parameter file.
+temporaryname=['TemporaryParameterFile' num2str(feature('GetPid')) ];
+copyfile(parametername,[temporaryname '.m']);
+
+%WARNING: this is a bug of matlab: the TemporaryParameterFile must be cleared
+%otherwise matlab keeps the previous version of this file which is not what
+%we want!!!
+eval(['clear ' temporaryname]);
+
+try,
+	eval(temporaryname);
+	delete([temporaryname '.m']);
+catch me,
+	delete([temporaryname '.m']);
+
+	%copy error message
+	me2=struct('message',me.message,'stack',me.stack);
+
+	%rename parameter file
+	me2.message=regexprep(me2.message,[temporaryname '.m'],parametername);
+	for i=1:length(me2.stack)-1,
+		me2.stack(i).file=regexprep(me2.stack(i).file,[temporaryname '.m'],parametername);
+		me2.stack(i).name=regexprep(me2.stack(i).name,[temporaryname],parametername);
+		if strcmp(me2.stack(i).name,'parameterize'),
+			%remove error (eval(temporaryname);) misleading
+			me2.stack(i)=[];
+		end
+	end
+
+	%throw error message
+	rethrow(me2);
+end
+
+%Name and notes
+if isempty(md.miscellaneous.name), 
+	[path,root,ext]=fileparts(parametername);
+	md.miscellaneous.name=root; 
+end
+md.miscellaneous.notes=['Model created by using parameter file: ' parametername ' on: ' datestr(now)];
+
Index: /issm/trunk/src/m/parameterization/parameterize.py
===================================================================
--- /issm/trunk/src/m/parameterization/parameterize.py	(revision 13395)
+++ /issm/trunk/src/m/parameterization/parameterize.py	(revision 13395)
@@ -0,0 +1,33 @@
+import os
+import datetime
+
+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.exists(parametername):
+		raise IOError("parameterize error message: file '%s' not found!" % parametername)
+
+	#Try and run parameter file.
+	execfile(parametername)
+
+	#Name and notes
+	if not md.miscellaneous.name:
+		md.miscellaneous.name=os.path.basename(parametername).split('.')[0]
+
+	md.miscellaneous.notes="Model created by using parameter file: '%s' on: %s." % (parametername,datetime.datetime.strftime(datetime.datetime.now(),'%c'))
+
+	return md
+
Index: /issm/trunk/src/m/parameterization/setflowequation.m
===================================================================
--- /issm/trunk/src/m/parameterization/setflowequation.m	(revision 13395)
+++ /issm/trunk/src/m/parameterization/setflowequation.m	(revision 13395)
@@ -0,0 +1,300 @@
+function md=setflowequation(md,varargin)
+%SETELEMENTSTYPE - associate a solution type to each element
+%
+%   This routine works like plotmodel: it works with an even number of inputs
+%   'hutter','macayeal','l1l2','pattyn','stokes' and 'fill' are the possible options
+%   that must be followed by the corresponding exp file or flags list
+%   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
+%   If user wants every element outside the domain to be 
+%   setflowequationd, add '~' to the name of the domain file (ex: '~Pattyn.exp');
+%   an empty string '' will be considered as an empty domain
+%   a string 'all' will be considered as the entire domain
+%   You can specify the type of coupling, 'penalties' or 'tiling', to use with the input 'coupling'
+%   NB: l1l2 cannot currently be coupled to any other ice flow model
+%
+%   Usage:
+%      md=setflowequation(md,varargin)
+%
+%   Example:
+%      md=setflowequation(md,'pattyn','Pattyn.exp','macayeal',md.mask.elementonfloatingice,'fill','hutter');
+%      md=setflowequation(md,'pattyn','Pattyn.exp',fill','hutter','coupling','tiling');
+
+%some checks on list of arguments
+if ((nargin<2) | (nargout~=1)),
+	error('setflowequation error message');
+end
+
+%Process options
+options=pairoptions(varargin{:});
+options=deleteduplicates(options,1);
+
+%Find_out what kind of coupling to use
+coupling_method=getfieldvalue(options,'coupling','tiling');
+if (~strcmpi(coupling_method,'tiling') & ~strcmpi(coupling_method,'penalties')),
+	error('coupling type can only be: tiling or penalties');
+end
+
+%recover elements distribution
+hutterflag   = FlagElements(md,getfieldvalue(options,'hutter',''));
+macayealflag = FlagElements(md,getfieldvalue(options,'macayeal',''));
+pattynflag   = FlagElements(md,getfieldvalue(options,'pattyn',''));
+l1l2flag     = FlagElements(md,getfieldvalue(options,'l1l2',''));
+stokesflag   = FlagElements(md,getfieldvalue(options,'stokes',''));
+filltype     = getfieldvalue(options,'fill','none');
+
+%Flag the elements that have not been flagged as filltype
+if strcmpi(filltype,'hutter'),
+	hutterflag(find(~(macayealflag | pattynflag)))=1;
+elseif strcmpi(filltype,'macayeal'),
+	macayealflag(find(~(hutterflag | pattynflag | stokesflag)))=1;
+elseif strcmpi(filltype,'pattyn'),
+	pattynflag(find(~(hutterflag | macayealflag | stokesflag)))=1;
+end
+
+%check that each element has at least one flag
+if any(hutterflag+macayealflag+pattynflag+l1l2flag+stokesflag==0),
+	error('elements type not assigned, must be specified')
+end
+
+%check that each element has only one flag
+if any(hutterflag+macayealflag+pattynflag+l1l2flag+stokesflag>1),
+	disp('setflowequation warning message: some elements have several types, higher order type is used for them')
+	hutterflag(find(hutterflag & macayealflag))=0;
+	hutterflag(find(hutterflag & pattynflag))=0;
+	macayealflag(find(macayealflag & pattynflag))=0;
+end
+
+%check that l1l2 is not coupled to any other model for now
+if any(l1l2flag) & any(hutterflag | macayealflag | pattynflag | stokesflag)
+	error('l1l2 cannot be coupled to any other model');
+end
+
+%Check that no l1l2 or pattyn or stokes for 2d mesh
+if (md.mesh.dimension==2),
+	if any(l1l2flag | stokesflag | pattynflag)
+		error('stokes and pattyn elements not allowed in 2d mesh, extrude it first')
+	end
+end
+
+%Stokes can only be used alone for now:
+if any(stokesflag) &any(hutterflag),
+	error('stokes cannot be used with any other model for now, put stokes everywhere')
+end
+
+%Initialize node fields
+nodeonhutter=zeros(md.mesh.numberofvertices,1);
+nodeonhutter(md.mesh.elements(find(hutterflag),:))=1;
+nodeonmacayeal=zeros(md.mesh.numberofvertices,1);
+nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+nodeonpattyn=zeros(md.mesh.numberofvertices,1);
+nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
+nodeonl1l2=zeros(md.mesh.numberofvertices,1);
+nodeonl1l2(md.mesh.elements(find(l1l2flag),:))=1;
+nodeonstokes=zeros(md.mesh.numberofvertices,1);
+noneflag=zeros(md.mesh.numberofelements,1);
+
+%First modify stokesflag to get rid of elements contrained everywhere (spc + border with pattyn or macayeal)
+if any(stokesflag),
+	fullspcnodes=double((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy)+~isnan(md.diagnostic.spcvz))==3 | (nodeonpattyn & nodeonstokes));         %find all the nodes on the boundary of the domain without icefront
+	fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
+	stokesflag(find(fullspcelems))=0;
+	nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+end
+
+%Then complete with NoneApproximation or the other model used if there is no stokes
+if any(stokesflag), 
+	if any(pattynflag), %fill with pattyn
+		pattynflag(~stokesflag)=1;
+		nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
+	elseif any(macayealflag), %fill with macayeal
+		macayealflag(~stokesflag)=1;
+		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+	else %fill with none 
+		noneflag(find(~stokesflag))=1;
+	end
+end
+
+%Now take care of the coupling between MacAyeal and Pattyn
+md.diagnostic.vertex_pairing=[];
+nodeonmacayealpattyn=zeros(md.mesh.numberofvertices,1);
+nodeonpattynstokes=zeros(md.mesh.numberofvertices,1);
+nodeonmacayealstokes=zeros(md.mesh.numberofvertices,1);
+macayealpattynflag=zeros(md.mesh.numberofelements,1);
+macayealstokesflag=zeros(md.mesh.numberofelements,1);
+pattynstokesflag=zeros(md.mesh.numberofelements,1);
+if strcmpi(coupling_method,'penalties'),
+	%Create the border nodes between Pattyn and MacAyeal and extrude them
+	numnodes2d=md.mesh.numberofvertices2d;
+	numlayers=md.mesh.numberoflayers;
+	bordernodes2d=find(nodeonpattyn(1:numnodes2d) & nodeonmacayeal(1:numnodes2d)); %Nodes connected to two different types of elements
+
+	%initialize and fill in penalties structure
+	if ~isnan(bordernodes2d),
+		penalties=[];
+		for	i=1:numlayers-1,
+			penalties=[penalties; [bordernodes2d bordernodes2d+md.mesh.numberofvertices2d*(i)]];
+		end
+		md.diagnostic.vertex_pairing=penalties;
+	end
+elseif strcmpi(coupling_method,'tiling'),
+	if any(macayealflag) & any(pattynflag), %coupling macayeal pattyn
+		%Find node at the border
+		nodeonmacayealpattyn(find(nodeonmacayeal & nodeonpattyn))=1;
+		%Macayeal elements in contact with this layer become MacAyealPattyn elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonmacayealpattyn));
+		commonelements=sum(matrixelements,2)~=0;
+		commonelements(find(pattynflag))=0; %only one layer: the elements previously in macayeal
+		macayealflag(find(commonelements))=0; %these elements are now macayealpattynelements
+		macayealpattynflag(find(commonelements))=1;
+		nodeonmacayeal(:)=0;
+		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+
+		%rule out elements that don't touch the 2 boundaries
+		pos=find(macayealpattynflag);
+		elist=zeros(length(pos),1);
+		elist = elist + any(sum(nodeonmacayeal(md.mesh.elements(pos,:)),2),2);
+		elist = elist - any(sum(nodeonpattyn(md.mesh.elements(pos,:))  ,2),2);
+		pos1=find(elist==1);
+		macayealflag(pos(pos1))=1;
+		macayealpattynflag(pos(pos1))=0;
+		pos2=find(elist==-1);
+		pattynflag(pos(pos2))=1;
+		macayealpattynflag(pos(pos2))=0;
+
+		%Recompute nodes associated to these elements
+		nodeonmacayeal(:)=0;
+		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+		nodeonpattyn(:)=0;
+		nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
+		nodeonmacayealpattyn(:)=0;
+		nodeonmacayealpattyn(md.mesh.elements(find(macayealpattynflag),:))=1;
+
+	elseif any(pattynflag) & any(stokesflag), %coupling pattyn stokes
+		%Find node at the border
+		nodeonpattynstokes(find(nodeonpattyn & nodeonstokes))=1;
+		%Stokes elements in contact with this layer become PattynStokes elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonpattynstokes));
+		commonelements=sum(matrixelements,2)~=0;
+		commonelements(find(pattynflag))=0; %only one layer: the elements previously in macayeal
+		stokesflag(find(commonelements))=0; %these elements are now macayealpattynelements
+		pattynstokesflag(find(commonelements))=1;
+		nodeonstokes=zeros(md.mesh.numberofvertices,1);
+		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+
+		%rule out elements that don't touch the 2 boundaries
+		pos=find(pattynstokesflag);
+		elist=zeros(length(pos),1);
+		elist = elist + any(sum(nodeonstokes(md.mesh.elements(pos,:)),2),2);
+		elist = elist - any(sum(nodeonpattyn(md.mesh.elements(pos,:)),2),2);
+		pos1=find(elist==1);
+		stokesflag(pos(pos1))=1;
+		pattynstokesflag(pos(pos1))=0;
+		pos2=find(elist==-1);
+		pattynflag(pos(pos2))=1;
+		pattynstokesflag(pos(pos2))=0;
+
+		%Recompute nodes associated to these elements
+		nodeonstokes(:)=0;
+		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+		nodeonpattyn(:)=0;
+		nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
+		nodeonpattynstokes(:)=0;
+		nodeonpattynstokes(md.mesh.elements(find(pattynstokesflag),:))=1;
+
+	elseif any(stokesflag) & any(macayealflag),
+		%Find node at the border
+		nodeonmacayealstokes(find(nodeonmacayeal & nodeonstokes))=1;
+		%Stokes elements in contact with this layer become MacAyealStokes elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonmacayealstokes));
+		commonelements=sum(matrixelements,2)~=0;
+		commonelements(find(macayealflag))=0; %only one layer: the elements previously in macayeal
+		stokesflag(find(commonelements))=0; %these elements are now macayealmacayealelements
+		macayealstokesflag(find(commonelements))=1;
+		nodeonstokes=zeros(md.mesh.numberofvertices,1);
+		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+
+		%rule out elements that don't touch the 2 boundaries
+		pos=find(macayealstokesflag);
+		elist=zeros(length(pos),1);
+		elist = elist + any(sum(nodeonmacayeal(md.mesh.elements(pos,:)),2),2);
+		elist = elist - any(sum(nodeonstokes(md.mesh.elements(pos,:))  ,2),2);
+		pos1=find(elist==1);
+		macayealflag(pos(pos1))=1;
+		macayealstokesflag(pos(pos1))=0;
+		pos2=find(elist==-1);
+		stokesflag(pos(pos2))=1;
+		macayealstokesflag(pos(pos2))=0;
+
+		%Recompute nodes associated to these elements
+		nodeonmacayeal(:)=0;
+		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+		nodeonstokes(:)=0;
+		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+		nodeonmacayealstokes(:)=0;
+		nodeonmacayealstokes(md.mesh.elements(find(macayealstokesflag),:))=1;
+
+	elseif any(stokesflag) & any(hutterflag),
+		error('type of coupling not supported yet');
+	end
+end
+
+%Create MacaAyealPattynApproximation where needed
+md.flowequation.element_equation=zeros(md.mesh.numberofelements,1);
+md.flowequation.element_equation(find(noneflag))=0;
+md.flowequation.element_equation(find(hutterflag))=1;
+md.flowequation.element_equation(find(macayealflag))=2;
+md.flowequation.element_equation(find(l1l2flag))=8;
+md.flowequation.element_equation(find(pattynflag))=3;
+md.flowequation.element_equation(find(stokesflag))=4;
+md.flowequation.element_equation(find(macayealpattynflag))=5;
+md.flowequation.element_equation(find(macayealstokesflag))=6;
+md.flowequation.element_equation(find(pattynstokesflag))=7;
+
+%border
+md.flowequation.borderpattyn=nodeonpattyn;
+md.flowequation.bordermacayeal=nodeonmacayeal;
+md.flowequation.borderstokes=nodeonstokes;
+
+%Create vertices_type
+md.flowequation.vertex_equation=zeros(md.mesh.numberofvertices,1);
+pos=find(nodeonmacayeal);
+md.flowequation.vertex_equation(pos)=2;
+pos=find(nodeonl1l2);
+md.flowequation.vertex_equation(pos)=8;
+pos=find(nodeonpattyn);
+md.flowequation.vertex_equation(pos)=3;
+pos=find(nodeonhutter);
+md.flowequation.vertex_equation(pos)=1;
+pos=find(nodeonmacayealpattyn);
+md.flowequation.vertex_equation(pos)=5;
+pos=find(nodeonstokes);
+md.flowequation.vertex_equation(pos)=4;
+if any(stokesflag),
+	pos=find(~nodeonstokes);
+	if(~any(pattynflag) & ~any(macayealflag)),
+		md.flowequation.vertex_equation(pos)=0;
+	end
+end
+pos=find(nodeonpattynstokes);
+md.flowequation.vertex_equation(pos)=7;
+pos=find(nodeonmacayealstokes);
+md.flowequation.vertex_equation(pos)=6;
+
+%figure out solution types
+md.flowequation.ishutter=double(any(md.flowequation.element_equation==1));
+md.flowequation.ismacayealpattyn=double(any(md.flowequation.element_equation==2 | md.flowequation.element_equation==3));
+md.flowequation.isstokes=double(any(md.flowequation.element_equation==4));
+md.flowequation.isl1l2=double(any(md.flowequation.element_equation==8));
+
+return
+
+%Check that tiling can work:
+if any(md.flowequation.bordermacayeal) & any(md.flowequation.borderpattyn) & any(md.flowequation.borderpattyn + md.flowequation.bordermacayeal ~=1),
+	error('error coupling domain too irregular');
+end
+if any(md.flowequation.bordermacayeal) & any(md.flowequation.borderstokes) & any(md.flowequation.borderstokes + md.flowequation.bordermacayeal ~=1),
+	error('error coupling domain too irregular');
+end
+if any(md.flowequation.borderstokes) & any(md.flowequation.borderpattyn) & any(md.flowequation.borderpattyn + md.flowequation.borderstokes~=1),
+	error('error coupling domain too irregular');
+end
Index: /issm/trunk/src/m/parameterization/setflowequation.py
===================================================================
--- /issm/trunk/src/m/parameterization/setflowequation.py	(revision 13395)
+++ /issm/trunk/src/m/parameterization/setflowequation.py	(revision 13395)
@@ -0,0 +1,291 @@
+import numpy
+from model import *
+from pairoptions import *
+from MatlabFuncs import *
+from FlagElements import *
+
+def setflowequation(md,*args):
+	"""
+	SETELEMENTSTYPE - associate a solution type to each element
+
+	   This routine works like plotmodel: it works with an even number of inputs
+	   'hutter','macayeal','pattyn','l1l2','stokes' and 'fill' are the possible options
+	   that must be followed by the corresponding exp file or flags list
+	   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
+	   If user wants every element outside the domain to be 
+	   setflowequationd, add '~' to the name of the domain file (ex: '~Pattyn.exp');
+	   an empty string '' will be considered as an empty domain
+	   a string 'all' will be considered as the entire domain
+	   You can specify the type of coupling, 'penalties' or 'tiling', to use with the input 'coupling'
+
+	   Usage:
+	      md=setflowequation(md,varargin)
+
+	   Example:
+	      md=setflowequation(md,'pattyn','Pattyn.exp','macayeal',md.mask.elementonfloatingice,'fill','hutter');
+	      md=setflowequation(md,'pattyn','Pattyn.exp',fill','hutter','coupling','tiling');
+	"""
+
+	#some checks on list of arguments
+	if not isinstance(md,model) or not len(args):
+		raise TypeError("setflowequation error message")
+
+	#process options
+	options=pairoptions(*args)
+#	options=deleteduplicates(options,1);
+
+	#Find_out what kind of coupling to use
+	coupling_method=options.getfieldvalue('coupling','tiling')
+	if not strcmpi(coupling_method,'tiling') and not strcmpi(coupling_method,'penalties'):
+		raise TypeError("coupling type can only be: tiling or penalties")
+
+	#recover elements distribution
+	hutterflag   = FlagElements(md,options.getfieldvalue('hutter',''))
+	macayealflag = FlagElements(md,options.getfieldvalue('macayeal',''))
+	pattynflag   = FlagElements(md,options.getfieldvalue('pattyn',''))
+	l1l2flag     = FlagElements(md,options.getfieldvalue('l1l2',''))
+	stokesflag   = FlagElements(md,options.getfieldvalue('stokes',''))
+	filltype     = options.getfieldvalue('fill','none')
+
+	#Flag the elements that have not been flagged as filltype
+	if   strcmpi(filltype,'hutter'):
+		hutterflag[numpy.nonzero(numpy.logical_not(numpy.logical_or(macayealflag,pattynflag)))]=1
+	elif strcmpi(filltype,'macayeal'):
+		macayealflag[numpy.nonzero(numpy.logical_not(numpy.logical_or(hutterflag,numpy.logical_or(pattynflag,stokesflag))))]=1
+	elif strcmpi(filltype,'pattyn'):
+		pattynflag[numpy.nonzero(numpy.logical_not(numpy.logical_or(hutterflag,numpy.logical_or(macayealflag,stokesflag))))]=1
+
+	#check that each element has at least one flag
+	if not any(hutterflag+macayealflag+l1l2flag+pattynflag+stokesflag):
+		raise TypeError("elements type not assigned, must be specified")
+
+	#check that each element has only one flag
+	if any(hutterflag+macayealflag+l1l2flag+pattynflag+stokesflag>1):
+		print "setflowequation warning message: some elements have several types, higher order type is used for them"
+		hutterflag[numpy.nonzero(numpy.logical_and(hutterflag,macayealflag))]=0
+		hutterflag[numpy.nonzero(numpy.logical_and(hutterflag,pattynflag))]=0
+		macayealflag[numpy.nonzero(numpy.logical_and(macayealflag,pattynflag))]=0
+
+	#Check that no pattyn or stokes for 2d mesh
+	if md.mesh.dimension==2:
+		if numpy.any(numpy.logical_or(l1l2flag,stokesflag,pattynflag)):
+			raise TypeError("stokes and pattyn elements not allowed in 2d mesh, extrude it first")
+
+	#Stokes can only be used alone for now:
+	if any(stokesflag) and any(hutterflag):
+		raise TypeError("stokes cannot be used with any other model for now, put stokes everywhere")
+
+	#Initialize node fields
+	nodeonhutter=numpy.zeros(md.mesh.numberofvertices)
+	nodeonhutter[md.mesh.elements[numpy.nonzero(hutterflag),:].astype(int)-1]=1
+	nodeonmacayeal=numpy.zeros(md.mesh.numberofvertices)
+	nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:].astype(int)-1]=1
+	nodeonl1l2=numpy.zeros(md.mesh.numberofvertices)
+	nodeonl1l2[md.mesh.elements[numpy.nonzero(l1l2flag),:].astype(int)-1]=1
+	nodeonpattyn=numpy.zeros(md.mesh.numberofvertices)
+	nodeonpattyn[md.mesh.elements[numpy.nonzero(pattynflag),:].astype(int)-1]=1
+	nodeonstokes=numpy.zeros(md.mesh.numberofvertices)
+	noneflag=numpy.zeros(md.mesh.numberofelements)
+
+	#First modify stokesflag to get rid of elements contrained everywhere (spc + border with pattyn or macayeal)
+	if any(stokesflag):
+#		fullspcnodes=double((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy)+~isnan(md.diagnostic.spcvz))==3 | (nodeonpattyn & nodeonstokes));         %find all the nodes on the boundary of the domain without icefront
+		fullspcnodes=numpy.logical_or(numpy.logical_not(numpy.isnan(md.diagnostic.spcvx)).astype(int)+ \
+		                              numpy.logical_not(numpy.isnan(md.diagnostic.spcvy)).astype(int)+ \
+		                              numpy.logical_not(numpy.isnan(md.diagnostic.spcvz)).astype(int)==3, \
+		                              numpy.logical_and(nodeonpattyn,nodeonstokes)).astype(int)    #find all the nodes on the boundary of the domain without icefront
+#		fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
+		fullspcelems=(numpy.sum(fullspcnodes[md.mesh.elements.astype(int)-1],axis=1)==6).astype(int)    #find all the nodes on the boundary of the domain without icefront
+		stokesflag[numpy.nonzero(fullspcelems)]=0
+		nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:].astype(int)-1]=1
+
+	#Then complete with NoneApproximation or the other model used if there is no stokes
+	if any(stokesflag): 
+		if   any(pattynflag):    #fill with pattyn
+			pattynflag[numpy.logical_not(stokesflag)]=1
+			nodeonpattyn[md.mesh.elements[numpy.nonzero(pattynflag),:].astype(int)-1]=1
+		elif any(macayealflag):    #fill with macayeal
+			macayealflag[numpy.logical_not(stokesflag)]=1
+			nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:].astype(int)-1]=1
+		else:    #fill with none 
+			noneflag[numpy.nonzero(numpy.logical_not(stokesflag))]=1
+
+	#Now take care of the coupling between MacAyeal and Pattyn
+	md.diagnostic.vertex_pairing=numpy.array([])
+	nodeonmacayealpattyn=numpy.zeros(md.mesh.numberofvertices)
+	nodeonpattynstokes=numpy.zeros(md.mesh.numberofvertices)
+	nodeonmacayealstokes=numpy.zeros(md.mesh.numberofvertices)
+	macayealpattynflag=numpy.zeros(md.mesh.numberofelements)
+	macayealstokesflag=numpy.zeros(md.mesh.numberofelements)
+	pattynstokesflag=numpy.zeros(md.mesh.numberofelements)
+	if   strcmpi(coupling_method,'penalties'):
+		#Create the border nodes between Pattyn and MacAyeal and extrude them
+		numnodes2d=md.mesh.numberofvertices2d
+		numlayers=md.mesh.numberoflayers
+		bordernodes2d=numpy.nonzero(numpy.logical_and(nodeonpattyn[1:numnodes2d],nodeonmacayeal[1:numnodes2d]))    #Nodes connected to two different types of elements
+
+		#initialize and fill in penalties structure
+		if numpy.all(numpy.logical_not(numpy.isnan(bordernodes2d))):
+			penalties=numpy.zeros((0,2))
+			for	i in xrange(1,numlayers):
+				penalties=numpy.concatenate((penalties,numpy.concatenate((bordernodes2d,bordernodes2d+md.mesh.numberofvertices2d*(i)),axis=1)),axis=0)
+			md.diagnostic.vertex_pairing=penalties
+
+	elif strcmpi(coupling_method,'tiling'):
+		if   any(macayealflag) and any(pattynflag):    #coupling macayeal pattyn
+			#Find node at the border
+			nodeonmacayealpattyn[numpy.nonzero(numpy.logical_and(nodeonmacayeal,nodeonpattyn))]=1
+			#Macayeal elements in contact with this layer become MacAyealPattyn elements
+			matrixelements=ismember(md.mesh.elements,numpy.nonzero(nodeonmacayealpattyn))
+			commonelements=numpy.sum(matrixelements,axis=1)!=0
+			commonelements[numpy.nonzero(pattynflag)]=0    #only one layer: the elements previously in macayeal
+			macayealflag[numpy.nonzero(commonelements)]=0    #these elements are now macayealpattynelements
+			macayealpattynflag[numpy.nonzero(commonelements)]=1
+			nodeonmacayeal[:]=0
+			nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:].astype(int)-1]=1
+
+			#rule out elements that don't touch the 2 boundaries
+			pos=numpy.nonzero(macayealpattynflag)
+			elist=numpy.zeros(len(pos))
+			elist = elist + numpy.any(numpy.sum(nodeonmacayeal[md.mesh.elements[pos,:].astype(int)-1],axis=1),axis=1)
+			elist = elist - numpy.any(numpy.sum(nodeonpattyn[md.mesh.elements[pos,:].astype(int)-1]  ,axis=1),axis=1)
+			pos1=numpy.nonzero(elist==1)
+			macayealflag[pos[pos1]]=1
+			macayealpattynflag[pos[pos1]]=0
+			pos2=numpy.nonzero(elist==-1)
+			pattynflag[pos[pos2]]=1
+			macayealpattynflag[pos[pos2]]=0
+
+			#Recompute nodes associated to these elements
+			nodeonmacayeal[:]=0
+			nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:].astype(int)-1]=1
+			nodeonpattyn[:]=0
+			nodeonpattyn[md.mesh.elements[numpy.nonzero(pattynflag),:].astype(int)-1]=1
+			nodeonmacayealpattyn[:]=0
+			nodeonmacayealpattyn[md.mesh.elements[numpy.nonzero(macayealpattynflag),:].astype(int)-1]=1
+
+		elif any(pattynflag) and any(stokesflag):    #coupling pattyn stokes
+			#Find node at the border
+			nodeonpattynstokes[numpy.nonzero(numpy.logical_and(nodeonpattyn,nodeonstokes))]=1
+			#Stokes elements in contact with this layer become PattynStokes elements
+			matrixelements=ismember(md.mesh.elements,numpy.nonzero(nodeonpattynstokes))
+			commonelements=numpy.sum(matrixelements,axis=1)!=0
+			commonelements[numpy.nonzero(pattynflag)]=0    #only one layer: the elements previously in macayeal
+			stokesflag[numpy.nonzero(commonelements)]=0    #these elements are now macayealpattynelements
+			pattynstokesflag[numpy.nonzero(commonelements)]=1
+			nodeonstokes=numpy.zeros(md.mesh.numberofvertices)
+			nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:].astype(int)-1]=1
+
+			#rule out elements that don't touch the 2 boundaries
+			pos=numpy.nonzero(pattynstokesflag)
+			elist=numpy.zeros(len(pos))
+			elist = elist + numpy.any(numpy.sum(nodeonstokes[md.mesh.elements[pos,:].astype(int)-1],axis=1),axis=1)
+			elist = elist - numpy.any(numpy.sum(nodeonpattyn[md.mesh.elements[pos,:].astype(int)-1],axis=1),axis=1)
+			pos1=numpy.nonzero(elist==1)
+			stokesflag[pos[pos1]]=1
+			pattynstokesflag[pos[pos1]]=0
+			pos2=numpy.nonzero(elist==-1)
+			pattynflag[pos[pos2]]=1
+			pattynstokesflag[pos[pos2]]=0
+
+			#Recompute nodes associated to these elements
+			nodeonstokes[:]=0
+			nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:].astype(int)-1]=1
+			nodeonpattyn[:]=0
+			nodeonpattyn[md.mesh.elements[numpy.nonzero(pattynflag),:].astype(int)-1]=1
+			nodeonpattynstokes[:]=0
+			nodeonpattynstokes[md.mesh.elements[numpy.nonzero(pattynstokesflag),:].astype(int)-1]=1
+
+		elif any(stokesflag) and any(macayealflag):
+			#Find node at the border
+			nodeonmacayealstokes[numpy.nonzero(numpy.logical_and(nodeonmacayeal,nodeonstokes))]=1
+			#Stokes elements in contact with this layer become MacAyealStokes elements
+			matrixelements=ismember(md.mesh.elements,numpy.nonzero(nodeonmacayealstokes))
+			commonelements=numpy.sum(matrixelements,axis=1)!=0
+			commonelements[numpy.nonzero(macayealflag)]=0    #only one layer: the elements previously in macayeal
+			stokesflag[numpy.nonzero(commonelements)]=0    #these elements are now macayealmacayealelements
+			macayealstokesflag[numpy.nonzero(commonelements)]=1
+			nodeonstokes=numpy.zeros(md.mesh.numberofvertices)
+			nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:].astype(int)-1]=1
+
+			#rule out elements that don't touch the 2 boundaries
+			pos=numpy.nonzero(macayealstokesflag)
+			elist=numpy.zeros(len(pos))
+			elist = elist + numpy.any(numpy.sum(nodeonmacayeal[md.mesh.elements[pos,:].astype(int)-1],axis=1),axis=1)
+			elist = elist - numpy.any(numpy.sum(nodeonstokes[md.mesh.elements[pos,:].astype(int)-1]  ,axis=1),axis=1)
+			pos1=numpy.nonzero(elist==1)
+			macayealflag[pos[pos1]]=1
+			macayealstokesflag[pos[pos1]]=0
+			pos2=numpy.nonzero(elist==-1)
+			stokesflag[pos[pos2]]=1
+			macayealstokesflag[pos[pos2]]=0
+
+			#Recompute nodes associated to these elements
+			nodeonmacayeal[:]=0
+			nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:].astype(int)-1]=1
+			nodeonstokes[:]=0
+			nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:].astype(int)-1]=1
+			nodeonmacayealstokes[:]=0
+			nodeonmacayealstokes[md.mesh.elements[numpy.nonzero(macayealstokesflag),:].astype(int)-1]=1
+
+		elif any(stokesflag) and any(hutterflag):
+			raise TypeError("type of coupling not supported yet")
+
+	#Create MacaAyealPattynApproximation where needed
+	md.flowequation.element_equation=numpy.zeros(md.mesh.numberofelements)
+	md.flowequation.element_equation[numpy.nonzero(noneflag)]=0
+	md.flowequation.element_equation[numpy.nonzero(hutterflag)]=1
+	md.flowequation.element_equation[numpy.nonzero(macayealflag)]=2
+	md.flowequation.element_equation[numpy.nonzero(l1l2flag)]=8
+	md.flowequation.element_equation[numpy.nonzero(pattynflag)]=3
+	md.flowequation.element_equation[numpy.nonzero(stokesflag)]=4
+	md.flowequation.element_equation[numpy.nonzero(macayealpattynflag)]=5
+	md.flowequation.element_equation[numpy.nonzero(macayealstokesflag)]=6
+	md.flowequation.element_equation[numpy.nonzero(pattynstokesflag)]=7
+
+	#border
+	md.flowequation.borderpattyn=nodeonpattyn
+	md.flowequation.bordermacayeal=nodeonmacayeal
+	md.flowequation.borderstokes=nodeonstokes
+
+	#Create vertices_type
+	md.flowequation.vertex_equation=numpy.zeros(md.mesh.numberofvertices)
+	pos=numpy.nonzero(nodeonmacayeal)
+	md.flowequation.vertex_equation[pos]=2
+	pos=numpy.nonzero(nodeonl1l2)
+	md.flowequation.vertex_equation[pos]=8
+	pos=numpy.nonzero(nodeonpattyn)
+	md.flowequation.vertex_equation[pos]=3
+	pos=numpy.nonzero(nodeonhutter)
+	md.flowequation.vertex_equation[pos]=1
+	pos=numpy.nonzero(nodeonmacayealpattyn)
+	md.flowequation.vertex_equation[pos]=5
+	pos=numpy.nonzero(nodeonstokes)
+	md.flowequation.vertex_equation[pos]=4
+	if any(stokesflag):
+		pos=numpy.nonzero(numpy.logical_not(nodeonstokes))
+		if not (any(pattynflag) or any(macayealflag)):
+			md.flowequation.vertex_equation[pos]=0
+	pos=numpy.nonzero(nodeonpattynstokes)
+	md.flowequation.vertex_equation[pos]=7
+	pos=numpy.nonzero(nodeonmacayealstokes)
+	md.flowequation.vertex_equation[pos]=6
+
+	#figure out solution types
+	md.flowequation.ishutter=float(any(md.flowequation.element_equation==1))
+	md.flowequation.ismacayealpattyn=float(numpy.any(numpy.logical_or(md.flowequation.element_equation==2,md.flowequation.element_equation==3)))
+	md.flowequation.isl1l2=float(any(md.flowequation.element_equation==8))
+	md.flowequation.isstokes=float(any(md.flowequation.element_equation==4))
+
+	return md
+
+	#Check that tiling can work:
+	if any(md.flowequation.bordermacayeal) and any(md.flowequation.borderpattyn) and any(md.flowequation.borderpattyn + md.flowequation.bordermacayeal !=1):
+		raise TypeError("error coupling domain too irregular")
+	if any(md.flowequation.bordermacayeal) and any(md.flowequation.borderstokes) and any(md.flowequation.borderstokes + md.flowequation.bordermacayeal !=1):
+		raise TypeError("error coupling domain too irregular")
+	if any(md.flowequation.borderstokes) and any(md.flowequation.borderpattyn) and any(md.flowequation.borderpattyn + md.flowequation.borderstokes !=1):
+		raise TypeError("error coupling domain too irregular")
+
+	return md
+
Index: /issm/trunk/src/m/parameterization/setmask.m
===================================================================
--- /issm/trunk/src/m/parameterization/setmask.m	(revision 13395)
+++ /issm/trunk/src/m/parameterization/setmask.m	(revision 13395)
@@ -0,0 +1,49 @@
+function md=setmask(md,floatingicename,groundedicename)
+%SETMASK - establish boundaries between grounded and floating ice.
+%
+%   By default, ice is considered grounded. The contour floatingicename defines nodes 
+%   for which ice is floating. The contour groundedicename defines nodes inside an floatingice, 
+%   that are grounded (ie: ice rises, islands, etc ...)
+%   All input files are in the Argus format (extension .exp).
+%
+%   Usage:
+%      md=setmask(md,floatingicename,groundedicename)
+%
+%   Examples:
+%      md=setmask(md,'all','');
+%      md=setmask(md,'Iceshelves.exp','Islands.exp');
+
+%some checks on list of arguments
+if ((nargin~=3) | (nargout~=1)),
+	help mask
+	error('mask error message');
+end
+
+%Get assigned fields
+x=md.mesh.x;
+y=md.mesh.y;
+elements=md.mesh.elements;
+
+%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);
+
+%Because groundedice nodes and elements can be included into an floatingice, we need to update. Remember, all the previous 
+%arrays come from domain outlines that can intersect one another: 
+elementonfloatingice=double((elementonfloatingice & ~elementongroundedice));
+elementongroundedice=double(~elementonfloatingice);
+
+%the order here is important. we choose vertexongroundedice as default on the grounding line.
+vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
+vertexongroundedice=zeros(md.mesh.numberofvertices,1);
+vertexongroundedice(md.mesh.elements(find(elementongroundedice),:))=1;
+vertexonfloatingice(find(~vertexongroundedice))=1;
+%}}}
+
+%Return: 
+md.mask.elementonfloatingice=elementonfloatingice;
+md.mask.vertexonfloatingice=vertexonfloatingice;
+md.mask.elementongroundedice=elementongroundedice;
+md.mask.vertexongroundedice=vertexongroundedice;
+md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
+md.mask.elementonwater=zeros(md.mesh.numberofelements,1);
Index: /issm/trunk/src/m/parameterization/setmask.py
===================================================================
--- /issm/trunk/src/m/parameterization/setmask.py	(revision 13395)
+++ /issm/trunk/src/m/parameterization/setmask.py	(revision 13395)
@@ -0,0 +1,55 @@
+from numpy import *
+import FlagElements as fe
+
+def setmask(md, floatingicename, groundedicename):
+	#SETMASK - establish boundaries between grounded and floating ice.
+	#
+	#   By default, ice is considered grounded. The contour floatingicename defines nodes 
+	#   for which ice is floating. The contour groundedicename defines nodes inside an floatingice, 
+	#   that are grounded (ie: ice rises, islands, etc ...)
+	#   All input files are in the Argus format (extension .exp).
+	#
+	#   Usage:
+	#      md=setmask(md,floatingicename,groundedicename)
+	#
+	#   Examples:
+	#      md=setmask(md,'all','');
+	#      md=setmask(md,'Iceshelves.exp','Islands.exp');
+
+	#%Get assigned fields
+	x = md.mesh.x
+	y = md.mesh.y
+	elements = md.mesh.elements
+
+	#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) 
+
+	#Because groundedice nodes and elements can be included into an floatingice, we need to update. Remember, all the previous 
+	#arrays come from domain outlines that can intersect one another: 
+
+	elementonfloatingice = logical_and(elementonfloatingice,~elementongroundedice)
+	elementongroundedice = ~elementonfloatingice
+
+	#the order here is important. we choose vertexongroundedice as default on the grounding line.
+	vertexonfloatingice = zeros(md.mesh.numberofvertices,'bool')
+	vertexongroundedice = zeros(md.mesh.numberofvertices,'bool')
+
+	pos=argwhere(elementongroundedice==1)
+	pos=md.mesh.elements[pos,:]-1
+	if pos.size:
+		vertexongroundedice[pos]=True
+
+	pos=argwhere(~vertexongroundedice)
+	if pos.size:
+		vertexonfloatingice[pos]=True;
+	#%}}}
+
+	#Return: 
+	md.mask.elementonfloatingice = double(elementonfloatingice)
+	md.mask.vertexonfloatingice = double(vertexonfloatingice)
+	md.mask.elementongroundedice = double(elementongroundedice)
+	md.mask.vertexongroundedice = double(vertexongroundedice)
+	md.mask.vertexonwater = zeros(md.mesh.numberofvertices)
+	md.mask.elementonwater = zeros(md.mesh.numberofelements)
+	return md
Index: /issm/trunk/src/m/parameterization/setmask2.m
===================================================================
--- /issm/trunk/src/m/parameterization/setmask2.m	(revision 13395)
+++ /issm/trunk/src/m/parameterization/setmask2.m	(revision 13395)
@@ -0,0 +1,148 @@
+function md=setmask2(md,landname,floatingicename,groundedicename)
+%GEOGRAPHY2 - establish land, ice sheet and ice shelf areas in a domains.
+%
+%   Usage:
+%      md=setmask2(md,landname,floatingicename,groundedicename)
+%
+%   Examples:
+%      md=setmask2(md,'LandName.exp','Iceshelves.exp','Islands.exp');
+
+%Get assigned fields
+x=md.mesh.x;
+y=md.mesh.y;
+elements=md.mesh.elements;
+
+%recover elements and nodes on land.
+if ischar(landname),
+	[vertexonland,elementonland]=ContourToMesh(elements,x,y,landname,'element and node',2);
+elseif isfloat(landname),
+	if size(landname,1)~=md.mesh.numberofelements,
+		error('Landname for area must be of same size as number of elements in model');
+	end
+	elementonland=landname;
+	vertexonland=zeros(md.mesh.numberofvertices,1);
+	vertexonland(md.mesh.elements(find(elementonland),:))=1;
+else
+	error('Invalid area option option');
+end
+
+%Now, build the connectivity tables for this mesh.
+if size(md.mesh.vertexconnectivity,1)~=md.mesh.numberofvertices,
+	md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+end
+if size(md.mesh.elementconnectivity,1)~=md.mesh.numberofelements,
+	md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+end
+
+%any element with 3 nodes on land should be on land:
+elementsonwater=find(~elementonland);
+wrongelements=elementsonwater(find(( vertexonland(md.mesh.elements(elementsonwater,1)) + vertexonland(md.mesh.elements(elementsonwater,2)) + vertexonland(md.mesh.elements(elementsonwater,3)) ...
+                  )==3));
+elementonland(wrongelements)=1;
+
+%any element with its barycentre on land should be on land: (only if landname is an expfile)
+if ischar(landname),
+weights={[1;1;1],[2;1;1],[1;2;1],[1;1;2]};
+	for i=1:length(weights),
+		xelem=x(md.mesh.elements)*weights{i}/sum(weights{i});
+		yelem=y(md.mesh.elements)*weights{i}/sum(weights{i});
+	end
+	baryonland=ContourToNodes(xelem,yelem,landname,1);
+	pos=find(~baryonland); elementonland(pos)=0;
+	pos=find(baryonland); elementonland(pos)=1;
+end
+
+%figure out which elements on land are actually in the middle of the ocean!
+pos1=find(elementonland); 
+connectedtoland=md.mesh.elementconnectivity(pos1,:);
+pos=find(connectedtoland); connectedtoland(pos)=1-elementonland(connectedtoland(pos));
+connectedtolandsum=sum(connectedtoland,2);
+waterelements=pos1(find(connectedtolandsum==3));
+elementonland(waterelements)=0;
+
+%figure out which elements on water  are actually in the middle of the land!
+pos1=find(~elementonland); 
+connectedtowater=md.mesh.elementconnectivity(pos1,:);
+pos=find(connectedtowater); connectedtowater(pos)=elementonland(connectedtowater(pos));
+connectedtowatersum=sum(connectedtowater,2);
+landelements=pos1(find(connectedtowatersum==3));
+elementonland(landelements)=1;
+
+%recover arrays of ice shelf nodes and elements, and ice sheet nodes and elements.
+elementonfloatingice=FlagElements(md,floatingicename);
+elementongroundedice=FlagElements(md,groundedicename);
+
+%Because groundedice nodes and elements can be included into an floatingice, we need to update. Remember, all the previous 
+%arrays come from domain outlines that can intersect one another: 
+vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
+vertexongroundedice=zeros(md.mesh.numberofvertices,1);
+elementonfloatingice=double((elementonfloatingice & ~elementongroundedice));
+elementongroundedice=double(~elementonfloatingice);
+vertexonfloatingice(md.mesh.elements(find(elementonfloatingice),:))=1;
+vertexongroundedice(md.mesh.elements(find(elementongroundedice),:))=1;
+
+%now correct, so that none of the floatingice and groundedice elements and nodes are in the water.
+pos=find(~elementonland);
+elementonfloatingice(pos)=0; 
+elementongroundedice(pos)=0;
+
+pos=find(~vertexonland);
+vertexonfloatingice(pos)=0; 
+vertexongroundedice(pos)=0;
+
+%create vertexonwater and elementonwater: 
+vertexonwater=double(~vertexonland);
+elementonwater=double(~elementonland);
+
+%correct for islands:
+vertexonfloatingice=double(vertexonfloatingice & ~vertexongroundedice);
+elementonfloatingice=double(elementonfloatingice & ~elementongroundedice);
+
+%now, groundedices are everything except iceshelves and water
+vertexongroundedice=double(~vertexonfloatingice & ~vertexonwater);
+elementongroundedice=double(~elementonfloatingice & ~elementonwater);
+
+%Deal with segments on neumann:
+
+%Get current connectivity
+mesh.elementconnectivity=md.mesh.elementconnectivity;
+
+%put 0 for elements on water
+pos=find(mesh.elementconnectivity);
+mesh.elementconnectivity(pos)=mesh.elementconnectivity(pos).*(~elementonwater(mesh.elementconnectivity(pos)));
+
+%put line of ones for elements on water
+pos=find(elementonwater);
+mesh.elementconnectivity(pos,:)=1;% line of ones for elements on water so they won't be considered
+
+%resort lines (zeros must be at the last column for findsegments)
+mesh.elementconnectivity=sort(mesh.elementconnectivity,2,'descend');
+
+%call findsegments to build segment using THIS conectivity
+md.mesh.segments=findsegments(md,'mesh.elementconnectivity',mesh.elementconnectivity);
+
+%some final checks: 
+%check that no node thinks it's on an ice shelf or ice sheet, and lies actually in the middle of the water.
+nodesgrounded=find(~vertexonwater);
+lengthconnectivity=size(md.mesh.vertexconnectivity,2);
+groundedcounters=md.mesh.vertexconnectivity(nodesgrounded,lengthconnectivity);
+groundedconnectivity=md.mesh.vertexconnectivity(nodesgrounded,1:lengthconnectivity-1);
+pos=find(groundedconnectivity);
+groundedconnectivity(pos)=elementonwater(groundedconnectivity(pos));
+groundedsum=sum(groundedconnectivity,2);
+errorflags=find(groundedsum==groundedcounters);
+errornodes=nodesgrounded(errorflags);
+
+vertexonwater(errornodes)=1;
+vertexongroundedice(errornodes)=0;
+vertexonfloatingice(errornodes)=0;
+
+%Return: 
+md.mask.vertexonfloatingice=vertexonfloatingice;
+md.mask.elementonfloatingice=elementonfloatingice;
+md.mask.vertexonwater=vertexonwater;
+md.mask.elementonwater=elementonwater;
+md.mask.vertexongroundedice=vertexongroundedice;
+md.mask.elementongroundedice=elementongroundedice;
+
+md.mesh.segmentmarkers(:)=1;
Index: /issm/trunk/src/m/partition/AreaAverageOntoPartition.m
===================================================================
--- /issm/trunk/src/m/partition/AreaAverageOntoPartition.m	(revision 13395)
+++ /issm/trunk/src/m/partition/AreaAverageOntoPartition.m	(revision 13395)
@@ -0,0 +1,55 @@
+function partvector=AreaAverageOntoPartition(md,vector,layer)
+%AREAAVERAGEONTOPARTITION 
+%   compute partition values for a certain vector expressed on the vertices of the mesh.
+%   Use area weighted average.
+%
+%   Usage:
+%      average=AreaAverageOntoPartition(md,vector)
+%      average=AreaAverageOntoPartition(md,vector,layer) %if in 3D, chose which layer is partitioned
+
+%some checks
+if md.mesh.dimension==3,
+	if nargin~=3,
+		error('layer should be provided onto which Area Averaging occurs');
+	end
+	%save 3D model
+	md3d=md;
+	
+	md.mesh.elements=md.mesh.elements2d;
+	md.mesh.x=md.mesh.x2d;
+	md.mesh.y=md.mesh.y2d;
+	md.mesh.numberofvertices=md.mesh.numberofvertices2d;
+	md.mesh.numberofelements=md.mesh.numberofelements2d;
+	md.qmu.vertex_weight=[];
+	md.mesh.vertexconnectivity=[];
+
+	%run connectivity routine
+	md=adjacency(md);
+
+	%finally, project vector: 
+	vector=project2d(md3d,vector,layer);
+	md.qmu.partition=project2d(md3d,md3d.qmu.partition,layer);
+end
+
+%ok, first check that part is Matlab indexed
+part=md.qmu.partition+1;
+
+%some check: 
+if md.qmu.numberofpartitions~=max(part),
+	error('AreaAverageOntoPartition error message: ''npart'' should be equal to max(md.qmu.partition)');
+end
+
+%initialize output
+partvector=zeros(max(part),1);
+
+%start weight average
+weightedvector=vector.*md.qmu.vertex_weight;
+for i=1:max(part),
+	pos=find(part==i);
+	partvector(i)=sum(weightedvector(pos))/sum(md.qmu.vertex_weight(pos));
+end
+
+%in 3D, restore 3D model:
+if md.mesh.dimension==3,
+	md=md3d;
+end
Index: /issm/trunk/src/m/partition/adjacency.m
===================================================================
--- /issm/trunk/src/m/partition/adjacency.m	(revision 13395)
+++ /issm/trunk/src/m/partition/adjacency.m	(revision 13395)
@@ -0,0 +1,26 @@
+function md=adjacency(md);
+%ADJACENCY -  compute adjacency matrix, list of vertices and list of weights.
+%
+%  function to create the adjacency matrix from the connectivity table.
+%
+%  the required output is:
+%    md.adj_mat     (double [sparse nv x nv], vertex adjacency matrix)
+%    md.qmu.vertex_weight        (double [nv], vertex weights)
+
+indi=[md.mesh.elements(:,1);md.mesh.elements(:,2);md.mesh.elements(:,3)];
+indj=[md.mesh.elements(:,2);md.mesh.elements(:,3);md.mesh.elements(:,1)];
+values=1;
+
+md.qmu.adjacency=sparse(indi,indj,values,md.mesh.numberofvertices,md.mesh.numberofvertices);
+md.qmu.adjacency=double([md.qmu.adjacency | md.qmu.adjacency']);
+
+%now, build vwgt:
+areas=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
+
+%get node connectivity
+md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+
+connectivity=md.mesh.vertexconnectivity(:,1:end-1);
+pos=find(connectivity);
+connectivity(pos)=areas(connectivity(pos))/3;
+md.qmu.vertex_weight=sum(connectivity,2);
Index: /issm/trunk/src/m/partition/flagedges.m
===================================================================
--- /issm/trunk/src/m/partition/flagedges.m	(revision 13395)
+++ /issm/trunk/src/m/partition/flagedges.m	(revision 13395)
@@ -0,0 +1,45 @@
+function [xsegments ysegments]=flagedges(elements,x,y,partition);
+%FLAGEDGES - return pairs of x,y segments, delimiting partitions.
+%
+%   Usage:
+%      [xsegments ysegments]=flagedges(elements,x,y,partition)
+
+xsegments=[];
+ysegments=[];
+
+for i=1:size(elements,1),
+	m1=partition(elements(i,1));
+	m2=partition(elements(i,2));
+	m3=partition(elements(i,3));
+	x1=x(elements(i,1));
+	x2=x(elements(i,2));
+	x3=x(elements(i,3));
+	y1=y(elements(i,1));
+	y2=y(elements(i,2));
+	y3=y(elements(i,3));
+
+	if (m1~=m2) & (m1~=m3) & (m2~=m3),
+		xmiddle=(x1+x2+x3)/3;
+		ymiddle=(y1+y2+y3)/3;
+		xsegments=[xsegments; (x1+x2)/2 xmiddle];
+		xsegments=[xsegments; (x1+x3)/2 xmiddle];
+		xsegments=[xsegments; (x2+x3)/2 xmiddle];
+		ysegments=[ysegments; (y1+y2)/2 ymiddle];
+		ysegments=[ysegments; (y1+y3)/2 ymiddle];
+		ysegments=[ysegments; (y2+y3)/2 ymiddle];
+	end
+
+	if (m1==m2) & (m1~=m3),
+		xsegments=[xsegments; (x1+x3)/2 (x2+x3)/2];
+		ysegments=[ysegments; (y1+y3)/2 (y2+y3)/2];
+	end
+	if (m1==m3) & (m2~=m3),
+		xsegments=[xsegments; (x1+x2)/2 (x2+x3)/2];
+		ysegments=[ysegments; (y1+y2)/2 (y2+y3)/2];
+	end
+
+	if (m2==m3) & (m1~=m3),
+		xsegments=[xsegments; (x1+x2)/2 (x1+x3)/2];
+		ysegments=[ysegments; (y1+y2)/2 (y1+y3)/2];
+	end
+end
Index: /issm/trunk/src/m/partition/partitioner.m
===================================================================
--- /issm/trunk/src/m/partition/partitioner.m	(revision 13395)
+++ /issm/trunk/src/m/partition/partitioner.m	(revision 13395)
@@ -0,0 +1,107 @@
+function md=partitioner(md,varargin)
+%PARTITIONER - partition mesh 
+%
+%   List of options to partitioner: 
+%
+%   package: 'chaco', 'metis' or 'scotch'
+%   npart: number of partitions.
+%   weighting: 'on' or 'off': default off
+%   section:  1 by defaults(1=bisection, 2=quadrisection, 3=octasection)
+%   recomputeadjacency:  'on' by default (set to 'off' to compute existing one)
+%   Output: md.qmu.partition recover the partition vector
+%   
+%   Usage:
+%      md=partitioner(md,'package','chaco','npart',100,'weighting','on');
+%
+
+%get options: 
+options=pairoptions(varargin{:});
+
+%set defaults
+options=addfielddefault(options,'package','chaco');
+options=addfielddefault(options,'npart',10);
+options=addfielddefault(options,'weighting','on');
+options=addfielddefault(options,'section',1);
+options=addfielddefault(options,'recomputeadjacency','on');
+
+%get package: 
+package=getfieldvalue(options,'package');
+npart=getfieldvalue(options,'npart');
+recomputeadjacency=getfieldvalue(options,'recomputeadjacency');
+
+if(md.mesh.dimension==3),
+	%partitioning essentially happens in 2D. So partition in 2D, then 
+	%extrude the partition vector vertically. 
+	md3d=md; %save  for later
+	md.mesh.elements=md.mesh.elements2d;
+	md.mesh.x=md.mesh.x2d;
+	md.mesh.y=md.mesh.y2d;
+	md.mesh.numberofvertices=md.mesh.numberofvertices2d;
+	md.mesh.numberofelements=md.mesh.numberofelements2d;
+	md.qmu.vertex_weight=[];
+	md.mesh.vertexconnectivity=[];
+end
+
+%adjacency matrix if needed:
+if strcmpi(recomputeadjacency,'on'),
+	md=adjacency(md);
+else
+	disp('skipping adjacency matrix computation as requested in the options');
+end
+
+
+if strcmpi(package,'chaco'),
+
+	%  default method (from chaco.m)
+	method=[1 1 0 0 1 1 50 0 .001 7654321]';
+	method(1)=3;    %  global method (3=inertial (geometric))
+	method(3)=0;    %  vertex weights (0=off, 1=on)
+	
+	%specify bisection
+	method(6)=getfieldvalue(options,'section');%  ndims (1=bisection, 2=quadrisection, 3=octasection)
+
+	%are we using weights? 
+	if strcmpi(getfieldvalue(options,'weighting'),'on'),
+		weights=floor(md.qmu.vertex_weight/min(md.qmu.vertex_weight));
+		method(3)=1;
+	else 
+		weights=[];
+	end
+	
+	%  partition into nparts
+	part=Chaco(md.qmu.adjacency,weights,[],md.mesh.x, md.mesh.y ,md.mesh.z,method,npart,[])'+1; %index partitions from 1 up. like metis.
+
+elseif strcmpi(package,'scotch'),
+
+	%are we using weights? 
+	if strcmpi(getfieldvalue(options,'weighting'),'on'),
+		weights=floor(md.qmu.vertex_weight/min(md.qmu.vertex_weight));
+	end
+	maptab=Scotch(md.qmu.adjacency,[],weights,[],'cmplt',[npart]);
+	
+	part=maptab(:,2);%index partitions from 1 up. like metis.
+
+
+elseif strcmpi(package,'linear'),
+
+	part=1:1:md.mesh.numberofvertices;
+
+elseif strcmpi(package,'metis'),
+
+	[element_partitioning,part]=MeshPartition(md.mesh,md.qmu.numberofpartitions);
+
+else
+
+	error(['partitioner error message: could not find ' package ' partitioner']);
+	help partitioner
+end
+
+%extrude if we are in 3D:
+if md.mesh.dimension==3,
+	md3d.qmu.vertex_weight=md.qmu.vertex_weight;
+	md3d.qmu.adjacency=md.qmu.adjacency;
+	md=md3d;
+	part=project3d(md,'vector',part','type','node');
+end
+
+md.qmu.partition=part;
Index: /issm/trunk/src/m/plot/applyoptions.m
===================================================================
--- /issm/trunk/src/m/plot/applyoptions.m	(revision 13395)
+++ /issm/trunk/src/m/plot/applyoptions.m	(revision 13395)
@@ -0,0 +1,509 @@
+function applyoptions(md,data,options)
+%APPLYOPTIONS - apply the options to current plot
+%
+%   Usage:
+%      applyoptions(md,data,options)
+%
+%   See also: PLOTMODEL, PARSE_OPTIONS
+		
+
+%some defaults
+if isfield(md.mesh,'hemisphere'),
+	if strcmpi(md.mesh.hemisphere,'n'), options=addfielddefault(options,'hemisphere','n'); 
+	elseif strcmpi(md.mesh.hemisphere,'s'), options=addfielddefault(options,'hemisphere','s'); 
+	end
+end
+
+%fontsize
+fontsize=getfieldvalue(options,'fontsize',14);
+
+%fontweight
+fontweight=getfieldvalue(options,'fontweight','normal');
+
+%title
+if exist(options,'title')
+	titlevalue=getfieldvalue(options,'title');
+	if iscell(titlevalue),
+		title(titlevalue,'FontSize',fontsize,'FontWeight',fontweight);
+	else
+		if ~isnan(titlevalue),
+			title(titlevalue,'FontSize',fontsize,'FontWeight',fontweight);
+		end
+	end
+end
+
+%xlabel, ylabel and zlabel
+if exist(options,'xlabel');
+	xlabel(getfieldvalue(options,'xlabel'),'FontSize',fontsize,'FontWeight',fontweight);
+end
+if exist(options,'ylabel');
+	ylabel(getfieldvalue(options,'ylabel'),'FontSize',fontsize,'FontWeight',fontweight);
+end
+if exist(options,'zlabel');
+	zlabel(getfieldvalue(options,'zlabel'),'FontSize',fontsize,'FontWeight',fontweight);
+end
+
+%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
+if exist(options,'ztick'), set(gca,'ZTick',getfieldvalue(options,'ztick')); end
+
+%view 
+if md.mesh.dimension==3 & ~exist(options,'layer'),
+	view(getfieldvalue(options,'view',3));
+else
+	view(getfieldvalue(options,'view',2));
+end
+
+%axis
+set(gca,'FontSize',getfieldvalue(options,'axisfontsize',fontsize));;
+if exist(options,'axis')
+	eval(['axis ' getfieldvalue(options,'axis')]);
+else
+	if ((md.mesh.dimension==2) | exist(options,'layer')),
+		axis tight equal;
+	else
+		axis auto tight
+	end
+end
+
+%box
+if exist(options,'box')
+	eval(['box ' getfieldvalue(options,'box')]);
+end
+
+%xlim, ylim and zlim
+if exist(options,'xlim');
+	xlim(getfieldvalue(options,'xlim'));
+end
+if exist(options,'ylim');
+	ylim(getfieldvalue(options,'ylim'));
+end
+if exist(options,'zlim');
+	zlim(getfieldvalue(options,'zlim'));
+end
+
+%latlon
+%Must be done here (before xlim and ylim??) so that it uses the same xlim and ylim as plot_overlay
+%these are changed by axis that follows
+if ~strcmpi(getfieldvalue(options,'latlon','off'),'off')
+	latlonoverlay(md,options);
+end
+
+%Basinzoom
+if exist(options,'basin');
+	basinzoom(options);
+end
+
+%ShowBasins
+if strcmpi(getfieldvalue(options,'showbasins','off'),'on')
+	showbasins(options);
+end
+
+%Caxis
+if exist(options,'caxis'),
+	caxis(getfieldvalue(options,'caxis'));
+end
+
+%shading
+if exist(options,'shading'),
+	shading(getfieldvalue(options,'shading'));
+end
+
+%grid
+if exist(options,'grid'),
+	if strcmpi(getfieldvalue(options,'grid'),'on'),
+		grid on;
+	end
+end
+
+%colormap
+c = getcolormap(options);
+h = colormap(c);
+
+%wrapping
+if exist(options,'wrapping'),
+	if ~exist(options,'colormap'),
+		h=jet;
+	end
+	colormap(repmat(h,getfieldvalue(options,'wrapping',1),1));
+end
+
+%colorbar
+if getfieldvalue(options,'colorbar',1)==1,
+	if exist(options,'colorbarcornerposition'),
+		c=colorbar(getfieldvalue(options,'colorbarcornerposition'),'peer',gca);
+	else 
+		c=colorbar('peer',gca);
+	end
+	set(c,'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'YColor',getfieldvalue(options,'FontColor','k'));
+	if exist(options,'wrapping')
+		lim=get(c,'Ylim');
+		lim=[lim(1) lim(1)+(lim(2)-lim(1))/getfieldvalue(options,'wrapping')];
+		set(c,'Ylim',lim);
+	end
+	if exist(options,'colorbarpos'),
+		set(c,'Position',getfieldvalue(options,'colorbarpos'));
+	end
+	if exist(options,'log'),
+		nlab=5;
+		logvalue=getfieldvalue(options,'log');
+
+		scaleminmax=caxis;
+		Min=min(scaleminmax);
+		Max=max(scaleminmax);
+		set(c,'YLim',[Min Max]); % set colorbar limits
+		set(c,'YTick',linspace(Min,Max,nlab));     % set tick mark locations
+
+		labels = cell(1,nlab);
+		tick_vals = linspace(Min,Max,nlab);
+		tick_vals = exp(log(logvalue)*tick_vals);
+		warning off MATLAB:log:logOfZero;
+		for i = 1:nlab
+			labels{i} = sprintf('%-3.4g',round_ice(tick_vals(i),2));
+			%labels{i} = sprintf('%-.4g',round_ice(tick_vals(i),2));
+		end
+		warning on MATLAB:log:logOfZero;
+		set(c,'YTickLabel',labels);
+	end 
+ 	if exist(options,'cbYLim'); 
+		set(c,'YLim',getfieldvalue(options,'cbYLim'));
+	end
+	if exist(options,'colorbartitle'),
+		set(get(c,'title'),'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'String',getfieldvalue(options,'colorbartitle'),...
+			'Color',getfieldvalue(options,'FontColor','k'));
+	end
+	if exist(options,'colorbarYLabel'),
+		set(get(c,'Ylabel'),'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'String',getfieldvalue(options,'colorbarYLabel'),...
+			'Color',getfieldvalue(options,'FontColor','k'),'Interpreter',getfieldvalue(options,'Interpreter','none'));
+	end
+	if exist(options,'colorbarwidth'),
+		posaxes=get(gca,'Position');
+		alpha=getfieldvalue(options,'colorbarwidth',1);
+		position=get(c,'Position');
+		dx=position(3);
+		newdx=dx*alpha;
+		position(1)=position(1)+(dx-newdx)/2;
+		position(3)=newdx;
+		set(c,'Position',position);
+		set(gca,'Position',posaxes);
+	end
+	if exist(options,'colorbarheight'),
+		posaxes=get(gca,'Position');
+		alpha=getfieldvalue(options,'colorbarheight',1);
+		position=get(c,'Position');
+		dy=position(4);
+		newdy=dy*alpha;
+		position(2)=position(2)+(dy-newdy)/2;
+		position(4)=newdy;
+		set(c,'Position',position);
+		set(gca,'Position',posaxes);
+	end
+	if exist(options,'cbYTickLabel');
+		tick_vals=getfieldvalue(options,'cbYTickLabel');
+		if ~isnumeric(tick_vals) & strcmp(tick_vals,'on')
+			tick_vals=get(c,'YTick')';
+			if exist(options,'log')
+				logval= getfieldvalue(options,'log');
+				for i= 1:size(tick_vals,1)
+					tick_vals(i)= logval^(tick_vals(i));
+				end
+			elseif size(tick_vals,1) == 3
+				tick_vals=[tick_vals(1); mean(tick_vals(1:2)); tick_vals(2); ...
+					mean(tick_vals(2:3)); tick_vals(3)];
+				set(c,'YTick',tick_vals);
+			end
+		end
+		labels = cell(1,size(tick_vals,1));
+		for i = 1:size(tick_vals,1)
+			labels{i} = sprintf('%-3.4g',round_ice(tick_vals(i),2));
+		end
+		set(c,'YTickLabel',labels);
+	end
+
+elseif getfieldvalue(options,'colorbar',1)==0,
+	colorbar('off');
+else
+	%do nothing
+	
+end
+
+
+%area
+if exist(options,'area'),
+	antzoom(getfieldvalue(options,'area'));
+end
+
+%expdisp
+filename=(getfieldvalue(options,'expdisp'));
+style=(getfieldvalue(options,'expstyle'));
+for i=1:length(getfieldvalue(options,'expdisp')),
+	filenamei=filename{i};
+	stylei=style{i};
+	expdisp(filenamei,gcf,stylei,getfieldvalue(options,'linewidth',1),getfieldvalue(options,'unit',1));
+end
+
+%text (default value is empty, not NaN...)
+if exist(options,'text');
+	textstring=getfieldvalue(options,'text');
+	textweight=getfieldvalue(options,'textweight','b');
+	textsize=getfieldvalue(options,'textsize');
+	textcolor=getfieldvalue(options,'textcolor');
+	textposition=getfieldvalue(options,'textposition');
+	textrotation=getfieldvalue(options,'textrotation');
+	for i=1:length(getfieldvalue(options,'text'));
+		textstringi=textstring{i};
+		textweighti=textweight{i};
+		textsizei=textsize{i};
+		textcolori=textcolor{i};
+		textpositioni=textposition{i};
+		textrotationi=textrotation{i};
+		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
+end
+
+%north arrow
+if exist(options,'northarrow'),
+	northarrow(getfieldvalue(options,'northarrow'));
+end
+
+%Scale ruler
+if exist(options,'scaleruler'),
+	scaleruler(options);
+end
+
+%streamliness
+if exist(options,'streamlines'),
+	plot_streamlines(md,options);
+end
+
+%contours
+if exist(options,'contourlevels'),
+	plot_contour(md,data,options);
+end
+
+%YTickLabel
+if exist(options,'yticklabel'),
+	set(gca,'YTickLabel',getfieldvalue(options,'YTickLabel'));
+end
+
+%XTickLabel
+if exist(options,'xticklabel'),
+	set(gca,'XTickLabel',getfieldvalue(options,'XTickLabel'));
+end
+
+%xtick
+if exist(options,'xtick'),
+	set(gca,'xtick',getfieldvalue(options,'xtick'));
+end
+
+%ytick
+if exist(options,'ytick'),
+	set(gca,'ytick',getfieldvalue(options,'ytick'));
+end
+
+%Axis positions
+if exist(options,'offsetaxispos'),
+	offset=getfieldvalue(options,'offsetaxispos');
+	P=get(gca,'pos');
+	P(1)=P(1)+offset(1);
+	P(2)=P(2)+offset(2);
+	P(3)=P(3)+offset(3);
+	P(3)=P(4)+offset(4);
+	set(gca,'pos',P);
+end
+if exist(options,'axispos'),
+	Axis=getfieldvalue(options,'axispos');
+	hold on
+	set(gca,'pos',Axis);
+end
+
+
+%position of figure
+if exist(options,'figposition'),
+	
+	figposition=getfieldvalue(options,'figposition');
+	if ischar(figposition),
+		if strcmpi(figposition,'larour'),
+			set(gcf,'Position',[1604 4 1594 1177]);
+		elseif strcmpi(figposition,'larour2'),
+			set(gcf,'Position',[756    62   827   504]);
+		elseif strcmpi(figposition,'mathieu'),
+			set(gcf,'Position',[300 1 1580 1150]);
+		elseif strcmpi(figposition,'fullscreen'),
+			set(gcf,'Position',get(0,'ScreenSize'));
+		elseif strcmpi(figposition,'halfright'),
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+			set(gcf,'Position',fix([left+widt/2 bott widt/2 heig]));
+		elseif strcmpi(figposition,'halfleft'),
+			screen=get(0,'ScreenSize');
+			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")
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+			portrait=fix([left+widt-(heig*8.5/11) bott heig*8.5/11 heig]);
+			set(gcf,'Position',portrait)
+		elseif strcmpi(figposition,'landscape'),
+			%reformat with letter paper size (8.5" x 11")
+			screen=get(0,'ScreenSize');
+			left=screen(1); bott=screen(2); widt=screen(3); heig=screen(4)-25;
+			landscape=fix([left+widt-(heig*11/8.5) bott heig*11/8.5 heig]);
+			set(gcf,'Position',landscape)
+		else
+			disp('''figposition'' string not supported yet');
+		end
+	else
+		set(gcf,'Position',figposition);
+	end
+
+end
+
+%axes position
+if exist(options,'axesPosition')
+	set(gca,'Position',getfieldvalue(options,'axesPosition'));
+end
+
+%showregion
+if strcmpi(getfieldvalue(options,'showregion','off'),'on'),
+	%Keep pointer of main axis
+	maingca=gca;
+	%get inset relative position (x,y,width,height)
+	insetpos=getfieldvalue(options,'insetpos',[0.02 0.70 0.18 0.18]);
+	%get current plos position
+	cplotpos=get(maingca,'pos');
+	%compute inset position
+	PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
+	axes('pos',PosInset);
+	axis equal off
+	%box off
+	if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
+		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']);
+	else
+		error('applyoptions error message: hemisphere not defined');
+	end
+	offset=3*10^4;
+	Ax=[min(A.x)-offset max(A.x)+offset];
+	Ay=[min(A.y)-offset max(A.y)+offset];
+	%if we are zooming on a basin, don't take the mesh for the boundaries!
+	if exist(options,'basin'),
+		[mdx mdy]=basinzoom(options);
+	else
+		mdx=[min(md.mesh.x)-offset max(md.mesh.x)+offset];
+		mdy=[min(md.mesh.y)-offset max(md.mesh.y)+offset];
+	end
+	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)
+	colorbar('off');
+	%back to main gca
+	set(gcf,'CurrentAxes',maingca)
+end
+
+%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
+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
+
+%backgroundcolor
+set(gca,'color',getfieldvalue(options,'backgroundcolor','none'));
+
+%figurebackgrounbcolor
+set(gcf,'color',getfieldvalue(options,'figurebackgroundcolor','w'));
+
+%lighting
+if strcmpi(getfieldvalue(options,'light','off'),'on'),
+	set(gca,'FaceLighting','gouraud','FaceColor','interp','AmbientStrength',0.5);
+	light('Position',[0 0.1 0.1],'Style','infinite');
+end
+
+%cloud of points: 
+if exist(options,'cloud'),
+	field=getfieldvalue(options,'cloud');
+	x=field(:,1);
+	y=field(:,2);
+	%unit multiplier:
+	if exist(options,'unit'),
+		unit=getfieldvalue(options,'unit');
+		x=x*unit;
+		y=y*unit;
+	end
+	hold on,p=plot(x,y,'k.');
+	markersize=getfieldvalue(options,'markersize',5);
+	color=getfieldvalue(options,'cloudcolor','k');
+	set(p,'Color',color);
+end
+
+%========================%
+%OK VERY LAST STEP: INSET|
+%========================%
+if exist(options,'inset'),
+
+	%Keep pointer of main axis
+	maingca=gca;
+	%get inset relative position (x,y,width,height)
+	insetpos=getfieldvalue(options,'insetpos',[0.56 0.55 0.35 0.35]);
+	%get current plot position
+	cplotpos=get(gca,'pos');
+	%compute inset position
+	PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
+	%show pos
+	X1=getfieldvalue(options,'insetx',xlim);
+	Y1=getfieldvalue(options,'insety',ylim);
+	if strcmpi(getfieldvalue(options,'showinset','off'),'on')
+		line(X1([1 2 2 1 1]),Y1([1 1 2 2 1]),zeros(1,5),'Color','k','LineWidth',2);
+	end
+
+	%Get current figure
+	ax1=gca;
+
+	%plot inset
+	axes('pos',PosInset);
+	copyobj(get(ax1,'children'),gca);
+	patch('Faces',[1 2 3 4 1],'Vertices',[X1([1 2 2 1])' Y1([1 1 2 2])'],'FaceColor','None','EdgeColor','k','LineWidth',2);
+
+	%applay options
+	options=removefield(options,'text',0);
+	options=removefield(options,'title',0);
+	options=removefield(options,'xlabel',0);
+	options=removefield(options,'ylabel',0);
+	options=removefield(options,'inset',0);
+	options=removefield(options,'offsetaxispos',0);
+	options=removefield(options,'showregion',0);
+	options=changefieldvalue(options,'colorbar',0);
+	options=changefieldvalue(options,'latlon','off');
+	options=changefieldvalue(options,'axis','equal off');
+	options=changefieldvalue(options,'xlim',getfieldvalue(options,'insetx',xlim));
+	options=changefieldvalue(options,'ylim',getfieldvalue(options,'insety',ylim));
+	applyoptions(md,data,options);
+
+	%back to main gca
+	set(gcf,'CurrentAxes',maingca)
+end
Index: /issm/trunk/src/m/plot/arrow.m
===================================================================
--- /issm/trunk/src/m/plot/arrow.m	(revision 13395)
+++ /issm/trunk/src/m/plot/arrow.m	(revision 13395)
@@ -0,0 +1,60 @@
+function arrow(x0,y0,x1,y1,varargin)
+%ARROW - plot arrow, using (x0,y0) and (x1,y1) as initial and end points. options can be specified.
+%
+%   Usage:
+%      arrow(x1,y1,x2,y2,options)
+%      where options is a lit of paired arguments of string OR enums
+%      options can be: 
+%            'ratio': default .5 (ratio headarrow/length)
+%            'widthratio': default is 1/10 of length
+
+
+%recover options
+options=pairoptions(varargin{:});
+ratio=getfieldvalue(options,'ratio',.5);
+widthratio=getfieldvalue(options,'widthratio',.1);
+color=getfieldvalue(options,'color','k');
+
+%compute some values out of (x1,y1) and (x2,y2)
+length=sqrt((x1-x0)^2+(y1-y0)^2);
+width=length*widthratio;
+
+%Build the two points Ap and Bp
+x=zeros(2,1);
+y=zeros(2,1);
+x(1)=x0; y(1)=y0;
+x(2)=x1; y(2)=y1;
+
+Ap=[x(1)
+   y(1)];
+Bp=[x(2)
+   y(2)];
+
+%Build arrowhead first
+ang2=150*2*pi/360;
+rotation=[cos(ang2), sin(ang2); -sin(ang2), cos(ang2)];
+
+E=ratio*rotation*(Bp-Ap)+Bp;
+F=Bp;
+G=ratio*rotation'*(Bp-Ap)+Bp;
+H=Bp/4+E*3/8+G*3/8;
+
+%Build rectangle
+u=Bp-Ap;
+alpha=atan2(u(2),u(1));
+
+A=Ap-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+ B=H-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+C=H+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+D=Ap+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+
+%Plot arrow
+hold on
+p1=patch([A(1) B(1) C(1) D(1)],[A(2) B(2) C(2) D(2)],color);
+set(p1,'EdgeColor',color); set(p1,'FaceColor',color);
+p2=patch([E(1) F(1) G(1) H(1)],[E(2) F(2) G(2) H(2)],color);
+set(p2,'EdgeColor',color); set(p2,'FaceColor',color);
Index: /issm/trunk/src/m/plot/checkplotoptions.m
===================================================================
--- /issm/trunk/src/m/plot/checkplotoptions.m	(revision 13395)
+++ /issm/trunk/src/m/plot/checkplotoptions.m	(revision 13395)
@@ -0,0 +1,206 @@
+function options=checkplotoptions(md,options);
+%PARSE_OPTIONS - build a structure that holds all plot options
+%
+%   Usage:
+%      options=checkplotoptions(md,options);
+%
+%   See also: PLOTMODEL
+
+%units
+if exist(options,'unit'),
+	if strcmpi(getfieldvalue(options,'unit'),'km')
+		options=changefieldvalue(options,'unit',10^-3);
+	end
+	if strcmpi(getfieldvalue(options,'unit'),'100km')
+		options=changefieldvalue(options,'unit',10^-5);
+	end
+
+end
+
+%density
+if exist(options,'density'),
+	density=getfieldvalue(options,'density');
+	options=changefieldvalue(options,'density',abs(ceil(density)));
+end
+
+%Show section
+if exist(options,'showsection'),
+	if strcmpi(getfieldvalue(options,'showsection'),'on')
+		options=changefieldvalue(options,'showsection',4);
+	end
+end
+
+%smooth values
+if exist(options,'smooth'),
+	if strcmpi(getfieldvalue(options,'smooth'),'on')
+		options=changefieldvalue(options,'smooth',0);
+	end
+end
+
+%contouronly values
+if exist(options,'contouronly'),
+	if strcmpi(getfieldvalue(options,'contouronly'),'on')
+		options=changefieldvalue(options,'contouronly',1);
+	end
+end
+
+%Colorbar;
+if exist(options,'colorbar'),
+	if strcmpi(getfieldvalue(options,'colorbar'),'on')
+		options=changefieldvalue(options,'colorbar',1);
+	elseif strcmpi(getfieldvalue(options,'colorbar'),'off')
+			options=changefieldvalue(options,'colorbar',0);
+	end
+end
+	
+%text
+if exist(options,'text'),
+	%1: textvalue
+	textvalues=getfieldvalue(options,'text');
+	%ischar if only one expstyle -> create a cell
+	if ischar(textvalues),
+		textvalues={textvalues};
+		numtext=1;
+	elseif iscell(textvalues),
+		numtext=length(textvalues);
+	else
+		error('plot error message: ''text'' option should be either a string or a cell');
+	end
+
+	%2: textweight
+	if exist(options,'textweight'),
+		textweightvalues=getfieldvalue(options,'textweight');
+		%ischar if only one textweight -> create a cell
+		if ischar(textweightvalues),
+			textweightvalues={textweightvalues};
+		elseif ~iscell(textweightvalues);
+			error('plot error message: ''textweight'' option should be either a string or a cell');
+		end
+	else
+		textweightvalues={'n'};
+	end
+	textweightvalues=repmat(textweightvalues,1,numtext); textweightvalues(numtext+1:end)=[];
+	%3: textsize
+	if exist(options,'textsize'),
+		textsizevalues=getfieldvalue(options,'textsize');
+		%ischar if only one textsize -> create a cell
+		if isnumeric(textsizevalues),
+			textsizevalues={textsizevalues};
+		elseif ~iscell(textsizevalues);
+			error('plot error message: ''textsize'' option should be either a number or a cell');
+		end
+	else
+		textsizevalues={14};
+	end
+	textsizevalues=repmat(textsizevalues,1,numtext); textsizevalues(numtext+1:end)=[];
+	%4: textcolor
+	if exist(options,'textcolor'),
+		textcolorvalues=getfieldvalue(options,'textcolor');
+		%ischar if only one textcolor -> create a cell
+		if ischar(textcolorvalues),
+			textcolorvalues={textcolorvalues};
+		elseif ~iscell(textcolorvalues);
+			error('plot error message: ''textcolor'' option should be either a string or a cell');
+		end
+	else
+		textcolorvalues={'k'};
+	end
+	textcolorvalues=repmat(textcolorvalues,1,numtext); textcolorvalues(numtext+1:end)=[];
+	%4: textposition
+	if exist(options,'textposition'),
+		textpositionvalues=getfieldvalue(options,'textposition');
+		%ischar if only one textposition -> create a cell
+		if isnumeric(textpositionvalues),
+			textpositionvalues={textpositionvalues};
+		elseif ~iscell(textpositionvalues);
+			error('plot error message: ''textposition'' option should be either a string or a cell');
+		end
+	else
+		error('plot error message: ''textposition'' option is missing');
+	end
+	%6: textrotation
+	if exist(options,'textrotation'),
+		textrotationvalues=getfieldvalue(options,'textrotation');
+		%ischar if only one textsize -> create a cell
+		if isnumeric(textrotationvalues),
+			textrotationvalues={textrotationvalues};
+		elseif ~iscell(textrotationvalues);
+			error('plot error message: ''textrotation'' option should be either a number or a cell');
+		end
+	else
+		textrotationvalues={0};
+	end
+	textrotationvalues=repmat(textrotationvalues,1,numtext); textrotationvalues(numtext+1:end)=[];
+	options=changefieldvalue(options,'text',textvalues);
+	options=changefieldvalue(options,'textsize',textsizevalues);
+	options=changefieldvalue(options,'textweight',textweightvalues);
+	options=changefieldvalue(options,'textcolor',textcolorvalues);
+	options=changefieldvalue(options,'textposition',textpositionvalues);
+	options=changefieldvalue(options,'textrotation',textrotationvalues);
+end
+
+%expdisp
+expdispvaluesarray=cell(0,0);
+expstylevaluesarray=cell(0,0);
+expstylevalues=cell(0,0);
+if exist(options,'expstyle'),
+	expstylevalues=getfieldvalue(options,'expstyle');
+	%ischar if only one expstyle -> create a cell
+	if ischar(expstylevalues),
+		expstylevalues={expstylevalues};
+	end
+end
+if exist(options,'expdisp'),
+	expdispvalues=getfieldvalue(options,'expdisp');
+	%ischar if only one expstyle -> create a cell
+	if ischar(expdispvalues),
+		expdispvalues={expdispvalues};
+	end
+	for i=1:length(expdispvalues)
+		expdispvaluesarray{end+1}=expdispvalues{i};
+		if (length(expstylevalues)>=i),
+			expstylevaluesarray{end+1}=expstylevalues{i};
+		else
+			expstylevaluesarray{end+1}='g-';
+		end
+	end
+end
+options=changefieldvalue(options,'expstyle',expstylevaluesarray);
+options=changefieldvalue(options,'expdisp',expdispvaluesarray);
+
+%latlonnumbering
+if exist(options,'latlonclick'),
+	if strcmpi(getfieldvalue(options,'latlonclick'),'on')
+		options=changefieldvalue(options,'latlonclick',1);
+	end
+end
+
+%north arrow
+if exist(options,'northarrow'),
+	if strcmpi(getfieldvalue(options,'northarrow'),'on')
+		%default values
+		Lx=max(md.mesh.y)-min(md.mesh.y);
+		Ly=max(md.mesh.y)-min(md.mesh.y);
+		%default values
+		options=changefieldvalue(options,'northarrow',[min(md.mesh.x)+1/6*Lx   min(md.mesh.y)+5/6*Ly   1/15*Ly   0.25   1/250*Ly]);
+	end
+end
+
+%scale ruler
+if exist(options,'scaleruler'),
+	if strcmpi(getfieldvalue(options,'scaleruler'),'on')
+		%default values
+		Lx=max(md.mesh.y)-min(md.mesh.y);
+		Ly=max(md.mesh.y)-min(md.mesh.y);
+		%default values
+		options=changefieldvalue(options,'scaleruler',[min(md.mesh.x)+6/8*Lx   min(md.mesh.y)+1/10*Ly   10^(ceil(log10(Lx)))/5 floor(Lx/100) 5]);
+	end
+end
+
+%Log scale (LOTS of changes to be performed
+if exist(options,'log'),
+	if exist(options,'caxis')
+		options=changefieldvalue(options,'caxis',log(getfieldvalue(options,'caxis'))/log(getfieldvalue(options,'log')));
+	end
+	options=changefieldvalue(options,'cutoff',log(getfieldvalue(options,'cutoff',1.5))/log(getfieldvalue(options,'log')));
+end
Index: /issm/trunk/src/m/plot/colormaps/getcolormap.m
===================================================================
--- /issm/trunk/src/m/plot/colormaps/getcolormap.m	(revision 13395)
+++ /issm/trunk/src/m/plot/colormaps/getcolormap.m	(revision 13395)
@@ -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;
+	map = map(128:end,:);
+elseif strcmpi(map,'redblue'),
+	map = hsv;
+	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;
+	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;
+	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;
+	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/trunk/src/m/plot/colormaps/haxby.m
===================================================================
--- /issm/trunk/src/m/plot/colormaps/haxby.m	(revision 13395)
+++ /issm/trunk/src/m/plot/colormaps/haxby.m	(revision 13395)
@@ -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/trunk/src/m/plot/colormaps/lbmap.m
===================================================================
--- /issm/trunk/src/m/plot/colormaps/lbmap.m	(revision 13395)
+++ /issm/trunk/src/m/plot/colormaps/lbmap.m	(revision 13395)
@@ -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/trunk/src/m/plot/kmlgroundoverlay.m
===================================================================
--- /issm/trunk/src/m/plot/kmlgroundoverlay.m	(revision 13395)
+++ /issm/trunk/src/m/plot/kmlgroundoverlay.m	(revision 13395)
@@ -0,0 +1,61 @@
+function kmlgroundoverlay(md,options);
+%KMLGROUNDOVERLAY: create ground overlay image in kml format
+%
+%
+%    options: 
+%         kmlfilename
+%         imagename
+%
+%    Usage: 
+%         kmlgroundoverlay(md,'kmlfilename','temp.kml','imagename','greenland.jpeg');
+%
+
+%first figure out if lat and long were computed!
+if (isempty(md.mesh.lat) | isempty(md.mesh.long)),
+	error('kmlgroundoverlay error message: project x,y onto lat,long fields of model!');
+end
+
+%process kml options
+kmlfilename=getfieldvalue(options,'kmlfilename','tempfile.kml');
+kmlroot=getfieldvalue(options,'kmlroot','./');
+kmlimagename=getfieldvalue(options,'kmlimagename','tempimage');
+kmlimagetype=getfieldvalue(options,'kmlimagetype','png');
+kmlresolution=getfieldvalue(options,'kmlresolution',1);
+kmlfolder=getfieldvalue(options,'kmlfolder','Ground Overlay');
+kmlfolderdescription=getfieldvalue(options,'kmlfolderdescription','');
+kmlgroundoverlayname=getfieldvalue(options,'kmlgroundoverlayname','');
+kmlgroundoverlaydescription=getfieldvalue(options,'kmlgroundoverlaydescription','');
+
+%figure out  min and max for lat and long of this image:
+west=min(md.mesh.long);
+east=max(md.mesh.long);
+south=min(md.mesh.lat);
+north=max(md.mesh.lat);
+
+%print image at high resolution
+printmodel([kmlroot '/' kmlimagename],kmlimagetype,'trim','on','resolution',kmlresolution,'margin','off','frame','off');
+
+%now write kml file
+fid=fopen([kmlroot '/' kmlfilename],'w');
+
+fprintf(fid,'%s\n','<?xml version="1.0" encoding="UTF-8"?>');
+fprintf(fid,'%s\n','<kml xmlns="http://www.opengis.net/kml/2.2">');
+fprintf(fid,'%s\n','<Folder>');
+fprintf(fid,'%s%s%s\n','<name>',kmlfolder,'</name>');
+fprintf(fid,'%s%s%s\n','<description>',kmlfolderdescription,'</description>');
+fprintf(fid,'%s\n','<GroundOverlay>');
+fprintf(fid,'%s%s%s\n','<name>',kmlgroundoverlayname,'</name>');
+fprintf(fid,'%s\n','<description>',kmlgroundoverlaydescription,'</description>');
+fprintf(fid,'%s%s.%s%s\n','<Icon>',kmlimagename,kmlimagetype,'</Icon>');
+fprintf(fid,'%s\n','<LatLonBox>');
+fprintf(fid,'%s%f%s\n','<north>',north,'</north>');
+fprintf(fid,'%s%f%s\n','<south>',south,'</south>');
+fprintf(fid,'%s%f%s\n','<east>',east,'</east>');
+fprintf(fid,'%s%f%s\n','<west>',west,'</west>');
+fprintf(fid,'%s\n','<rotation>0</rotation>');
+fprintf(fid,'%s\n','</LatLonBox>');
+fprintf(fid,'%s\n','</GroundOverlay>');
+fprintf(fid,'%s\n','</Folder>');
+fprintf(fid,'%s\n','</kml>');
+
+fclose(fid);
Index: /issm/trunk/src/m/plot/latlonoverlay.m
===================================================================
--- /issm/trunk/src/m/plot/latlonoverlay.m	(revision 13395)
+++ /issm/trunk/src/m/plot/latlonoverlay.m	(revision 13395)
@@ -0,0 +1,149 @@
+function latlonoverlay(md,options)
+%LATLONOVERLAY - overlay latitude and longitude lines on current figure
+%
+%   latstep,lonstep, in latitude and longitude degreees, between two latitudinal, longitudinal profiles.
+%   color: [1 1 1] for example
+%   resolution: profile resolution ( in lat,lon degrees) 
+%   gap: gap (in meters) to plug lat,lon degree numbers;
+%
+%   Usage:
+%      latlonoverlay(options)
+
+%get options
+latlon=getfieldvalue(options,'latlon');
+numbering=getfieldvalue(options,'latlonnumbering','off');
+latlonclick=getfieldvalue(options,'latlonclick',0);
+fontsize=getfieldvalue(options,'fontsize',16);
+
+%recover arguments (set default parameters if needed)
+%1: latlon
+if ~iscell(latlon),
+	if ischar(latlon) & strcmpi(latlon,'on'),
+		%defaults
+		latstep=3; lonstep=3;
+		resolution=0.1;
+		color=[1 0 1];
+	else return; end
+else
+	if length(latlon)<2
+		error('latlonoverlay error message: at least 2 arguments are required, or use ''on'' option.');
+	end
+	if length(latlon)>3, color=latlon{4};      else color=[1 1 1]; end
+	if length(latlon)>2, resolution=latlon{3}; else resolution=0.1;end
+	latstep=latlon{1};
+	lonstep=latlon{2};
+end
+
+%2: numbering
+if ~iscell(numbering) & isnan(numbering),
+	numbering=false;
+else
+	if ~iscell(numbering),
+		if strcmpi(char(numbering),'on'),
+			%defaults
+			latgap=2; longap=2;
+			colornumber=color;
+			latangle=0; lonangle=0;
+			numbering=true;
+		else
+			numbering=false;
+		end
+	else
+		latgap=numbering{1}; longap=numbering{2};
+		colornumber=numbering{3};
+		latangle=numbering{4}; lonangle=numbering{5};
+		numbering=true;
+	end
+end
+
+%what are the x and y limits
+xlimits=getfieldvalue(options,'xlim',xlim);
+ylimits=getfieldvalue(options,'ylim',ylim);
+
+%lat
+for lat=-90:latstep:90
+	longitudes=0:resolution:360;
+	latitudes =lat*ones(size(longitudes));
+
+	if strcmpi(md.mesh.hemisphere,'n'),
+		if lat<0, continue; end
+		[x,y]=ll2xy(latitudes,longitudes,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		if lat>0, continue; end
+		[x,y]=ll2xy(latitudes,longitudes,-1, 0,71);
+	else error('field hemisphere should either be ''n'' or ''s'''); end
+
+	pos=find(x<=xlimits(2) & x>=xlimits(1) & y<=ylimits(2) & y>=ylimits(1));
+	if length(pos)<=1, continue; end
+	x=x(pos);y=y(pos);
+	l=line(x,y,'Color',color);
+
+	if numbering
+		ind=length(x)-2*latgap;
+		if (ind<=0), continue; end
+		xcorner=x(ind);            ycorner=y(ind);
+		xcorner2=x(max(ind-10,1)); ycorner2=y(max(ind-10,1));
+
+		if (xcorner>xlimits(1) & xcorner<xlimits(2) & ycorner>ylimits(1) & ycorner<ylimits(2)),
+			angle=mod((180)/pi*atan2((ycorner2-ycorner),(xcorner2-xcorner))+latangle,360);
+			if lat<0, label=[num2str(abs(lat)) '^{\circ}S'];
+			else      label=[num2str(abs(lat)) '^{\circ}N']; end
+			th=text(xcorner,ycorner,label);
+			set(th,'Color',colornumber,'Rotation',angle,'FontSize',fontsize,'HorizontalAlignment','center','VerticalAlignment','middle','Clipping','on');
+
+			%erase line and redraw it in two parts, to leave space for latitude number
+			delete(l);
+			line(x(1:ind-latgap),y(1:ind-latgap),'Color',color);hold on;
+			line(x(ind+latgap:end),y(ind+latgap:end),'Color',color);
+			set(gcf,'InvertHardcopy','off');
+		end
+
+	end
+end
+
+%lon
+for lon=-180:lonstep:180
+
+	if strcmpi(md.mesh.hemisphere,'n'),
+		latitudes =0:resolution:90;
+		longitudes=lon*ones(size(latitudes));
+		[x,y]=ll2xy(latitudes,longitudes,+1,45,70);
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		latitudes =-90:resolution:0;
+		longitudes=lon*ones(size(latitudes));
+		[x,y]=ll2xy(latitudes,longitudes,-1, 0,71);
+	else
+		error('field hemisphere should either be ''n'' or ''s'''); 
+	end
+
+
+	pos=find(x<=xlimits(2) & x>=xlimits(1) & y<=ylimits(2) & y>=ylimits(1));
+	if length(pos)<=1, continue; end
+	x=x(pos);y=y(pos);
+	l=line(x,y,'Color',color);
+
+	if numbering,
+		ind=length(x)-2*longap;
+		if (ind<=0), continue; end
+		xcorner=x(ind);            ycorner=y(ind);
+		xcorner2=x(max(ind-10,1)); ycorner2=y(max(ind-10,1));
+
+		if (xcorner>xlimits(1) & xcorner<xlimits(2) & ycorner>ylimits(1) & ycorner<ylimits(2)),
+			angle=mod((180)/pi*atan2((ycorner2-ycorner),(xcorner2-xcorner))+lonangle,360);
+			if lon<0, label=[num2str(abs(lon)) '^{\circ}W'];
+			else      label=[num2str(abs(lon)) '^{\circ}E']; end
+			th=text(xcorner,ycorner,label);
+			set(th,'Color',colornumber,'Rotation',angle,'FontSize',fontsize,'HorizontalAlignment','center','VerticalAlignment','middle','Clipping','on');
+
+			%erase line and redraw it in two parts, to leave space for latitude number
+			delete(l);
+			line(x(1:ind-longap),y(1:ind-longap),'Color',color);hold on;
+			line(x(ind+longap:end),y(ind+longap:end),'Color',color);
+		end
+
+	end
+end
+
+%Back to original limits
+xlim(xlimits);
+ylim(ylimits);
Index: /issm/trunk/src/m/plot/northarrow.m
===================================================================
--- /issm/trunk/src/m/plot/northarrow.m	(revision 13395)
+++ /issm/trunk/src/m/plot/northarrow.m	(revision 13395)
@@ -0,0 +1,76 @@
+function northarrow(structure)
+%NORTHARROW - overlay an arrow pointing north on the current plot
+%
+%   Usage:
+%      northarrow(structure)
+
+%Go through structure and fill missing arguments
+if length(structure)<3
+	error('plotmodel error message: the position or the length of the North arrow is missing');
+elseif length(structure)==3
+	structure(4)=0.5; %default ratio headarrow/length
+	structure(5)=structure(3)/10; %default width =length/10
+elseif length(structure)==4
+	structure(5)=structure(3)/10; %default width =length/10
+elseif length(structure)==5
+	structure(6)=16; %default fontsize
+elseif length(structure)>6
+	error('plotmodel error message: to many input arguments for northarrow: [x0 y0 length [ratio width fontsize]]');
+end
+
+%retrieve north arrow parameters
+x0=structure(1);
+y0=structure(2);
+lengtharrow=structure(3);
+ratio=structure(4);
+width=structure(5);
+fontsize=structure(6);
+
+%Figure out angle to point towards north
+ang=atan2(y0,x0);
+
+%Build the two points Ap and Bp
+x=zeros(2,1);
+y=zeros(2,1);
+x(1)=x0;
+y(1)=y0;
+
+x(2)=x(1)+lengtharrow*cos(ang);
+y(2)=y(1)+lengtharrow*sin(ang);
+
+Ap=[x(1)
+   y(1)];
+Bp=[x(2)
+   y(2)];
+
+%Build arrowhead first
+ang2=150*2*pi/360;
+rotation=[cos(ang2), sin(ang2); -sin(ang2), cos(ang2)];
+
+E=ratio*rotation*(Bp-Ap)+Bp;
+F=Bp;
+G=ratio*rotation'*(Bp-Ap)+Bp;
+H=Bp/4+E*3/8+G*3/8;
+
+%Build rectangle
+u=Bp-Ap;
+alpha=atan2(u(2),u(1));
+
+A=Ap-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+ B=H-[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+C=H+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+D=Ap+[-width/2*sin(alpha)
+   width/2*cos(alpha)];
+
+%Plot arrow
+hold on
+p1=patch([A(1) B(1) C(1) D(1)],[A(2) B(2) C(2) D(2)],'Black');
+p2=patch([E(1) F(1) G(1) H(1)],[E(2) F(2) G(2) H(2)],'Black');
+
+%Text North
+xN=max([A(1) D(1) E(1) F(1) G(1)])+ratio/3*abs(lengtharrow);
+yN=mean([A(2) F(2) H(2)]);
+text(xN,yN,'North','FontSize',fontsize,'FontWeight','b');
Index: /issm/trunk/src/m/plot/plot_BC.m
===================================================================
--- /issm/trunk/src/m/plot/plot_BC.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_BC.m	(revision 13395)
@@ -0,0 +1,41 @@
+function plot_BC(md,options,width,i,data);
+
+%plot neuman
+plot_icefront(md,options,width,i,data)
+
+hold on
+
+%plot dirichlets
+h1=plot3(...
+	md.mesh.x(find(~isnan(md.diagnostic.spcvx(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.y(find(~isnan(md.diagnostic.spcvx(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.z(find(~isnan(md.diagnostic.spcvx(1:md.mesh.numberofvertices,1)))),...
+	'ro','MarkerSize',14,'MarkerFaceColor','r');
+h2=plot3(...
+	md.mesh.x(find(~isnan(md.diagnostic.spcvy(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.y(find(~isnan(md.diagnostic.spcvy(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.z(find(~isnan(md.diagnostic.spcvy(1:md.mesh.numberofvertices,1)))),...
+	'bo','MarkerSize',10,'MarkerFaceColor','b');
+h3=plot3(...
+	md.mesh.x(find(~isnan(md.diagnostic.spcvz(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.y(find(~isnan(md.diagnostic.spcvz(1:md.mesh.numberofvertices,1)))),...
+	md.mesh.z(find(~isnan(md.diagnostic.spcvz(1:md.mesh.numberofvertices,1)))),...
+	'yo','MarkerSize',6 ,'MarkerFaceColor','y');
+
+%update legend
+[legend_h,object_h,plot_h,text_strings]=legend();
+legend('off');
+text_strings{end+1}='vx Dirichlet';
+text_strings{end+1}='vy Dirichlet';
+if h3, text_strings{end+1}='vz Dirichlet'; end
+plot_h(end+1)=h1;
+plot_h(end+1)=h2;
+if h3, plot_h(end+1)=h3; end
+legend(plot_h,text_strings,'location','NorthEast')
+
+hold off
+
+%apply options
+options=addfielddefault(options,'title','Boundary conditions');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_basaldrag.m
===================================================================
--- /issm/trunk/src/m/plot/plot_basaldrag.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_basaldrag.m	(revision 13395)
@@ -0,0 +1,53 @@
+function plot_basaldrag(md,options,width,i,type);
+
+%PLOT_BASALDRAG - plot basal drag
+%
+%   Usage:
+%      plot_basaldrag(md,options,width,i,type);
+%
+%   See also: PLOTMODEL
+
+%check layer
+if md.mesh.dimension==3,
+	if getfieldvalue(options,'layer',1)~=1;
+		disp('plot_basaldrag warning: basal drag is displayed in the lower layer')
+		changefieldvalue(options,'layer',1);
+	end
+end
+
+%compute exponents
+s=averaging(md,1./md.friction.p,0);
+r=averaging(md,md.friction.q./md.friction.p,0);
+
+%compute horizontal velocity
+if strcmpi(type,'basal_drag')
+	ub=sqrt(md.initialization.vx.^2+md.initialization.vy.^2)/md.constants.yts;
+elseif strcmpi(type,'basal_dragx')
+	ub=md.initialization.vx/md.constants.yts;
+elseif strcmpi(type,'basal_dragy')
+	ub=md.initialization.vy/md.constants.yts;
+end
+
+%compute basal drag
+drag=(max(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed),0)).^r.*(md.friction.coefficient).^2.*ub.^s/1000;
+
+%Figure out if this is a Section plot
+if exist(options,'sectionvalue')
+	plot_section(md,drag,options,width,i);
+	return;
+else
+
+	%process data and model
+	[x y z elements is2d isplanet]=processmesh(md,[],options);
+	[basal_drag datatype]=processdata(md,drag,options);
+
+	%plot basaldrag
+	subplot(width,width,i); 
+	plot_unit(x,y,z,elements,basal_drag,is2d,isplanet,datatype,options);
+
+	%apply options
+	options=addfielddefault(options,'title','Basal drag [kPa]');
+	options=addfielddefault(options,'view',2);
+	applyoptions(md,basal_drag,options);
+
+end
Index: /issm/trunk/src/m/plot/plot_boundaries.m
===================================================================
--- /issm/trunk/src/m/plot/plot_boundaries.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_boundaries.m	(revision 13395)
@@ -0,0 +1,39 @@
+function plot_boundaries(md,options,width,i);
+%PLOT_BOUNDARIES - plot mesh boundaries
+%
+%   Usage:
+%      plot_boundaries(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+subplot(width,width,i); 
+
+%process data and model
+if getfieldvalue(options,'layer',0)
+	options=removefield(options,'layer',1);
+end
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');hold on;
+end
+
+%plot rifts if present: 
+if isstruct(md.rifts.riftstruct),
+	for i=1:size(md.rifts.riftstruct,1),
+		segments=md.rifts.riftstruct(i).segments;
+		for j=1:size(segments,1),
+			plot(x(segments(j,1:2)),y(segments(j,1:2)),'r.-');
+		end
+		text(x(segments(floor(size(segments,1)/4),1)),y(segments(floor(size(segments,1)/4),1)),['Rift #' num2str(i)]);
+		%point out the tips
+		plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'b*');
+		plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'b*');
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Mesh boundaries');
+options=addfielddefault(options,'colorbar',0);
+options=addfielddefault(options,'view',2);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_contour.m
===================================================================
--- /issm/trunk/src/m/plot/plot_contour.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_contour.m	(revision 13395)
@@ -0,0 +1,245 @@
+function plot_contour(md,datain,options);
+%PLOT_CONTOUR - plot contours of a given field
+%
+%   Usage:
+%      plot_contour(md,data,options);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z index is2d isplanet]=processmesh(md,[],options);
+options=removefield(options,'log',0);
+[data datatype]=processdata(md,datain,options);
+
+%check is2d
+if ~is2d,
+	error('plot_contour error message: contour not supported for 3d meshes, project on a layer');
+end
+
+%first, process data: must be on nodes
+if datatype==1,
+	%elements -> take average
+	data=averaging(md,data,0);
+elseif datatype==2,
+	%nodes -> do nothing
+elseif datatype==3,
+	%quiver -> take norm
+	data=sqrt(sum(datain.*datain,2));
+else
+	error('datatype not supported yet');
+end
+
+%prepare colors
+if exist(options,'contouronly')
+	%remove the previous plots
+	cla
+end
+color=getfieldvalue(options,'contourcolor','y');
+linewidth=getfieldvalue(options,'linewidth',1);
+
+%get contours levels
+contourlevels=getfieldvalue(options,'contourlevels');
+if isnumeric(contourlevels),
+	levels=round_ice(linspace(max(data),min(data),contourlevels),2);
+else
+	levels=[];
+	for i=1:length(contourlevels)
+		levels(end+1)=contourlevels{i};
+	end
+	levels=sort(unique(levels),'descend');
+end
+numlevels=length(levels);
+
+%initialization of some variables
+numberofelements=size(index,1);
+elementslist=1:numberofelements;
+c=[];
+h=[];
+
+%get unique edges in mesh
+%1: list of edges
+edges=[index(:,[1,2]); index(:,[2,3]); index(:,[3,1])];
+%2: find unique edges
+[edges,I,J]=unique(sort(edges,2),'rows');
+%3: unique edge numbers
+vec=J;
+%4: unique edges numbers in each triangle (2 triangles sharing the same edge will have
+%   the same edge number)
+edges_tria=[vec(elementslist), vec(elementslist+numberofelements), vec(elementslist+2*numberofelements)];
+
+%segments [nodes1 nodes2]
+Seg1=index(:,[1 2]);
+Seg2=index(:,[2 3]);
+Seg3=index(:,[3 1]);
+
+%segment numbers [1;4;6;...]
+Seg1_num=edges_tria(:,1);
+Seg2_num=edges_tria(:,2);
+Seg3_num=edges_tria(:,3);
+
+%value of data on each tips of the segments
+Data1=data(Seg1);
+Data2=data(Seg2);
+Data3=data(Seg3);
+
+%get the ranges for each segment
+Range1=sort(Data1,2);
+Range2=sort(Data2,2);
+Range3=sort(Data3,2);
+
+for i=1:numlevels
+
+	level=levels(i);
+
+	%find the segments that contain this value
+	pos1=(Range1(:,1)<level & Range1(:,2)>level);
+	pos2=(Range2(:,1)<level & Range2(:,2)>level);
+	pos3=(Range3(:,1)<level & Range3(:,2)>level);
+
+	%get elements
+	poselem12=(pos1 & pos2);
+	poselem13=(pos1 & pos3);
+	poselem23=(pos2 & pos3);
+	poselem=find(poselem12 | poselem13 | poselem23);
+	numelems=length(poselem);
+
+	%if no element has been flagged, skip to the next level
+	if numelems==0,
+		continue,
+	end
+
+	%go through the elements and build the coordinates for each segment (1 by element)
+	x1=zeros(numelems,1);
+	x2=zeros(numelems,1);
+	y1=zeros(numelems,1);
+	y2=zeros(numelems,1);
+	edge_l=zeros(numelems,2);
+
+	for j=1:numelems,
+
+		weight1=(level-Data1(poselem(j),1))/(Data1(poselem(j),2)-Data1(poselem(j),1));
+		weight2=(level-Data2(poselem(j),1))/(Data2(poselem(j),2)-Data2(poselem(j),1));
+		weight3=(level-Data3(poselem(j),1))/(Data3(poselem(j),2)-Data3(poselem(j),1));
+
+		if poselem12(poselem(j));
+
+			x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
+			x2(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
+			y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
+			y2(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
+			edge_l(j,1)=Seg1_num(poselem(j));
+			edge_l(j,2)=Seg2_num(poselem(j));
+
+		elseif poselem13(poselem(j)),
+
+			x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
+			x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
+			y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
+			y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
+			edge_l(j,1)=Seg1_num(poselem(j));
+			edge_l(j,2)=Seg3_num(poselem(j));
+
+		elseif poselem23(poselem(j)),
+
+			x1(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
+			x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
+			y1(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
+			y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
+			edge_l(j,1)=Seg2_num(poselem(j));
+			edge_l(j,2)=Seg3_num(poselem(j));
+		else
+			%it shoud not go here
+		end
+	end
+
+	%now that we have the segments, we must try to connect them...
+
+	%loop over the subcontours
+	while ~isempty(edge_l),
+
+		%take the right edge of the second segment and connect it to the next segments if any
+		e1=edge_l(1,1);   e2=edge_l(1,2);
+		xc=[x1(1);x2(1)]; yc=[y1(1);y2(1)];
+
+		%erase the lines corresponding to this edge
+		edge_l(1,:)=[];
+		x1(1)=[]; x2(1)=[];
+		y1(1)=[]; y2(1)=[];
+
+		[ro1,co1]=find(edge_l==e1);
+
+		while ~isempty(ro1)
+
+			if co1==1,
+				xc=[x2(ro1);xc]; yc=[y2(ro1);yc];
+
+				%next edge:
+				e1=edge_l(ro1,2);
+
+			else
+				xc=[x1(ro1);xc]; yc=[y1(ro1);yc];
+
+				%next edge:
+				e1=edge_l(ro1,1);
+			end
+
+			%erase the lines of this
+			edge_l(ro1,:)=[];
+			x1(ro1)=[]; x2(ro1)=[];
+			y1(ro1)=[]; y2(ro1)=[];
+
+			%next connection
+			[ro1,co1]=find(edge_l==e1);
+		end
+
+		%same thing the other way (to the right)
+		[ro2,co2]=find(edge_l==e2);
+
+		while ~isempty(ro2)
+
+			if co2==1,
+				xc=[xc;x2(ro2)]; yc=[yc;y2(ro2)];
+
+				%next edge:
+				e2=edge_l(ro2,2);
+			else
+				xc=[xc;x1(ro2)]; yc=[yc;y1(ro2)];
+
+				%next edge:
+				e2=edge_l(ro2,1);
+			end
+
+			%erase the lines of this
+			edge_l(ro2,:)=[];
+			x1(ro2)=[]; x2(ro2)=[];
+			y1(ro2)=[]; y2(ro2)=[];
+
+			%next connection
+			[ro2,co2]=find(edge_l==e2);
+		end
+
+		%we now have one subcontour ready to be plotted
+		zc=level*ones(length(xc)+1,1);
+		if getfieldvalue(options,'contouronly',0),
+			h=[h;patch('Xdata',[xc;NaN],'Ydata',[yc;NaN],'Zdata',zc,'Cdata',zc,'facecolor','none','edgecolor','flat','linewidth',linewidth)];
+			hold on      
+		else
+			h=[h;patch('Xdata',[xc;NaN],'Ydata',[yc;NaN],'facecolor','none','edgecolor',color,'linewidth',linewidth)];
+			hold on
+		end
+
+		% Update the CS data structure as per "contours.m"
+		% so that clabel works
+		c = horzcat(c,[level, xc'; length(xc), yc']);
+
+	end
+end
+
+%labels?
+if (~strcmpi(getfieldvalue(options,'contourticks','on'),'off') & ~isempty(c) & ~isempty(h))
+	if exist(options,'contouronly')
+		clabel(c,h);
+	else
+		clabel(c,h,'color',color,'FontSize',14);
+	end
+end
Index: /issm/trunk/src/m/plot/plot_drivingstress.m
===================================================================
--- /issm/trunk/src/m/plot/plot_drivingstress.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_drivingstress.m	(revision 13395)
@@ -0,0 +1,24 @@
+function plot_drivingstress(md,options,width,i);
+%PLOT_DRIVINGSTRESS - plot driving stress
+%
+%   Usage:
+%      plot_drivingstress(md,options,width,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+%get driving stress
+[sx sy s]=drivingstress(md);
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[dstress datatype]=processdata(md,s,options);
+dstress=dstress/1000;
+
+%plot mesh quivervel
+subplot(width,width,i); 
+plot_unit(x,y,z,elements,dstress,is2d,isplanet,datatype,options)
+
+%apply options
+options=addfielddefault(options,'title','Driving stress [kPa]');
+options=addfielddefault(options,'view',2);
+applyoptions(md,dstress,options);
Index: /issm/trunk/src/m/plot/plot_edges.m
===================================================================
--- /issm/trunk/src/m/plot/plot_edges.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_edges.m	(revision 13395)
@@ -0,0 +1,34 @@
+function plot_edges(md,options,width,i,datai);
+%PLOT_SEGMENTS - plot edges, with different colors according to segment markers.
+%
+%   Usage:
+%      plot_edges(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+edges=md.mesh.edges;
+if isnan(edges)
+	error('edges in NaN')
+end
+
+if (md.mesh.dimension==2),
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+	text(sum(x(edges(:,1:2)),2)/2,sum(y(edges(:,1:2)),2)/2,sum(z(edges(:,1:2)),2)/2,...
+		num2str(transpose(1:size(edges,1))),...
+		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	error('plot_edges: 3d plot of edges not supported yet!');
+end
+
+%apply options
+options=addfielddefault(options,'title','Edges');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_elementnumbering.m
===================================================================
--- /issm/trunk/src/m/plot/plot_elementnumbering.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_elementnumbering.m	(revision 13395)
@@ -0,0 +1,57 @@
+function plot_elementnumbering(md,options,width,i);
+%PLOT_ELEMENTNUMBERING - plot element numbering
+%
+%   Usage:
+%      plot_elementnumbering(md,options,width,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+subplot(width,width,i); 
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[elementnumbers datatype]=processdata(md,[1:md.mesh.numberofelements]',options);
+
+%plot
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+
+	%numbering
+	text(sum(x(elements(:,1:3)),2)/3,sum(y(elements(:,1:3)),2)/3,sum(z(elements(:,1:3)),2)/3,...
+		num2str(transpose(1:size(elements,1))),...
+		'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','none','EdgeColor','black');
+
+	%numbering
+	text(sum(x(elements(:,1:6)),2)/6,sum(y(elements(:,1:6)),2)/6,sum(z(elements(:,1:6)),2)/6,...
+		num2str(transpose(1:size(elements,1))),...
+		'HorizontalAlignment','center','VerticalAlignment','middle');
+end
+
+%apply options
+options=addfielddefault(options,'title','Element numbering');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_elementstype.m
===================================================================
--- /issm/trunk/src/m/plot/plot_elementstype.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_elementstype.m	(revision 13395)
@@ -0,0 +1,131 @@
+function plot_elementstype(md,options,width,i);
+%PLOT_ELEMENTSTYPE - plot elements type
+%
+%   Usage:
+%      plot_elementstype(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[data datatype]=processdata(md,md.flowequation.element_equation,options);
+
+%edgecolor?
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%plot
+subplot(width,width,i);
+
+if is2d
+	%Hutter elements
+	posH=find(data==1);
+	A=elements(posH,1); B=elements(posH,2); C=elements(posH,3); 
+	p1=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',1,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyeal element
+	posM=find(data==2);
+	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); 
+	p2=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',2,'FaceColor','flat','EdgeColor',edgecolor);
+	%Pattyn element
+	posP=find(data==3);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); 
+	p3=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',3,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyealPattyn element
+	posMP=find(data==5);
+	A=elements(posMP,1); B=elements(posMP,2); C=elements(posMP,3); 
+	p5=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',5,'FaceColor','flat','EdgeColor',edgecolor);
+	%Stokes elements
+	posS=find(data==4);
+	A=elements(posS,1); B=elements(posS,2); C=elements(posS,3); 
+	p6=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',4,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyealStokes elements
+	posMS=find(data==6);
+	A=elements(posMS,1); B=elements(posMS,2); C=elements(posMS,3); 
+	p7=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',6,'FaceColor','flat','EdgeColor',edgecolor);
+	%PattynStokes elements
+	posPS=find(data==7);
+	A=elements(posPS,1); B=elements(posPS,2); C=elements(posPS,3); 
+	p8=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',7,'FaceColor','flat','EdgeColor',edgecolor);
+	%None elements
+	posNONE=find(data==0);
+	A=elements(posNONE,1); B=elements(posNONE,2); C=elements(posNONE,3); 
+	p9=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',0,'FaceColor','flat','EdgeColor',edgecolor);
+
+	legend([p1 p2 p3 p5 p6 p7 p8 p9],...
+		'Hutter''s elements','MacAyeal''s elements','Pattyn''s elements',...
+		'MacAyealPattyn''s elements','Stokes''s elements','MacAyealStokes''s elements','PattynStokes''s elements','None element');
+
+else
+	%Hutter elements
+	posH=find(data==1);
+	A=elements(posH,1); B=elements(posH,2); C=elements(posH,3); D=elements(posH,4); E=elements(posH,5); F=elements(posH,6);
+	p1=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyeal elements
+	posM=find(data==2);
+	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); D=elements(posM,4); E=elements(posM,5); F=elements(posM,6);
+	p2=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
+	%Pattyn elements
+	posP=find(data==3);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
+	p3=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
+	%Stokes elements
+	posS=find(data==4);
+	A=elements(posS,1); B=elements(posS,2); C=elements(posS,3); D=elements(posS,4); E=elements(posS,5); F=elements(posS,6);
+	p4=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyealPattyn elements
+	posP=find(data==5);
+	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
+	p5=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
+	%PattynStokes elements
+	PosPS=find(data==7);
+	A=elements(PosPS,1); B=elements(PosPS,2); C=elements(PosPS,3); D=elements(PosPS,4); E=elements(PosPS,5); F=elements(PosPS,6);
+	p6=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
+	%MacAyealStokes elements
+	PosMS=find(data==6);
+	A=elements(PosMS,1); B=elements(PosMS,2); C=elements(PosMS,3); D=elements(PosMS,4); E=elements(PosMS,5); F=elements(PosMS,6);
+	p7=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 6,'FaceColor','flat','EdgeColor',edgecolor);
+	%None elements
+	PosNONE=find(data==0);
+	A=elements(PosNONE,1); B=elements(PosNONE,2); C=elements(PosNONE,3); D=elements(PosNONE,4); E=elements(PosNONE,5); F=elements(PosNONE,6);
+	p8=patch( 'Faces', [A B C],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 0,'FaceColor','flat','EdgeColor',edgecolor);
+
+	legend([p1 p2 p3 p4 p5 p6 p7 p8],...
+		'Hutter''s elements','MacAyeal''s elements','Pattyn''s elements','Stokes''s elements',...
+		'MacAyealPattyn''s elements','PattynStokes''s elements','MacAyealStokes''s elements','None elements');
+end
+
+%apply options
+options=addfielddefault(options,'title','Elements type');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_gridded.m
===================================================================
--- /issm/trunk/src/m/plot/plot_gridded.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_gridded.m	(revision 13395)
@@ -0,0 +1,64 @@
+function plot_gridded(md,data,options,plotlines,plotcols,i)
+%PLOT_OVERLAY - superimpose radar image to a given field
+%
+%   Usage:
+%      plot_gridded(md,options,plotlines,plotcols,i)
+%
+%   See also: PLOTMODEL
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[data datatype]=processdata(md,data,options);
+
+%check is2d
+if ~is2d, 
+	error('buildgridded error message: gridded not supported for 3d meshes, project on a layer');
+end
+
+%Get xlim and ylim (used to extract radar image)
+xlim=getfieldvalue(options,'xlim',[min(x) max(x)]);
+ylim=getfieldvalue(options,'ylim',[min(y) max(y)]);
+post=getfieldvalue(options,'posting',diff(xlim)/1000);
+
+%Interpolating data on grid
+[x_m y_m data_grid]=InterpFromMeshToGrid(elements,x,y,data,xlim(1),ylim(2),post,post,round(diff(ylim)/post),round(diff(xlim)/post),NaN);
+if size(data_grid,1)<3 | size(data_grid,2)<3,
+	error('data_grid size too small in plot_gridded, check posting and uni');
+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'),
+	caxis_opt=getfieldvalue(options,'caxis');
+	data_grid(find(data_grid<caxis_opt(1)))=caxis_opt(1);
+	data_grid(find(data_grid>caxis_opt(2)))=caxis_opt(2);
+	data_min=caxis_opt(1);
+	data_max=caxis_opt(2);
+else
+	data_min=min(data_grid(:));
+	data_max=max(data_grid(:));
+end
+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 
+subplotmodel(plotlines,plotcols,i,options);
+
+%shading interp;
+h=imagesc(xlim,ylim,data_grid);set(gca,'YDir','normal');
+
+%last step: mesh gridded?
+if exist(options,'edgecolor'),
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch('Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',data_grid(1)*ones(size(x)),'FaceColor','none','EdgeColor',getfieldvalue(options,'edgecolor'));
+end
+
+%Apply options
+applyoptions(md,data,options);
Index: /issm/trunk/src/m/plot/plot_highlightelements.m
===================================================================
--- /issm/trunk/src/m/plot/plot_highlightelements.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_highlightelements.m	(revision 13395)
@@ -0,0 +1,51 @@
+function plot_highlightelements(md,options,width,i);
+%PLOT_HIGHLIGHTELEMENTS - plot selected elements
+%
+%   Usage:
+%      plot_highlightelements(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[elementnumbers datatype]=processdata(md,[1:md.mesh.numberofelements]',options);
+
+%plot
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [0.9 0.5 0.5],'FaceColor','flat','EdgeColor','black');
+end
+
+%apply options
+if ~exist(options,'highlight')
+	disp('highlightelements warning : highlight option empty, not element highlighted');
+end
+options=addfielddefault(options,'title','Highlighted Elements');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_highlightvertices.m
===================================================================
--- /issm/trunk/src/m/plot/plot_highlightvertices.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_highlightvertices.m	(revision 13395)
@@ -0,0 +1,46 @@
+function plot_highlightvertices(md,options,width,i);
+%PLOT_HIGHLIGHTVERTICES - plot selected vertices
+%
+%   Usage:
+%      plot_highlightvertices(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[nodenumbers datatype]=processdata(md,[1:md.mesh.numberofvertices]',options);
+
+%plot
+subplot(width,width,i); 
+
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+end
+
+%apply options
+if ~exist(options,'highlight')
+	disp('highlightvertices warning : highlight option empty, not node highlighted');
+end
+options=addfielddefault(options,'title','Highlighted Nodes');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_icefront.m
===================================================================
--- /issm/trunk/src/m/plot/plot_icefront.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_icefront.m	(revision 13395)
@@ -0,0 +1,106 @@
+function plot_icefront(md,options,width,i,data);
+%PLOT_ICEFRONT - plot segment on neumann BC
+%
+%   Usage:
+%      plot_icefront(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+icefront=md.diagnostic.icefront;
+
+if (md.mesh.dimension==2),
+
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	%highlight elements on neumann
+	pos=find(icefront(:,end)==1);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h2=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	pos=find(icefront(:,end)==0);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h3=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+
+	pos=find(icefront(:,end)==2);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h3bis=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+
+	%display arrows pointing outward
+	xstart=mean(x(icefront(:,1:end-2)),2);
+	ystart=mean(y(icefront(:,1:end-2)),2);
+	length=sqrt((x(icefront(:,1))-x(icefront(:,2))).^2 + (y(icefront(:,1))-y(icefront(:,2))).^2 );
+	normal(:,1)=cos(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
+	normal(:,2)=sin(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
+	xend=xstart+length.*normal(:,1);
+	yend=ystart+length.*normal(:,2);
+	q=quiver(xstart,ystart,xend-xstart,yend-ystart); hold on;
+	h4=plot(xstart,ystart,'r*');
+else
+
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	h1=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	%highlight elements on neumann
+	pos=find(icefront(:,end)==1);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	h2=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
+	pos=find(icefront(:,end)==0);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	h3=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	pos=find(icefront(:,end)==2);
+	pos=icefront(pos,end-1);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+	h3bis=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+
+	%display arrows pointing outward
+	xstart=mean(x(icefront(:,1:end-2)),2);
+	ystart=mean(y(icefront(:,1:end-2)),2);
+	zstart=mean(z(icefront(:,1:end-2)),2);
+	length=sqrt((x(icefront(:,1))-x(icefront(:,2))).^2 + (y(icefront(:,1))-y(icefront(:,2))).^2 );
+	normal(:,1)=cos(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
+	normal(:,2)=sin(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
+	xend=xstart+length.*normal(:,1);
+	yend=ystart+length.*normal(:,2);
+	q=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zeros(numel(xstart),1)); hold on;
+	h4=plot3(xstart,ystart,zstart,'r*');
+end
+
+%legend (disable warnings)
+warning off
+legend([h2,h3,h3bis,q],'element on ice front (Water)','element on ice front (Air)','element on ice front (Ice)','normal vectors')
+warning on
+
+%apply options
+options=addfielddefault(options,'title','Neumann boundary conditions');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_importancefactors.m
===================================================================
--- /issm/trunk/src/m/plot/plot_importancefactors.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_importancefactors.m	(revision 13395)
@@ -0,0 +1,83 @@
+function plot_importancefactors(md,options,width,ii);
+%PLOT_IMPORTANCEFACTORS - plot importance factors
+%
+%   Usage:
+%      plot_importancefactors(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%first recover design variable descriptor
+if exist(options,'designvariable'),
+	descriptor=getfieldvalue(options,'designvariable');
+else
+	error('plot_importancefactors error message: Need to supply design variable descriptor');
+end
+descriptorlength=length(descriptor);
+
+%then recover responsfunction name
+if exist(options,'responsefunction'),
+	responsefunctiondescriptor=getfieldvalue(options,'responsefunction');
+else
+	error('plot_importancefactors error message: Need to supply response function descriptor');
+end
+
+%go through all response functions and find the one corresponding to the correct responsefunctiondescriptor
+responsefunctions=md.qmu.results{2};
+found=0;
+for i=1:length(responsefunctions),
+	if strcmpi(responsefunctions(i).descriptor,responsefunctiondescriptor),
+		found=i;
+		break;
+	end
+end
+if ~found,
+	error('plot_importancefactors error message: could not find correct response function');
+end
+responsefunctions=responsefunctions(found);
+nfun=size(responsefunctions.desvar,1);
+
+%Now recover response to the correct desgin variable
+importancefactors=zeros(md.qmu.numberofpartitions,1);
+count=0;
+for i=1:nfun,
+	desvar=responsefunctions.desvar{i};
+	if strncmpi(desvar,descriptor,descriptorlength),
+		count=count+1;
+		importancefactors(count)=responsefunctions.impfac(i);
+	end
+end
+if count==0,
+	error('plot_importancefactors error message: could not find to response functions with corresponding design variable');
+end
+
+%log?
+if exist(options,'log'),
+	logvalue=getfieldvalue(options,'log');
+	importancefactors=log(importancefactors)/log(logvalue);
+end
+
+%Ok, get partitioning.
+[epart npart]=MeshPartition(md,md.qmu.numberofpartitions);
+
+%distribute importance factor
+nodeimportance=importancefactors(npart);
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%standard plot:
+subplot(width,width,ii);
+
+%ok, plot nodeimportance now.
+if is2d,
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', nodeimportance,'FaceColor','interp','EdgeColor',edgecolor);
+else
+	error('plot_importancefactors error message: 3d meshes not supported yet');
+end
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_manager.m
===================================================================
--- /issm/trunk/src/m/plot/plot_manager.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_manager.m	(revision 13395)
@@ -0,0 +1,204 @@
+function plot_manager(md,options,subplotwidth,nlines,ncols,i);
+%PLOT__MANAGER - distribute the plots, called by plotmodel
+%
+%   Usage:
+%      plot_manager(md,options,subplotwidth,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT
+
+%parse options and get a structure of options. 
+options=checkplotoptions(md,options);
+
+%get data to be displayed
+data=getfieldvalue(options,'data');
+
+%figure out if this is a special plot
+if ischar(data),
+
+	switch data,
+
+		case 'boundaries',
+			plot_boundaries(md,options,subplotwidth,i);
+			return;
+		case 'BC',
+			plot_BC(md,options,subplotwidth,i,data);
+			return;
+		case 'edges'
+			plot_edges(md,options,subplotwidth,i,data)
+			return
+		case 'elementnumbering',
+			plot_elementnumbering(md,options,subplotwidth,i);
+			return;
+		case 'highlightelements',
+			plot_highlightelements(md,options,subplotwidth,i);
+			return;
+		
+		case 'qmumean',
+			plot_qmumean(md,options,nlines,ncols,i);
+			return;
+		
+		case 'qmustddev',
+			plot_qmustddev(md,options,nlines,ncols,i);
+			return;
+		
+		case 'qmuhistnorm',
+			plot_qmuhistnorm(md,options,nlines,ncols,i);
+			return;
+
+		case 'qmu_mass_flux_segments',
+			plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
+			return;
+
+		case 'part_hist',
+			plot_parthist(md,options,nlines,ncols,i);
+			return;
+		case 'part_hist_n',
+			plot_parthistn(md,options,nlines,ncols,i);
+			return;
+		case 'part_hist_w',
+			plot_parthistw(md,options,nlines,ncols,i);
+			return;
+		case 'elements_type',
+			plot_elementstype(md,options,subplotwidth,i);
+			return;
+		case 'vertexnumbering',
+			plot_vertexnumbering(md,options,subplotwidth,i);
+			return;
+		case 'highlightvertices',
+			plot_highlightvertices(md,options,subplotwidth,i);
+			return;
+		case {'basal_drag','basal_dragx','basal_dragy'},
+			plot_basaldrag(md,options,subplotwidth,i,data);
+			return;
+		case 'driving_stress',
+			plot_drivingstress(md,options,subplotwidth,i);
+			return;
+		case 'mesh',
+			plot_mesh(md,options,nlines,ncols,i);
+			return;
+		case 'none',
+			if ~exist(options,'overlay'),
+				plot_none(md,options,nlines,ncols,i);
+				return;
+			end
+		case 'penalties',
+			plot_penalties(md,options,subplotwidth,i);
+			return;
+		case 'partition',
+			plot_partition(md,options,nlines,ncols,i);
+			return;
+		case 'referential',
+			plot_referential(md,options,nlines,ncols,i);
+			return;
+		case 'riftvel',
+			plot_riftvel(md,options,nlines,ncols,i);
+			return;
+		case 'riftnumbering',
+			plot_riftnumbering(md,options,nlines,ncols,i);
+			return;
+		case 'rifts',
+			plot_rifts(md,options,nlines,ncols,i);
+			return;
+		case 'riftrelvel',
+			plot_riftrelvel(md,options,nlines,ncols,i);
+			return;
+		case 'riftpenetration',
+			plot_riftpenetration(md,options,nlines,ncols,i);
+			return;
+		case 'riftfraction',
+			plot_riftfraction(md,options,nlines,ncols,i);
+			return;
+		case 'sarpwr',
+			plot_sarpwr(md,options,subplotwidth,i)
+			return
+		case 'icefront'
+			plot_icefront(md,options,subplotwidth,i,data)
+			return
+		case 'segments'
+			plot_segments(md,options,subplotwidth,i,data)
+			return
+		
+		case 'quiver'
+			data=[md.initialization.vx md.initialization.vy]; %Go ahead and try plot_unit
+
+		case {'strainrate_tensor','strainrate','strainrate_principal','strainrate_principalaxis1','strainrate_principalaxis2','strainrate_principalaxis3',...
+				'stress_tensor','stress','stress_principal','stress_principalaxis1','stress_principalaxis2','stress_principalaxis3',...
+				'deviatoricstress_tensor','deviatoricstress','deviatoricstress_principal','deviatoricstress_principalaxis1','deviatoricstress_principalaxis2','deviatoricstress_principalaxis3'},
+			plot_tensor(md,options,subplotwidth,i,data);
+			return;
+		case 'thermaltransient_results',
+			plot_thermaltransient_results(md,options,subplotwidth,i);
+			return;
+		case 'transient_movie',
+			plot_transient_movie(md,options,subplotwidth,i);
+			return;
+		case 'transient_results',
+			plot_transient_results(md,options,subplotwidth,i);
+
+		case 'transient_field',
+			plot_transient_field(md,options,subplotwidth,i);
+			return;
+
+	otherwise,
+
+		if ismember(data,properties('model')),
+			data=eval(['md.' data ';']);
+		else
+			error('plot error message: data provided not supported yet. Type plotdoc for help');
+		end
+	end
+end
+
+%Figure out if this is a semi-transparent plot.
+if exist(options,'overlay'),
+	plot_overlay(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a semi-transparent plot.
+if exist(options,'gridded'),
+	plot_gridded(md,data,options,nlines,ncols,i);
+	return;
+end
+
+%Figure out if this is a Section plot
+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
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,data,options);
+[data2 datatype]=processdata(md,data,options);
+
+%standard plot:
+subplot(nlines,ncols,i);
+
+%plot unit
+plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options);
+
+%apply all options
+if datatype==3,
+	options=changefieldvalue(options,'colorbar',2);
+	if exist(options,'contourlevels'),
+		data2=data;
+	end
+end
+
+applyoptions(md,data2,options);
+
+%do ground overlay on kml plot_unit? 
+if (strcmpi(getfieldvalue(options,'kmlgroundoverlay','off'),'on')),
+	if ((nlines*ncols~=1) | (i~=1)),
+		error('cannot kmlgroundoverlay on multi-plots');
+	end
+	
+	%call routine to build kml file and image that goes with it.
+	kmlgroundoverlay(md,options);
+end
Index: /issm/trunk/src/m/plot/plot_mesh.m
===================================================================
--- /issm/trunk/src/m/plot/plot_mesh.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_mesh.m	(revision 13395)
@@ -0,0 +1,41 @@
+function plot_mesh(md,options,nlines,ncols,i);
+%PLOT_MESH - plot model mesh
+%
+%   Usage:
+%      plot_mesh(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%retrieve some options
+linewidth=getfieldvalue(options,'linewidth',1);
+edgecolor=getfieldvalue(options,'edgecolor','black');
+
+%plot mesh
+if is2d
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+else
+	if ~isplanet,
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+		patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+		patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+	else
+		A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+		if (size(elements,2)==4), D=elements(:,4); else D=C; end
+		patch( 'Faces', [A B C D],  'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none','EdgeColor',edgecolor,'linewidth',linewidth);
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Mesh');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_none.m
===================================================================
--- /issm/trunk/src/m/plot/plot_none.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_none.m	(revision 13395)
@@ -0,0 +1,20 @@
+function plot_none(md,options,nlines,ncols,i);
+%PLOT_NONE - plot nothing, just apply options
+%
+%   Usage:
+%      plot_mesh(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+return;
+
+options=addfielddefault(options,'colorbar','none');
+options=addfielddefault(options,'map','none');
+options=addfielddefault(options,'axis','equal');
+
+if exist(options,'overlay'),
+	plot_overlay(md,'none',options,nlines,ncols,i);
+	return;
+end
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_overlay.m
===================================================================
--- /issm/trunk/src/m/plot/plot_overlay.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_overlay.m	(revision 13395)
@@ -0,0 +1,154 @@
+function plot_overlay(md,data,options,plotlines,plotcols,i)
+%PLOT_OVERLAY - superimpose radar image to a given field
+%
+%   Usage:
+%      plot_overlay(md,options,plotlines,plotcols,i)
+%
+%   See also: PLOTMODEL
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+if strcmpi(data,'none'),
+	radaronly=1;
+	data=NaN*ones(md.mesh.numberofvertices,1);
+	datatype=1;
+else
+	radaronly=0;
+	[data datatype]=processdata(md,data,options);
+end
+
+%check is2d
+if ~is2d, 
+	error('buildoverlay error message: overlay not supported for 3d meshes, project on a layer');
+end
+if datatype==3,
+	error('buildoverlay error message: overlay not supported for quiver plots');
+end
+
+
+%radar power
+if ~any(isnan(md.radaroverlay.x)) & ~any(isnan(md.radaroverlay.y)) & ~any(isnan(md.radaroverlay.pwr)),
+	disp('plot_overlay info: the radar image held by the model is being used');
+	xlim=[min(md.radaroverlay.x) max(md.radaroverlay.x)];
+	ylim=[min(md.radaroverlay.y) max(md.radaroverlay.y)];
+else
+	disp('Extracting radar image...');
+	%Get xlim and ylim (used to extract radar image)
+	xlim=getfieldvalue(options,'xlim',[min(x) max(x)])/getfieldvalue(options,'unit',1);
+	ylim=getfieldvalue(options,'ylim',[min(y) max(y)])/getfieldvalue(options,'unit',1);
+	options=addfielddefault(options,'xlim',xlim);
+	options=addfielddefault(options,'ylim',ylim);
+	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
+xmin=min(md.radaroverlay.x);
+ymax=max(md.radaroverlay.y);
+xspacing=(max(md.radaroverlay.x)-min(md.radaroverlay.x))/(length(md.radaroverlay.x));
+yspacing=(max(md.radaroverlay.y)-min(md.radaroverlay.y))/(length(md.radaroverlay.y));
+nlines=length(md.radaroverlay.y);
+ncols =length(md.radaroverlay.x);
+disp('Interpolating data on grid...');
+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 (For processing, it is better not to have nan)
+pos=find(isinf(data_grid));
+if ~isempty(pos),
+	disp('Warning: removing Infs from vector (probably log(0)?)');
+	data_grid(pos)=NaN;
+end
+if exist(options,'caxis'),
+	caxis_opt=getfieldvalue(options,'caxis');
+	data_grid(find(data_grid<caxis_opt(1)))=caxis_opt(1);
+	data_grid(find(data_grid>caxis_opt(2)))=caxis_opt(2);
+	data_min=caxis_opt(1);
+	data_max=caxis_opt(2);
+else
+	data_min=min(data_grid(:));
+	data_max=max(data_grid(:));
+end
+data_nan=find(isnan(data_grid));
+data_grid(data_nan)=data_min; 
+
+%Special colormaps that require hsv treatment
+colorm=getfieldvalue(options,'colormap','Rignot');
+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
+	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
+
+%Select plot area 
+subplotmodel(plotlines,plotcols,i,options);
+
+%Plot: 
+imagesc(md.radaroverlay.x*getfieldvalue(options,'unit',1),md.radaroverlay.y*getfieldvalue(options,'unit',1),image_rgb);set(gca,'YDir','normal');
+
+%last step: mesh overlay?
+if exist(options,'edgecolor'),
+	hold on
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch('Faces',[A B C],'Vertices', [x y z],'FaceVertexCData',zeros(size(x)),'FaceColor','none',...
+		'EdgeColor',getfieldvalue(options,'edgecolor'),'LineWidth',getfieldvalue(options,'linewidth',1));
+end
+
+%Apply options, without colorbar and without grid
+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
+end
+options=addfielddefault(options,'axis','equal off');              % default axis
+applyoptions(md,data,options);
+drawnow
Index: /issm/trunk/src/m/plot/plot_parthist.m
===================================================================
--- /issm/trunk/src/m/plot/plot_parthist.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_parthist.m	(revision 13395)
@@ -0,0 +1,34 @@
+function plot_parthist(md,options,nlines,ncols,i);
+%PLOT_PARTHIST - plot partitioning histogram
+%
+%   Usage:
+%      plot_parthist(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+imin=min(md.qmu.partition);
+imax=max(md.qmu.partition);
+
+part=zeros(imax-imin+1,2);
+
+for i=imin:imax
+    ind=find(md.qmu.partition == i);
+    part(i-imin+1,1)=length(ind);
+	part(i-imin+1,2)=sum(md.vertex_weight(ind));
+end
+
+subplot(2,1,1)
+bar(imin:imax,part(:,1));
+xlim([imin-0.5 imax+0.5])
+title('Number of Nodes in Each Partition')
+
+subplot(2,1,2)
+bar(imin:imax,part(:,2));
+xlim([imin-0.5 imax+0.5])
+title('Total Weight in Each Partition')
Index: /issm/trunk/src/m/plot/plot_parthistn.m
===================================================================
--- /issm/trunk/src/m/plot/plot_parthistn.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_parthistn.m	(revision 13395)
@@ -0,0 +1,43 @@
+function plot_parthist(md,options,nlines,ncols,i);
+%PLOT_PARTHIST - plot partitioning histogram
+%
+%   Usage:
+%      plot_parthist(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+imin=min(md.qmu.partition);
+imax=max(md.qmu.partition);
+
+part=zeros(imax-imin+1,2);
+
+for i=imin:imax
+    ind=find(md.qmu.partition == i);
+    part(i-imin+1,1)=length(ind);
+	part(i-imin+1,2)=sum(md.vertex_weight(ind));
+end
+
+%subplot(2,1,1)
+bar(imin:imax,part(:,1));
+%xlim([imin-0.5 imax+0.5])
+%title('Number of Nodes in Each Partition')
+options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+options=addfielddefault(options,'title','Number of Nodes in Each Partition');
+options=addfielddefault(options,'colorbar','off');
+
+%subplot(2,1,2)
+%bar(imin:imax,part(:,2));
+%xlim([imin-0.5 imax+0.5])
+%title('Total Weight in Each Partition')
+%options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+%options=addfielddefault(options,'title','Total Weight in Each Partition');
+%options=addfielddefault(options,'colorbar','off');
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_parthistw.m
===================================================================
--- /issm/trunk/src/m/plot/plot_parthistw.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_parthistw.m	(revision 13395)
@@ -0,0 +1,43 @@
+function plot_parthist(md,options,nlines,ncols,i);
+%PLOT_PARTHIST - plot partitioning histogram
+%
+%   Usage:
+%      plot_parthist(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+imin=min(md.qmu.partition);
+imax=max(md.qmu.partition);
+
+part=zeros(imax-imin+1,2);
+
+for i=imin:imax
+    ind=find(md.qmu.partition == i);
+    part(i-imin+1,1)=length(ind);
+	part(i-imin+1,2)=sum(md.vertex_weight(ind));
+end
+
+%subplot(2,1,1)
+%bar(imin:imax,part(:,1));
+%xlim([imin-0.5 imax+0.5])
+%title('Number of Nodes in Each Partition')
+%options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+%options=addfielddefault(options,'title','Number of Nodes in Each Partition');
+%options=addfielddefault(options,'colorbar','off');
+
+%subplot(2,1,2)
+bar(imin:imax,part(:,2));
+%xlim([imin-0.5 imax+0.5])
+%title('Total Weight in Each Partition')
+options=addfielddefault(options,'xlim',[imin-0.5 imax+0.5]);
+options=addfielddefault(options,'title','Total Weight in Each Partition');
+options=addfielddefault(options,'colorbar','off');
+
+%apply options
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_penalties.m
===================================================================
--- /issm/trunk/src/m/plot/plot_penalties.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_penalties.m	(revision 13395)
@@ -0,0 +1,48 @@
+function plot_penalties(md,options,width,i);
+%PLOT_PENALTIES - plot penalties
+%
+%   Usage:
+%      plot_penalties(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh penalties
+subplot(width,width,i); 
+
+%units
+if exist(options,'unit'),
+	unit=getfieldvalue(options,'unit');
+	x=x*unit;
+	y=y*unit;
+	z=z*unit;
+end
+
+if ~md.mesh.dimension==3,
+	error('no penalties to plot for ''2d'' model');
+elseif isempty(md.penalties),
+	disp('no penalty applied in this model');
+	return;
+else
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	hold on;
+	for (i=1:size(md.penalties,1)),
+		P1=plot3(x(md.penalties(i,1)),y(md.penalties(i,1)),z(md.penalties(i,1)),'ro','MarkerSize',15,'MarkerFaceColor','r');
+		P2=plot3(x(md.penalties(i,:)),y(md.penalties(i,:)),z(md.penalties(i,:)),'bo-','LineWidth',2,'MarkerSize',8,'MarkerFaceColor','b');
+	end
+	legend([P1 P2],'MacAyeal''s penalized nodes','Pattyn''s penalized nodes');
+end
+
+%apply options
+options=addfielddefault(options,'title','Penalties');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_profile.m
===================================================================
--- /issm/trunk/src/m/plot/plot_profile.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_profile.m	(revision 13395)
@@ -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/trunk/src/m/plot/plot_qmu_mass_flux_segments.m
===================================================================
--- /issm/trunk/src/m/plot/plot_qmu_mass_flux_segments.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_qmu_mass_flux_segments.m	(revision 13395)
@@ -0,0 +1,49 @@
+function plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
+%PLOT_QMU_MASS_FLUX_SEGMENTS - plot segments from the qmu analysis of mass fluxes
+%
+%   Usage:
+%      plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
+%
+
+subplot(nlines,ncols,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+allsegments=md.qmu.mass_flux_segments;
+
+if (md.mesh.dimension==2),
+
+	%recover segments
+	hold on
+	for i=1:length(allsegments),
+		segments=allsegments{i};
+
+		%plot semgnets
+		for j=1:length(segments),
+			plot([segments(j,1) segments(j,3)],[segments(j,2) segments(j,4)]);
+		end
+		text(segments(j,1),segments(j,2),['Profile #' num2str(i)]);
+
+		%plot normals
+		
+		for j=1:length(segments),
+			xstart=mean([segments(j,1) segments(j,3)]);
+			ystart=mean([segments(j,2) segments(j,4)]);
+			length1=sqrt((segments(j,1)-segments(j,3)).^2 + (segments(j,2)-segments(j,4)).^2);
+			normal(:,1)=cos(atan2(segments(j,1)-segments(j,3) , segments(j,4)-segments(j,2)));
+			normal(:,2)=sin(atan2(segments(j,1)-segments(j,3) , segments(j,4)-segments(j,2)));
+			xend=xstart+length1.*normal(:,1);
+			yend=ystart+length1.*normal(:,2);
+			plot([xstart xend],[ystart yend],'r-');
+		end
+
+	end
+else
+	error('plot_qmu_mass_flux_segments: 3d plot of segments not supported yet!');
+end
+
+%apply options
+options=addfielddefault(options,'title','Mass Flux segments and normals');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_qmuhistnorm.m
===================================================================
--- /issm/trunk/src/m/plot/plot_qmuhistnorm.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_qmuhistnorm.m	(revision 13395)
@@ -0,0 +1,48 @@
+function plot_qmuhistnorm(md,options,nlines,ncols,index);
+
+%prepare plot
+subplot(nlines,ncols,index); 
+hold on
+
+
+%recover histnorm data
+if ~exist(options,'qmudata')
+	error('plot_qmuhistnorm error message: option qmudata is required');
+else
+	qmudata=getfieldvalue(options,'qmudata');
+end
+
+%process options for the qmu plot: 
+
+%    hmin          (numeric, minimum for histogram)
+%    hmax          (numeric, maximum for histogram)
+%    hnint         (numeric, number of intervals for histogram)
+%    ymin1         (numeric, minimum of histogram y-axis)
+%    ymax1         (numeric, maximum of histogram y-axis)
+%    ymin2         (numeric, minimum of cdf y-axis)
+%    ymax2         (numeric, maximum of cdf y-axis)
+%    cdfplt        (char, 'off' to turn off cdf line plots)
+%    cdfleg        (char, 'off' to turn off cdf legends)
+%
+
+qmuoptions='';
+
+if exist(options,'hmin'), hmin=getfieldvalue(options,'hmin'); qmuoptions=[qmuoptions ',''hmin'',' num2str(hmin)]; end
+if exist(options,'hmax'), hmax=getfieldvalue(options,'hmax'); qmuoptions=[qmuoptions ',''hmax'',' num2str(hmax)]; end
+if exist(options,'hnint'), hnint=getfieldvalue(options,'hnint'); qmuoptions=[qmuoptions ',''hnint'',' num2str(hnint)]; end
+if exist(options,'ymin1'), ymin1=getfieldvalue(options,'ymin1'); qmuoptions=[qmuoptions ',''ymin1'',' num2str(ymin1)]; end
+if exist(options,'ymax1'), ymax1=getfieldvalue(options,'ymax1'); qmuoptions=[qmuoptions ',''ymax1'',' num2str(ymax1)]; end
+if exist(options,'ymin2'), ymin2=getfieldvalue(options,'ymin2'); qmuoptions=[qmuoptions ',''ymin2'',' num2str(ymin2)]; end
+if exist(options,'ymax2'), ymax2=getfieldvalue(options,'ymax2'); qmuoptions=[qmuoptions ',''ymax2'',' num2str(ymax2)]; end
+if exist(options,'cdfplt'), cdfplt=getfieldvalue(options,'cdfplt'); qmuoptions=[qmuoptions ',''cdfplt'',''' cdfplt '''']; end
+if exist(options,'cdfleg'), cdfleg=getfieldvalue(options,'cdfleg'); qmuoptions=[qmuoptions ',''cdfleg'',''' cdfleg '''']; end
+if exist(options,'nrmplt'), nrmplt=getfieldvalue(options,'nrmplt'); qmuoptions=[qmuoptions ',''nrmplt'',''' nrmplt '''']; end
+if exist(options,'EdgeColor'), EdgeColor=getfieldvalue(options,'EdgeColor'); qmuoptions=[qmuoptions ',''EdgeColor'',''' EdgeColor '''']; end
+if exist(options,'FaceColor'), FaceColor=getfieldvalue(options,'FaceColor'); qmuoptions=[qmuoptions ',''FaceColor'',''' FaceColor '''']; end
+
+%use qmu plot
+eval(['plot_hist_norm(qmudata' qmuoptions ');']);
+
+%apply options
+options=changefieldvalue(options,'colorbar','off');
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_qmumean.m
===================================================================
--- /issm/trunk/src/m/plot/plot_qmumean.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_qmumean.m	(revision 13395)
@@ -0,0 +1,59 @@
+function plot_qmumean(md,options,nlines,ncols,i);
+%PLOT_QMUMEAN - plot mean of a scaled response 
+%
+%   Usage:
+%      plot_qmumean(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%find response function
+if exist(options,'qmudata'), 
+	descriptor=getfieldvalue(options,'qmudata'); 
+	if ~ischar(descriptor),
+		error('plot_qmumean error message:  descriptor should be a string');
+	end
+else 
+	error('plot_qmumean error message:  provide descriptor of response function in ''qmudata'' option');
+end
+
+%go pick up the response: 
+allresponses=md.qmu.results.dresp_out;
+responses=zeros(md.qmu.numberofpartitions,1);
+
+count=1;
+for i=1:length(allresponses),
+	d=allresponses(i).descriptor;
+	if strncmpi(d,'scaled_',7),
+		d=d(8:end);
+		if strncmpi(d,descriptor,length(descriptor)),
+			responses(count)=allresponses(i).mean;
+			count=count+1;
+		end
+	end
+end
+
+%log?
+if exist(options,'log'),
+	responses=log(responses)/log(getfieldvalue(options,'log'));
+end
+
+%now, project onto vertices
+responses_on_node=responses(md.qmu.partition+1);
+
+%plot
+A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', responses_on_node,'FaceColor','interp','EdgeColor',edgecolor);
+
+%apply options
+options=addfielddefault(options,'title',['Mean distribution of ' descriptor]);
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_qmunormplot.m
===================================================================
--- /issm/trunk/src/m/plot/plot_qmunormplot.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_qmunormplot.m	(revision 13395)
@@ -0,0 +1,45 @@
+%
+%  plot a normal probability plot of the response functions.
+%
+%  []=plot_normplot(rfunc)
+%
+function []=plot_qmunormplot(rfunc,width,ii)
+
+if ~nargin
+    help plot_normplot
+    return
+end
+
+%%  assemble the data into a matrix
+
+desc=cell (1,length(rfunc));
+for i=1:length(rfunc)
+    ldata(i)=length(rfunc(i).sample);
+end
+data=zeros(max(ldata),length(rfunc));
+
+for i=1:length(rfunc)
+    desc(i)=cellstr(rfunc(i).descriptor);
+    data(1:ldata(i),i)=rfunc(i).sample;
+end
+
+%standard plot:
+subplot(width,width,ii);
+
+%%  draw the plot
+
+%  draw normal probability plot
+
+normplot(data)
+ax1=gca;
+
+%  add the annotation
+
+title('Normal Probability Plot of Design Variables and/or Response Functions')
+xlabel('Value')
+ylabel('Probability')
+
+hleg1=legend(ax1,desc,'Location','EastOutside',...
+             'Orientation','vertical','Interpreter','none');
+
+end
Index: /issm/trunk/src/m/plot/plot_qmustddev.m
===================================================================
--- /issm/trunk/src/m/plot/plot_qmustddev.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_qmustddev.m	(revision 13395)
@@ -0,0 +1,60 @@
+function plot_qmustddev(md,options,nlines,ncols,i);
+%PLOT_QMUMEAN - plot stddev of a scaled response 
+%
+%   Usage:
+%      plot_qmustddev(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh
+subplot(nlines,ncols,i); 
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%find response function
+if exist(options,'qmudata'), 
+	descriptor=getfieldvalue(options,'qmudata'); 
+	if ~ischar(descriptor),
+		error('plot_qmustddev error message:  descriptor should be a string');
+	end
+else 
+	error('plot_qmustddev error message:  provide descriptor of response function in ''qmudata'' option');
+end
+
+%go pick up the response: 
+allresponses=md.qmu.results.dresp_out;
+responses=zeros(md.qmu.numberofpartitions,1);
+
+count=1;
+for i=1:length(allresponses),
+	d=allresponses(i).descriptor;
+	if strncmpi(d,'scaled_',7),
+		d=d(8:end);
+		if strncmpi(d,descriptor,length(descriptor)),
+			responses(count)=allresponses(i).stddev/allresponses(i).mean*100;
+			count=count+1;
+		end
+	end
+end
+
+%log?
+if exist(options,'log'),
+	responses=log(responses)/log(getfieldvalue(options,'log'));
+end
+
+
+%now, project onto vertices
+responses_on_node=responses(md.qmu.partition+1);
+
+%plot
+A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', responses_on_node,'FaceColor','interp','EdgeColor',edgecolor);
+
+%apply options
+options=addfielddefault(options,'title',['Stddev  distribution of ' descriptor ' in %']);
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_quiver.m
===================================================================
--- /issm/trunk/src/m/plot/plot_quiver.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_quiver.m	(revision 13395)
@@ -0,0 +1,26 @@
+function plot_quiver(x,y,u,v,options),
+%PLOT_QUIVER - quiver plot with colors
+%
+%   to be perfected tomorrow
+%
+%   Usage:
+%      plot_quiver(x,y,u,v,options)
+%
+%   Example:
+%      plot_quiver(md.mesh.x,md.mesh.y,md.initialization.vx,md.initialization.vy,options);
+
+%process fields
+[quivers,palette]=quiver_process(x,y,u,v,options);
+
+%loop over the number of colors
+hold on
+h=[];
+for i=1:quivers.numcolors
+	pos=find(quivers.colorind==i);
+	hprime=quiver(quivers.x(pos),quivers.y(pos),quivers.u(pos),quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	h=[h;hprime];
+end
+
+%take care of colorbar
+quiver_colorbar(quivers,options);
Index: /issm/trunk/src/m/plot/plot_quiver3.m
===================================================================
--- /issm/trunk/src/m/plot/plot_quiver3.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_quiver3.m	(revision 13395)
@@ -0,0 +1,104 @@
+function plot_quiver3(x,y,z,u,v,w,options),
+%PLOT_QUIVER3 - 3d quiver plot with colors
+%
+%   to be perfected tomorrow
+%
+%   Usage:
+%      plot_quiver3(x,y,z,u,v,w,options)
+%
+%   Example:
+%      plot_quiver(md.mesh.x,md.mesh.y,md.mesh.z,md.initialization.vx,md.initialization.vy,md.initialization.vz,options);
+
+%keep only non NaN elements
+pos=find(~isnan(x) & ~isnan(y) & ~isnan(z) & ~isnan(u) & ~isnan(v) & ~isnan(w));
+x=x(pos); y=y(pos); z=z(pos);
+u=u(pos); v=v(pos); w=w(pos);
+
+%get norm Min and Max
+Norm=sqrt(u.^2+v.^2+w.^2);
+Min=min(Norm);
+Max=max(Norm);
+
+%process options: scaling factor?
+scalingfactor=getfieldvalue(options,'scaling',0.40);
+
+%number of colors?
+colorlevels=getfieldvalue(options,'colorlevels',NaN);
+if isnumeric(colorlevels),
+	if isnan(colorlevels),
+		numcolors=30;
+	else
+		numcolors=colorlevels;
+	end
+	levels=round_ice(linspace(Min,Max,numcolors+1),2);
+else
+	levels=zeros(1,length(colorlevels)+2);
+	levels(1)=Min;
+	for i=1:length(colorlevels)
+		levels(i+1)=colorlevels{i};
+	end
+	levels(end)=Max;
+	levels=sort(unique(levels));
+	numcolors=length(levels)-1;
+end
+
+%set the colormap 
+if numcolors==2;
+	%blue and red
+	c=[0 0 1;1 0 0];
+elseif numcolors==3,
+	%blue yellow and red
+	c=[0 0 1;1 1 0;1 0 0];
+else
+	%let jet choose
+	c=colormap(jet(numcolors));
+end
+
+%Scale data
+if strcmpi(getfieldvalue(options,'autoscale','on'),'off'),
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./Norm;
+	v=scalingfactor*sqrt(delta)*v./Norm;
+else
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./max(Norm);
+	v=scalingfactor*sqrt(delta)*v./max(Norm);
+end
+
+%loop over the number of colors
+hold on
+h=[];
+for i=1:numcolors
+	pos=find( (Norm>=levels(i)) & (Norm<=levels(i+1)) );
+	hprime=quiver3(x(pos),y(pos),z(pos),u(pos),v(pos),w(pos),'Color',c(i,:),'ShowArrowHead','on','AutoScale','off');
+	h=[h;hprime];
+end
+
+%take care of colorbar
+if  ~strcmpi(getfieldvalue(options,'colorbar','on'),'off'),
+
+	%build ticks
+	hcb=colorbar('peer',gca,'location','EastOutside');
+	ticklabel=cell(1,length(levels));
+	for i=1:length(levels),
+		ticklabel{i}=num2str(round_ice(levels(i),3));
+	end
+	tickpos=1:numcolors+1;
+
+	%remove ticks if to many have been created
+	proportion=round(length(levels)/10);
+	if proportion>1,
+		ticklabel=ticklabel(1:proportion:end);
+		tickpos=tickpos(1:proportion:end);
+	end
+
+	%draw colorbar
+	set(hcb,'YTickLabel',ticklabel,'YTick',tickpos);
+	%position
+	if exist(options,'colorbarpos'),
+		set(hcb,'Position',getfieldvalue(options,'colorbarpos'));
+	end
+	%fontsize
+	fontsize=getfieldvalue(options,'fontsize',14);
+	set(hcb,'FontSize',fontsize);
+end
Index: /issm/trunk/src/m/plot/plot_referential.m
===================================================================
--- /issm/trunk/src/m/plot/plot_referential.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_referential.m	(revision 13395)
@@ -0,0 +1,91 @@
+function plot_referential(md,options,width,i,data);
+%PLOT_PRESSURELOAD - plot segment on neumann BC
+%
+%   Usage:
+%      plot_referential(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+referential=md.diagnostic.referential;
+
+Xhat=md.diagnostic.referential(:,1:3);
+pos=find(sum(isnan(Xhat),2));
+Xhat(pos,:)=repmat([1 0 0],size(pos,1),1);
+Xhatnorm=sqrt(Xhat(:,1).^2+Xhat(:,2).^2+Xhat(:,3).^2);
+Xhat=Xhat./[Xhatnorm Xhatnorm Xhatnorm];
+
+Zhat=md.diagnostic.referential(:,4:6);
+pos=find(sum(isnan(Zhat),2));
+Zhat(pos,:)=repmat([0 0 1],size(pos,1),1);
+Zhatnorm=sqrt(Zhat(:,1).^2+Zhat(:,2).^2+Zhat(:,3).^2);
+Zhat=Zhat./[Zhatnorm Zhatnorm Zhatnorm];
+
+Yhat=cross(Zhat,Xhat);
+
+if (md.mesh.dimension==2),
+
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	xstart=x;
+	ystart=y;
+	zstart=z;
+	edgex=max(md.mesh.x(elements),[],2)-min(md.mesh.x(elements),[],2);
+	len=min(edgex)/1.5;
+	%plot X axis
+	xend=xstart+len*Xhat(:,1);
+	yend=ystart+len*Xhat(:,2);
+	hx=quiver(xstart,ystart,xend-xstart,yend-ystart,'Color','blue','ShowArrowHead','on','AutoScale','off');
+	%plot Y axis
+	xend=xstart+len*Yhat(:,1);
+	yend=ystart+len*Yhat(:,2);
+	hy=quiver(xstart,ystart,xend-xstart,yend-ystart,'Color','red','ShowArrowHead','on','AutoScale','off');
+
+	legend([hx,hy],'local X direction','local Y direction')
+else
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	h1=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	xstart=x;
+	ystart=y;
+	zstart=z;
+	edgex=max(md.mesh.x(elements),[],2)-min(md.mesh.x(elements),[],2);
+	edgez=max(md.mesh.z(elements),[],2)-min(md.mesh.z(elements),[],2);
+	len=min(edgex)/1.5;
+	lenz=min(edgez)/1.5;
+	%plot X axis
+	xend=xstart+len*Xhat(:,1);
+	yend=ystart+len*Xhat(:,2);
+	zend=zstart+len*Xhat(:,3);
+	hx=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zend-zstart,'Color','blue','ShowArrowHead','on','AutoScale','off');
+	%plot Y axis
+	xend=xstart+len*Yhat(:,1);
+	yend=ystart+len*Yhat(:,2);
+	zend=zstart+len*Yhat(:,3);
+	hy=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zend-zstart,'Color','red','ShowArrowHead','on','AutoScale','off');
+	%plot Z axis
+	xend=xstart+lenz*Zhat(:,1);
+	yend=ystart+lenz*Zhat(:,2);
+	zend=zstart+lenz*Zhat(:,3);
+	hz=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zend-zstart,'Color','green','ShowArrowHead','on','AutoScale','off');
+
+	legend([hx,hy,hz],'local X direction','local Y direction','local Z direction')
+end
+
+%apply options
+options=addfielddefault(options,'title','Diagnostic referential');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_riftfraction.m
===================================================================
--- /issm/trunk/src/m/plot/plot_riftfraction.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_riftfraction.m	(revision 13395)
@@ -0,0 +1,48 @@
+function plot_riftfraction(md,options,nlines,ncols,index);
+%PLOT_RIFTFRACTION - plot rift fractions
+%
+%   Usage:
+%      plot_riftfraction(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%check that there is something in riftproperties
+if isnan(md.rifts.riftstruct.riftproperties),
+	error('plot_riftfraction error message: field riftproperies is empty, run the model first')
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');
+end
+
+%first, build a vector of fractions, over all nodes. 
+fractions=zeros(md.mesh.numberofvertices,1);
+
+%complete the tips.
+for i=1:length(md.rifts.riftstruct), 
+	tips=md.rifts.riftstruct(i).tips;
+	fractions(tips)=1;
+end
+
+hold on;
+for i=1:length(md.rifts.riftstruct), 
+	segments=md.rifts.riftstruct(i).segments(:,1:2)';
+	xc=x(segments(:));
+	yc=y(segments(:));
+	zc=fractions(segments(:));
+	h2=patch('Xdata',xc,'Ydata',yc,'Zdata',zc,'Cdata',zc,'facecolor','none','edgecolor','flat');
+end
+legend([h1,h2],'mesh boundaries','rifts')
+hold off
+
+%apply options
+options=addfielddefault(options,'title','Rift ice/water fraction ???????'); %Eric, could you enter a better title?
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_riftnumbering.m
===================================================================
--- /issm/trunk/src/m/plot/plot_riftnumbering.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_riftnumbering.m	(revision 13395)
@@ -0,0 +1,94 @@
+function plot_riftnumbering(md,options,nlines,ncols,index);
+%PLOT_RIFTNUMBERING - plot rift penetration + numbering of all rift vertices, as well as rift numbers.
+%
+%   Usage:
+%      plot_riftnumbering(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+fontsize=getfieldvalue(options,'FontSize',8);
+
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');
+end
+
+isp1=0;
+isp2=0;
+
+if isstruct(md.rifts.riftstruct),
+	%plot mesh boundaries
+	for i=1:size(md.mesh.segments,1),
+		h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+	end
+	for i=1:size(md.rifts.riftstruct,1),
+		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+		segments=md.rifts.riftstruct(i).segments;
+		for j=1:size(segments,1),
+			plot(x(segments(j,1:2)),y(segments(j,1:2)),'b-');
+		end
+
+		normal=zeros(2,1);
+		for j=1:size(penaltypairs,1),
+			normal(1)=penaltypairs(j,5);
+			normal(2)=penaltypairs(j,6);
+
+			vx1=md.initialization.vx(penaltypairs(j,1)); 
+			vx2=md.initialization.vx(penaltypairs(j,2));
+			vy1=md.initialization.vy(penaltypairs(j,1)); 
+			vy2=md.initialization.vy(penaltypairs(j,2));
+			penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+			%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+			if(penetration>0),
+				p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ro-','LineWidth',1);
+				set(p2,'MarkerSize',3);
+				isp2=1;
+			else
+				p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ko-','LineWidth',1);
+				set(p1,'MarkerSize',3);
+				isp1=1;
+			end
+		end
+
+		%point out the tips
+		h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+		plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	end
+	if strcmpi(getfieldvalue(options,'legend','on'),'on'),
+		if isp1 & isp2
+			l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
+		elseif isp1
+			l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
+		elseif isp2
+			l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
+		else
+			l=legend([h1,h2],'mesh boundaries','crack tips');
+		end
+		set(l,'Location',getfieldvalue(options,'legend_location','NorthEast'));
+	end
+else
+	error('plot error message: no rifts available!');
+end
+
+%Now, plot rift vertices numbers.
+for i=1:size(md.rifts.riftstruct,1),
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+	for j=1:size(penaltypairs,1),
+		node=penaltypairs(j,1);
+		t=text(x(node),y(node),[num2str(i) '.' num2str(j)]);
+		set(t,'FontSize',fontsize);
+	end
+end
+
+
+%apply options
+options=addfielddefault(options,'title','Rift/Fault location');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_riftpenetration.m
===================================================================
--- /issm/trunk/src/m/plot/plot_riftpenetration.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_riftpenetration.m	(revision 13395)
@@ -0,0 +1,82 @@
+function plot_rifpenetration(md,options,nlines,ncols,index);
+%PLOT_RIFTPENETRATION - plot rift penetration
+%
+%   Usage:
+%      plot_rifpenetration(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k-');
+end
+
+isp1=0;
+isp2=0;
+
+if isstruct(md.rifts.riftstruct),
+	%plot mesh boundaries
+	for i=1:size(md.mesh.segments,1),
+		h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+	end
+	for i=1:size(md.rifts.riftstruct,1),
+		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+		segments=md.rifts.riftstruct(i).segments;
+		for j=1:size(segments,1),
+			plot(x(segments(j,1:2)),y(segments(j,1:2)),'b-');
+		end
+
+		normal=zeros(2,1);
+		for j=1:size(penaltypairs,1),
+			normal(1)=penaltypairs(j,5);
+			normal(2)=penaltypairs(j,6);
+
+			vx1=md.initialization.vx(penaltypairs(j,1)); 
+			vx2=md.initialization.vx(penaltypairs(j,2));
+			vy1=md.initialization.vy(penaltypairs(j,1)); 
+			vy2=md.initialization.vy(penaltypairs(j,2));
+			penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+			%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+			if(penetration>0),
+				p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ro-','LineWidth',1);
+				set(p2,'MarkerSize',3);
+				isp2=1;
+			else
+				p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'ko-','LineWidth',1);
+				set(p1,'MarkerSize',3);
+				isp1=1;
+			end
+		end
+
+		%point out the tips
+		h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+		plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	end
+	if strcmpi(getfieldvalue(options,'legend','on'),'on'),
+		if isp1 & isp2
+			l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
+		elseif isp1
+			l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
+		elseif isp2
+			l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
+		else
+			l=legend([h1,h2],'mesh boundaries','crack tips');
+		end
+		set(l,'Location',getfieldvalue(options,'legend_location','NorthEast'));
+	end
+else
+	error('plot error message: no rifts available!');
+end
+hold off
+
+%apply options
+options=addfielddefault(options,'title','Rift/Fault location');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_riftrelvel.m
===================================================================
--- /issm/trunk/src/m/plot/plot_riftrelvel.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_riftrelvel.m	(revision 13395)
@@ -0,0 +1,115 @@
+function plot_riftrelvel(md,options,nlines,ncols,index);
+%PLOT_RIFTRELVEL - plot rift relative velocities
+%
+%   Usage:
+%      plot_riftrelvel(md,options,nlines,ncols,i);
+%
+%   See also: PLOTMODEL
+
+%some checks
+if (length(md.initialization.vx)~=md.mesh.numberofvertices | length(md.initialization.vy)~=md.mesh.numberofvertices),
+	error('plot_riftvel error message: vx and vy do not have the right size'),
+end
+if ~isstruct(md.rifts.riftstruct),
+	error('plot error message: no rifts available!');
+end
+options=addfielddefault(options,'scaling',2);
+
+%recover vx and vy:
+vx=getfieldvalue(options,'riftrelvel_vx',md.initialization.vx);
+vy=getfieldvalue(options,'riftrelvel_vy',md.initialization.vy);
+
+%set as NaN all velocities not on rifts
+u=NaN*ones(md.mesh.numberofvertices,1);
+v=NaN*ones(md.mesh.numberofvertices,1);
+for i=1:size(md.rifts.riftstruct,1),
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs(:,[1 2]);
+	u(md.rifts.riftstruct(i).penaltypairs(:,1))=vx(penaltypairs(:,1))-vx(penaltypairs(:,2));
+	v(md.rifts.riftstruct(i).penaltypairs(:,1))=vy(penaltypairs(:,1))-vy(penaltypairs(:,2));
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[vel datatype]=processdata(md,[u v],options);
+[quivers,palette]=quiver_process(x,y,vel(:,1),vel(:,2),options);
+
+%prepare plot
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k-');
+end
+
+%plot rifts vel
+h3=[];
+for i=1:quivers.numcolors
+	pos=find(quivers.colorind==i);
+	hprime=quiver(quivers.x(pos),quivers.y(pos),quivers.u(pos),quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	hprime=quiver(quivers.x(pos),quivers.y(pos),-quivers.u(pos),-quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	h3=[h3;hprime];
+end
+
+%plot rift velocities
+isp1=0;
+isp2=0;
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+end
+for i=1:size(md.rifts.riftstruct,1),
+	
+	%get nodes on rift
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+	segments=md.rifts.riftstruct(i).segments;
+	for j=1:size(segments,1),
+		plot(x(segments(j,1:2)),y(segments(j,1:2)),'k-');
+	end
+
+	normal=zeros(2,1);
+	for j=1:size(penaltypairs,1),
+		normal(1)=penaltypairs(j,5);
+		normal(2)=penaltypairs(j,6);
+
+		vx1=vx(penaltypairs(j,1)); vx2=vx(penaltypairs(j,2)); vy1=vy(penaltypairs(j,1)); vy2=vy(penaltypairs(j,2));
+		penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+		%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+		if(penetration>0),
+			p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'*'); set(p2,'Color',[140 140 140]/255);
+			isp2=1;
+		else
+			p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'k*');
+			isp1=1;
+		end
+	end
+
+	%point out the tips
+	h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+	plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	segments=md.rifts.riftstruct(i).segments(:,1:2);
+end
+%legend
+if strcmpi(getfieldvalue(options,'legend','on'),'on'),
+	if isp1 & isp2
+		l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
+	elseif isp1
+		l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
+	elseif isp2
+		l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
+	else
+		l=legend([h1,h2],'mesh boundaries','crack tips');
+	end
+set(l,'Location',getfieldvalue(options,'legend_location','NorthEast'));
+end
+hold off
+
+%apply options
+quiver_colorbar(quivers,options);
+options=changefieldvalue(options,'colorbar',2);
+options=addfielddefault(options,'title','Rift/Fault Relative Velocity');
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_rifts.m
===================================================================
--- /issm/trunk/src/m/plot/plot_rifts.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_rifts.m	(revision 13395)
@@ -0,0 +1,77 @@
+function plot_rifts(md,options,nlines,ncols,index);
+%PLOT_RIFTS - plot rifts in a mesh
+%
+%   Usage:
+%      plot_rifts(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot mesh
+subplot(nlines,ncols,index); 
+
+%offset to separate rift flanks.
+offset=getfieldvalue(options,'offset',500);
+if isstruct(md.rifts.riftstruct),
+	
+	for i=1:size(md.rifts.riftstruct,1),
+		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+		normal=zeros(2,1);
+		for j=1:size(penaltypairs,1),
+			normal(1)=penaltypairs(j,5);
+			normal(2)=penaltypairs(j,6);
+			x(penaltypairs(j,1))=x(penaltypairs(j,1))-normal(1)*offset;
+			y(penaltypairs(j,1))=y(penaltypairs(j,1))-normal(2)*offset;
+		end
+		if length(md.rifts.riftstruct(i).tips)==3,
+			tip=md.rifts.riftstruct(i).tips(3);
+			%who is tip connected to? 
+			if isconnected(md.mesh.elements,penaltypairs(1,1),tip),
+				normal(1)=penaltypairs(1,5);
+				normal(2)=penaltypairs(1,6);
+				x(tip)=x(tip)-normal(1)*offset;
+				y(tip)=y(tip)-normal(2)*offset;
+			end
+
+			if isconnected(md.mesh.elements,penaltypairs(1,2),tip),
+				normal(1)=penaltypairs(1,5);
+				normal(2)=penaltypairs(1,6);
+				x(tip)=x(tip)+normal(1)*offset;
+				y(tip)=y(tip)+normal(2)*offset;
+			end
+			if isconnected(md.mesh.elements,penaltypairs(end,1),tip),
+				normal(1)=penaltypairs(end,5);
+				normal(2)=penaltypairs(end,6);
+				x(tip)=x(tip)-normal(1)*offset;
+				y(tip)=y(tip)-normal(2)*offset;
+			end
+			if isconnected(md.mesh.elements,penaltypairs(end,2),tip),
+				normal(1)=penaltypairs(end,5);
+				normal(2)=penaltypairs(end,6);
+				x(tip)=x(tip)+normal(1)*offset;
+				y(tip)=y(tip)+normal(2)*offset;
+			end
+		end
+	end
+end
+
+%plot mesh
+if is2d
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+else
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C ], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F ], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+end
+
+%apply options
+options=addfielddefault(options,'title','Rifts');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_riftvel.m
===================================================================
--- /issm/trunk/src/m/plot/plot_riftvel.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_riftvel.m	(revision 13395)
@@ -0,0 +1,108 @@
+function plot_riftvel(md,options,nlines,ncols,index);
+%PLOT_RIFTVEL - plot rift velocity
+%
+%   Usage:
+%      plot_riftvel(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%some checks
+if (length(md.initialization.vx)~=md.mesh.numberofvertices | length(md.initialization.vy)~=md.mesh.numberofvertices),
+	error('plot_riftvel error message: vx and vy do not have the right size'),
+end
+if ~isstruct(md.rifts.riftstruct),
+	error('plot error message: no rifts available!');
+end
+options=addfielddefault(options,'scaling',2);
+
+%set as NaN all velocities not on rifts
+u=NaN*ones(md.mesh.numberofvertices,1);
+v=NaN*ones(md.mesh.numberofvertices,1);
+for i=1:size(md.rifts.riftstruct,1),
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs(:,[1 2]);
+	u(penaltypairs(:))=md.initialization.vx(penaltypairs(:));
+	v(penaltypairs(:))=md.initialization.vy(penaltypairs(:));
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[vel datatype]=processdata(md,[u v],options);
+[quivers,palette]=quiver_process(x,y,vel(:,1),vel(:,2),options);
+
+%prepare plot
+subplot(nlines,ncols,index); 
+hold on
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k.-');
+end
+
+%plot rifts vel
+h3=[];
+for i=1:quivers.numcolors
+	pos=find(quivers.colorind==i);
+	hprime=quiver(quivers.x(pos),quivers.y(pos),quivers.u(pos),quivers.v(pos),...
+		'Color',palette(i,:),'ShowArrowHead','on','AutoScale','off');
+	h3=[h3;hprime];
+end
+
+%plot rift velocities
+isp1=0;
+isp2=0;
+
+%plot mesh boundaries
+for i=1:size(md.mesh.segments,1),
+	h1=plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'b-');
+end
+
+for i=1:size(md.rifts.riftstruct,1),
+	%get nodes on rift
+	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
+
+	segments=md.rifts.riftstruct(i).segments;
+	for j=1:size(segments,1),
+		plot(x(segments(j,1:2)),y(segments(j,1:2)),'b-');
+	end
+
+	normal=zeros(2,1);
+	for j=1:size(penaltypairs,1),
+		normal(1)=penaltypairs(j,5);
+		normal(2)=penaltypairs(j,6);
+
+		vx1=md.initialization.vx(penaltypairs(j,1)); vx2=md.initialization.vx(penaltypairs(j,2)); vy1=md.initialization.vy(penaltypairs(j,1)); vy2=md.initialization.vy(penaltypairs(j,2));
+		penetration=(vx2-vx1)*normal(1)+(vy2-vy1)*normal(2);
+		%if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
+		if(penetration>0),
+			p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'*'); set(p2,'Color',[140 140 140]/255);
+			isp2=1;
+		else
+			p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'k*');
+			isp1=1;
+		end
+	end
+
+	%point out the tips
+	h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
+	plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
+	segments=md.rifts.riftstruct(i).segments(:,1:2);
+end
+
+
+%legend
+if isp1 & isp2
+	legend([h1,h2,p1,p2],'mesh boundaries','rift tips',' rifts closing','rifts opening')
+elseif isp1
+	legend([h1,h2,p1],'mesh boundaries','rift tips',' rifts closing')
+elseif isp2
+	legend([h1,h2,p2],'mesh boundaries','rift tips','rifts opening')
+else
+	legend([h1,h2],'mesh boundaries','rift tips')
+end
+hold off
+
+%apply options
+quiver_colorbar(quivers,options);
+options=changefieldvalue(options,'colorbar',2);
+options=addfielddefault(options,'title','Rift Velocities');
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_sarpwr.m
===================================================================
--- /issm/trunk/src/m/plot/plot_sarpwr.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_sarpwr.m	(revision 13395)
@@ -0,0 +1,26 @@
+function plot_sarpwr(md,options,width,i);
+%PLOT_SARPWR - plot radar image
+%
+%   Usage:
+%      plot_sarpwr(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh sarpwr
+subplot(width,width,i); 
+
+%units
+if exist(options,'unit'),
+	unit=getfieldvalue(options,'unit');
+	md.mesh.x=md.mesh.x*unit;
+	md.mesh.y=md.mesh.y*unit;
+	md.mesh.z=md.mesh.z*unit;
+end
+					
+imagesc(md.radaroverlay.x,md.radaroverlay.y,double(md.radaroverlay.pwr)),set(gca,'YDir','normal');colormap(gray);
+
+%apply options
+options=addfielddefault(options,'colorbar',0);
+options=changefieldvalue(options,'colormap','gray');
+
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_scatter.m
===================================================================
--- /issm/trunk/src/m/plot/plot_scatter.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_scatter.m	(revision 13395)
@@ -0,0 +1,59 @@
+function plot_scatter(x,y,level,options),
+
+if nargin==3, options=pairoptions(); end
+
+%check input
+if numel(x)~=numel(y) | numel(x)~=numel(level),
+	error('x, y and data should have the same size');
+end
+
+%Some processing
+Min=min(level);
+Max=max(level);
+Siz=length(level);
+nlab=10;
+
+%OK, should we create a new colorbar for the occasion?
+if isempty(findobj(gcf,'tag','TMW_COLORBAR')),
+	alreadyplot=false;
+else
+	alreadyplot=true;
+end
+
+%generate levels
+if (alreadyplot),
+	phch = get(findall(gcf,'type','image','tag','TMW_COLORBAR'),{'parent'});
+	h    = phch{1};
+	ylim=get(h,'YLim');
+	palette=colormap;
+	numcolors=size(palette,1);
+	levels=round_ice(linspace(ylim(1),ylim(2),numcolors+1),2);
+else
+	palette=getcolormap(options);
+	numcolors=size(palette,1);
+	levels=round_ice(linspace(Min,Max,numcolors+1),2);
+end
+
+colorind=ones(Siz,1);
+for i=1:numcolors
+	pos=find((level>=levels(i)) & (level<=levels(i+1)) );
+	colorind(pos)=i;
+end
+colorind(find(level>levels(end)))=numcolors;
+
+%loop over the number of colors
+hold on
+hp=[];
+for i=1:numcolors
+	pos=find(colorind==i);
+	hprime=plot3(x(pos),y(pos),ones(size(x(pos))),...
+		'o','MarkerSize',getfieldvalue(options,'MarkerSize',3),'MarkerEdgeColor',palette(i,:),...
+		'MarkerFaceColor',palette(i,:));
+	hp=[hp;hprime];
+end
+
+if ~alreadyplot,
+	% format the colorbar
+	h    = colorbar;
+	caxis([min(levels) max(levels)]);
+end
Index: /issm/trunk/src/m/plot/plot_section.m
===================================================================
--- /issm/trunk/src/m/plot/plot_section.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_section.m	(revision 13395)
@@ -0,0 +1,210 @@
+function plot_section(md,data,options,nlines,ncols,i)
+%PLOT_SECTION - plot a given field on a section
+%
+%   Usage:
+%      plot_section(md,data,options,nlines,ncols,i)
+%
+%   See also: PLOTMODEL
+
+%How many subplots?
+if exist(options,'showsection')
+
+	%Compute the indexes of the 2 plots (one for the sectionvalue and one for showsection
+	upperplots=floor((i-1)/ncols);
+	if upperplots==0, leftplots=i-1; else leftplots=i-ncols*upperplots-1; end
+	index1=4*ncols*upperplots+2*leftplots+1;
+	index2=index1+1;
+	ncols=2*ncols;
+else
+	index1=i;
+end
+
+%process model
+[x_m y_m z_m elements_m is2d isplanet]=processmesh(md,[],options);
+
+%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
+
+%replug x and y onto model so that SectionValue treats the problem correctly
+md3d=md;
+if exist(options,'layer')
+	md.mesh.x=md.mesh.x2d; md.mesh.y=md.mesh.y2d; md.mesh.elements=md.mesh.elements2d; md.mesh.dimension=2;
+end
+
+%read contours: 
+profiles=expread(getfieldvalue(options,'sectionvalue'));
+numprofiles=length(profiles);
+
+%Loop over number of profiles: 
+for profile_i=1:numprofiles,
+	profile=profiles(profile_i);
+
+	%Loop over number of curves
+	for i=1:numcurves,
+
+		[datai datatype]=processdata(md3d,data(:,i),options);
+
+		%resolution
+		if exist(options,'resolution'),
+			resolution=getfieldvalue(options,'resolution');
+		else %Default resolution
+			resolution=[1000 10*md.mesh.numberoflayers];
+			disp(['plot_section warning: no resolution specified, use default resolution: [horizontal_resolution vertical_resolution]=[' num2str(resolution)  ']']);
+		end
+
+		%Compute section value
+		[elements,x,y,z,s,data_s]=SectionValues(md,datai,profile,resolution);
+
+		%units
+		if exist(options,'unit'),
+			unit=getfieldvalue(options,'unit');
+			x=x*unit;
+			y=y*unit;
+			z=z*unit;
+			s=s*unit;
+		end
+
+		%2D
+		if is2d,
+%		%plot section value
+%		hold on;
+%		subplot(nlines,ncols,index1)
+%		%subplot(1,3,[2 3])
+%		plot(s,data_s,'color',color(i,:),'LineWidth',getfieldvalue(options,'linewidth',1))
+%		%3D
+%	else
+%		%plot section value
+%		%if user requested view2: 2d plot with curvilinear coordinate
+%		if (getfieldvalue(options,'view',3)==2 )
+
+			%Show Section if requested by user
+			if exist(options,'showsection')
+
+				%compute number of labels
+				numlabels=min(getfieldvalue(options,'showsection'),length(s));
+				shift=fix(length(s)/numlabels);
+
+				%plot labels on current graph
+				hold on
+				text(s(1),data_s(1),'1','backgroundcolor',[0.8 0.9 0.8])
+				for i=2:numlabels-1
+					text(s(1+(i-1)*shift),data_s(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+				end
+				text(s(end),data_s(end),'end','backgroundcolor',[0.8 0.9 0.8])
+
+				%plot section only with labels
+				subplot(nlines,ncols,index2)
+				plot_unit(x_m,y_m,z_m,elements_m,data(:,i),is2d,isplanet,datatype,options)
+				hold on
+				text(x(1),y(1),'1','backgroundcolor',[0.8 0.9 0.8])
+				for i=2:numlabels-1
+					text(x(1+(i-1)*shift),y(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+				end
+				text(x(end),y(end),'end','backgroundcolor',[0.8 0.9 0.8])
+				plot(x,y,'-r')
+				axis([min(md.mesh.x)-1 max(md.mesh.x)+1 min(md.mesh.y)-1 max(md.mesh.y)+1])
+				view(2)
+			end
+
+			%plot section value
+			if(i==1), subplot(nlines,ncols,index1); end
+			plot(s,data_s,'color',color(i,:),'LineWidth',getfieldvalue(options,'linewidth',1))
+			hold on
+
+
+			%3D
+		else
+			%plot section value
+			%if user requested view2: 2d plot with curvilinear coordinate
+			if (getfieldvalue(options,'view',3)==2 )
+
+				%Show Section if requested by user
+				if exist(options,'showsection')
+
+					%compute number of labels
+					numlabels=min(getfieldvalue(options,'showsection'),length(s));
+					shift=fix(length(s)/numlabels);
+
+					%plot labels on current graph
+					hold on
+					text(s(1),z(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(s(1+(i-1)*shift),z(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(s(end),z(end),'end','backgroundcolor',[0.8 0.9 0.8])
+
+					%plot section only with labels
+					subplot(nlines,ncols,index2)
+					plot_unit(x_m,y_m,z_m,elements_m,data(:,i),is2d,datatype,options)
+					hold on
+					text(x(1),y(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(x(1+(i-1)*shift),y(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(x(end),y(end),'end','backgroundcolor',[0.8 0.9 0.8])
+					plot(x,y,'-r')
+					axis([min(md.mesh.x)-1 max(md.mesh.x)+1 min(md.mesh.y)-1 max(md.mesh.y)+1])
+					view(2)
+				end
+
+				subplot(nlines,ncols,index1)
+				A=elements(:,1); B=elements(:,2); C=elements(:,3);  D=elements(:,4); 
+				patch( 'Faces', [A B C D], 'Vertices', [s z zeros(length(s),1)],'FaceVertexCData',data_s,'FaceColor','interp','EdgeColor','none');
+
+			else
+
+				%Show Section if requested by user
+				if exist(options,'showsection')
+
+					%compute number of labels
+					numlabels=min(getfieldvalue(options,'showsection'),length(s));
+					shift=fix(length(x)/numlabels);
+
+					%plot labels on current graph
+					hold on
+					text(x(1),y(1),z(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(x(1+(i-1)*shift),y(1+(i-1)*shift),z(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(x(end),y(end),z(end),'end','backgroundcolor',[0.8 0.9 0.8])
+
+					%plot section only with labels
+					subplot(nlines,ncols,index2)
+					plot_unit(x_m,y_m,z_m,elements_m,data,is2d,datatype,options)
+					hold on
+					text(x(1),y(1),'1','backgroundcolor',[0.8 0.9 0.8])
+					for i=2:numlabels-1
+						text(x(1+(i-1)*shift),y(1+(i-1)*shift),num2str(i),'backgroundcolor',[0.8 0.9 0.8])
+					end
+					text(x(end),y(end),'end','backgroundcolor',[0.8 0.9 0.8])
+					plot(x,y,'-r')
+					axis([min(md.mesh.x)-1 max(md.mesh.x)+1 min(md.mesh.y)-1 max(md.mesh.y)+1])
+					view(2)
+				end
+
+				subplot(nlines,ncols,index1)
+				A=elements(:,1); B=elements(:,2); C=elements(:,3);  D=elements(:,4); 
+				patch( 'Faces', [A B C D], 'Vertices', [x y z],'FaceVertexCData',data_s,'FaceColor','interp','EdgeColor','none');
+				view(3)
+
+			end
+		end
+	end
+end
+
+%apply options
+options=addfielddefault(options,'title','Section value');
+if (md.mesh.dimension==2)
+	options=addfielddefault(options,'colorbar',0);
+end
+if ((md.mesh.dimension==2) | getfieldvalue(options,'view')==2 )
+	options=addfielddefault(options,'xlabel','Curvilinear coordinate');
+	options=addfielddefault(options,'axis','auto');
+end
+if (md.mesh.dimension==3 & getfieldvalue(options,'view')==2 )
+	options=addfielddefault(options,'ylabel','z');
+end
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_segments.m
===================================================================
--- /issm/trunk/src/m/plot/plot_segments.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_segments.m	(revision 13395)
@@ -0,0 +1,57 @@
+function plot_segments(md,options,width,i,datai);
+%PLOT_SEGMENTS - plot segments, with different colors according to segment markers.
+%
+%   Usage:
+%      plot_segments(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%plot mesh boundaries
+subplot(width,width,i); 
+
+%process mesh and data
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+segments=md.mesh.segments;
+
+if (md.mesh.dimension==2),
+	%plot mesh
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	h1=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	hold on;
+
+	%highlight elements on neumann
+	pos=segments(:,end);
+	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
+	h2=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+
+	if strcmpi(getfieldvalue(options,'segmentnumbering','off'),'on'),
+		text(sum(x(segments(:,1:2)),2)/2,sum(y(segments(:,1:2)),2)/2,sum(z(segments(:,1:2)),2)/2+1,...
+			num2str(md.mesh.segmentmarkers),...
+			'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+	end
+
+	%display arrows pointing outward
+	xstart=mean(x(segments(:,1:end-1)),2);
+	ystart=mean(y(segments(:,1:end-1)),2);
+	length=sqrt((x(segments(:,1))-x(segments(:,2))).^2 + (y(segments(:,1))-y(segments(:,2))).^2 );
+	normal(:,1)=cos(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+	normal(:,2)=sin(atan2((x(segments(:,1))-x(segments(:,2))) , (y(segments(:,2))-y(segments(:,1)))));
+	xend=xstart+length.*normal(:,1);
+	yend=ystart+length.*normal(:,2);
+	q=quiver(xstart,ystart,xend-xstart,yend-ystart); hold on;
+	h3=plot(xstart,ystart,'r*');
+
+
+else
+	error('plot_segments: 3d plot of segments not supported yet!');
+end
+
+%legend (disable warnings)
+warning off
+legend([h2,q],'element on segment','normal vectors')
+warning on
+
+%apply options
+options=addfielddefault(options,'title','Segment boundaries');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_streamlines.m
===================================================================
--- /issm/trunk/src/m/plot/plot_streamlines.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_streamlines.m	(revision 13395)
@@ -0,0 +1,41 @@
+function plot_streamlines(md,options)
+%PLOT_STREAMLINES - plot stream lines on a figure
+%
+%   Usage:
+%      plot_streamlines(md,options)
+
+%process data and model
+[x y z index is2d isplanet]=processmesh(md,[],options);
+[u datatype]=processdata(md,md.initialization.vx,options);
+[v datatype]=processdata(md,md.initialization.vy,options);
+
+%some checks
+if ~is2d,
+	disp('plot_streamlines error: streamlines option not supported for 3d plots. Project on a layer')
+	return
+end
+
+%initialize flowpath
+streamlines=getfieldvalue(options,'streamlines');
+if ischar(streamlines) & strcmpi(streamlines,'on');
+	streamlines=60;
+end
+if iscell(streamlines)
+	x0=[]; y0=[];
+	for i=1:size(streamlines,2)
+		coord=streamlines{i};
+		x0=[x0;coord(1)]; y0=[y0;coord(2)];
+	end
+else
+	x0=x(1:ceil(length(x)/streamlines):end);
+	y0=y(1:ceil(length(x)/streamlines):end);
+end
+
+%Get flow lines
+flowpath=flowlines(index,x,y,u,v,x0,y0);
+
+%plot
+hold on
+for i=1:length(flowpath)
+	patch('Xdata',[flowpath(i).x;NaN],'Ydata',[flowpath(i).y;NaN],'facecolor','none','edgecolor','y');
+end
Index: /issm/trunk/src/m/plot/plot_tensor.m
===================================================================
--- /issm/trunk/src/m/plot/plot_tensor.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_tensor.m	(revision 13395)
@@ -0,0 +1,40 @@
+function plot_tensor(md,options,width,i,type);
+%PLOT_TENSOR - plot tensor components
+%
+%   Usage:
+%      plot_tensor(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+h=subplot(width,width,i); axis off; pos=get(h,'Position');
+
+plot_options.offsetx=pos(1);
+plot_options.offsety=pos(2);
+plot_options.width=pos(3);
+plot_options.height=pos(4);
+
+%Figure out tensor type:
+%FIXME does not work anymore
+if strncmpi(type,'strain',6),
+	tensor=md.results.strainrate;
+elseif strncmpi(type,'stress',6),
+	tensor=md.results.stress;
+elseif strncmpi(type,'deviatoricstress',16),
+	tensor=md.results.deviatoricstress;
+else
+	error('plot_tensor error message: unsupported type of tensor');
+end
+
+%Figure out type of plot being requested
+if strncmpi(fliplr(type),fliplr('tensor'),6) | strcmpi(type,'strainrate') | strcmpi(type,'deviatoricstress') | strcmpi(type,'stress'),
+	plot_tensor_components(md,options,width,i,tensor,type,plot_options);
+	return;
+elseif strncmpi(fliplr(type),fliplr('principal'),9),
+	plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
+	return;
+elseif strncmpi(fliplr(type(1:end-1)),fliplr('principalaxis'),13),
+	plot_tensor_principalaxis(md,options,width,i,tensor,type,plot_options);
+	return;
+else
+	error('plot_tensor error message: unsurported type of plot');
+end
Index: /issm/trunk/src/m/plot/plot_tensor_components.m
===================================================================
--- /issm/trunk/src/m/plot/plot_tensor_components.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_tensor_components.m	(revision 13395)
@@ -0,0 +1,78 @@
+function plot_tensor_components(md,options,width,i,tensor,type,plot_options);
+%PLOT_TENSOR_COMPONENT - plot component of a tensor
+%
+%   Usage:
+%      plot_tensor_components(md,options,width,i,tensor,type,plot_option);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+%Compute the indexes of the components plots
+upperplots=fix((i-1)/width);
+if upperplots==0, leftplots=i-1; else leftplots=i-width*upperplots-1; end
+if (md.mesh.dimension==2)%3 components -> 3 indexes
+	index1=4*width*upperplots+2*leftplots+1;
+	index2=index1+1;
+	index3=index1+width*2;
+elseif md.mesh.dimension==3%6 components -> 6 indexes
+	index1=3*3*width*upperplots+3*leftplots+1;
+	index2=index1+1;
+	index3=index1+2;
+	index4=index1+width*3;
+	index5=index4+1;
+	index6=index4+2;
+end
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[tensor.xx datatype]=processdata(md,tensor.xx,options);
+[tensor.yy datatype]=processdata(md,tensor.yy,options);
+[tensor.xy datatype]=processdata(md,tensor.xy,options);
+if  md.mesh.dimension==3
+	[tensor.xz datatype]=processdata(md,tensor.xz,options);
+	[tensor.yz datatype]=processdata(md,tensor.yz,options);
+	[tensor.zz datatype]=processdata(md,tensor.zz,options);
+end
+
+if ((md.mesh.dimension==2)),
+	subplot(2*width,2*width,index1),
+	plot_unit(x,y,z,elements,tensor.xx,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xx')
+	subplot(2*width,2*width,index2),
+	plot_unit(x,y,z,elements,tensor.yy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'yy')
+	subplot(2*width,2*width,index3),
+	plot_unit(x,y,z,elements,tensor.xy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xy')
+else
+	subplot(3*width,3*width,index1),
+	plot_unit(x,y,z,elements,tensor.xx,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xx')
+	subplot(3*width,3*width,index2),
+	plot_unit(x,y,z,elements,tensor.yy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'yy')
+	subplot(3*width,3*width,index3),
+	plot_unit(x,y,z,elements,tensor.zz,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'zz')
+	subplot(3*width,3*width,index4),
+	plot_unit(x,y,z,elements,tensor.xy,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xy')
+	subplot(3*width,3*width,index5),
+	plot_unit(x,y,z,elements,tensor.xz,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'xz')
+	subplot(3*width,3*width,index6),
+	plot_unit(x,y,z,elements,tensor.yz,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'yz')
+end
+end
+
+function Apply_options_tensor(md,options,type,component)
+	%apply options
+	if ismember('_',type) %user plotet stress_tensor
+		strings=strsplit(type,'_');
+		string=strings{1};
+	else %default plot: user requested stress
+		string=type;
+	end
+	options=addfielddefault(options,'title',[upper(string(1)) string(2:end) ' ' component]);
+	applyoptions(md,[],options);
+end
Index: /issm/trunk/src/m/plot/plot_tensor_principal.m
===================================================================
--- /issm/trunk/src/m/plot/plot_tensor_principal.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_tensor_principal.m	(revision 13395)
@@ -0,0 +1,77 @@
+function plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
+%PLOT_TENSOR_PRINCIPAL - plot principal values
+%
+%   Usage:
+%      plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+%Compute the indexes of the components plots
+upperplots=fix((i-1)/width);
+if upperplots==0, leftplots=i-1; else leftplots=i-width*upperplots-1; end
+if (md.mesh.dimension==2)%3 components -> 3 indexes
+	index1=4*width*upperplots+2*leftplots+1;
+	index2=index1+1;
+	index3=index1+width*2;
+	index4=index3+1;
+	newwidth=2*width;
+elseif md.mesh.dimension==3%6 components -> 6 indexes
+	index1=3*3*width*upperplots+3*leftplots+1;
+	index2=index1+1;
+	index3=index1+2;
+	index4=index1+width*3;
+	index5=index4+1;
+	index6=index4+2;
+	newwidth=3*width;
+end
+
+%plot principal axis
+type1=[type 'axis1'];
+plot_tensor_principalaxis(md,options,newwidth,index1,tensor,type1,plot_options);
+type2=[type 'axis2'];
+plot_tensor_principalaxis(md,options,newwidth,index2,tensor,type2,plot_options);
+if  md.mesh.dimension==3
+	type3=[type 'axis3'];
+	plot_tensor_principalaxis(md,options,newwidth,index3,tensor,type3,plot_options);
+end
+
+%now plot principal values
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[tensor.principalvalue1 datatype]=processdata(md,tensor.principalvalue1,options);
+[tensor.principalvalue2 datatype]=processdata(md,tensor.principalvalue2,options);
+if  md.mesh.dimension==3
+	[tensor.principalvalue3 datatype]=processdata(md,tensor.principalvalue3,options);
+end
+
+if ((md.mesh.dimension==2)),
+	subplot(2*width,2*width,index3)
+	plot_unit(x,y,z,elements,tensor.principalvalue1,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 1')
+	subplot(2*width,2*width,index4)
+	plot_unit(x,y,z,elements,tensor.principalvalue2,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 2')
+else
+	subplot(3*width,3*width,index4)
+	plot_unit(x,y,z,elements,tensor.principalvalue1,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 1')
+	subplot(3*width,3*width,index5)
+	plot_unit(x,y,z,elements,tensor.principalvalue2,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 2')
+	subplot(3*width,3*width,index6)
+	plot_unit(x,y,z,elements,tensor.principalvalue3,is2d,isplanet,datatype,options)
+	Apply_options_tensor(md,options,type,'principal value 3')
+end
+end
+
+function Apply_options_tensor(md,options,type,component)
+%apply options
+if ismember('_',type) %user plotet stress_tensor
+	strings=strsplit(type,'_');
+	string=strings{1};
+else %default plot: user requested stress
+	string=type;
+end
+options=addfielddefault(options,'title',[upper(string(1)) string(2:end) ' ' component]);
+options=changefieldvalue(options,'colorbar',2);
+applyoptions(md,[],options);
+end
Index: /issm/trunk/src/m/plot/plot_tensor_principalaxis.m
===================================================================
--- /issm/trunk/src/m/plot/plot_tensor_principalaxis.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_tensor_principalaxis.m	(revision 13395)
@@ -0,0 +1,95 @@
+function plot_tensor_principalaxis(md,options,width,i,tensor,type,plot_options);
+%PLOT_TENSOR_PRINCIPALAXIS - plot ytensor principal axis
+%
+%   Usage:
+%      plot_tensor_principalaxis(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%prepare subplot
+subplot(width,width,i); 
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+if ((md.mesh.dimension==2)),
+	eval(['Vx=tensor.principalaxis' type(end) '(:,1); Vy=tensor.principalaxis' type(end) '(:,2);'])
+	eval(['value=tensor.principalvalue' type(end) ';']);
+	[Vx datatype]=processdata(md,Vx,options);
+	[Vy datatype]=processdata(md,Vy,options);
+	[value datatype]=processdata(md,value,options);
+else
+	eval(['Vx=tensor.principalaxis' type(end) '(:,1); Vy=tensor.principalaxis' type(end) '(:,2); Vz=tensor.principalaxis' type(end) '(:,3);'])
+	[Vx datatype]=processdata(md,Vx,options);
+	[Vy datatype]=processdata(md,Vy,options);
+	[Vz datatype]=processdata(md,Vz,options);
+	[value datatype]=processdata(md,value,options);
+end
+
+%take the center of each element if ~isonnode
+if datatype==1,
+	x=mean(md.mesh.x(md.mesh.elements'))'; y=mean(md.mesh.y(md.mesh.elements'))'; z=mean(md.mesh.z(md.mesh.elements'))';
+end
+
+%plot quivers
+if (md.mesh.dimension==2),
+
+	%density
+	if exist(options,'density')
+		density=getfieldvalue(options,'density');
+		x=x(1:density:end);
+		y=y(1:density:end);
+		Vx=Vx(1:density:end);
+		Vy=Vy(1:density:end);
+		value=value(1:density:end);
+	end
+
+	%scaling:
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	scale=0.5/max(sqrt((Vx.^2+Vy.^2)/delta));
+	Vx=scale*Vx; Vy=scale*Vy;
+
+	pos=find(value>=0);
+	q1=quiver(x(pos),y(pos),Vx(pos),Vy(pos),'Color','r','ShowArrowHead','off','AutoScale','off');
+	hold on
+	pos=find(value<0);
+	q2=quiver(x(pos),y(pos),Vx(pos),Vy(pos),'Color','b','ShowArrowHead','off','AutoScale','off');
+
+else
+	%density
+	if exist(options,'density')
+		density=getfieldvalue(options,'density');
+		x=x(1:density:end);
+		y=y(1:density:end);
+		z=z(1:density:end);
+		Vx=Vx(1:density:end);
+		Vy=Vy(1:density:end);
+		Vz=Vz(1:density:end);
+		value=value(1:density:end);
+	end
+
+	%scaling:
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	scale=0.5/max(sqrt((Vx.^2+Vy.^2)/delta));
+	Vx=scale*Vx; Vy=scale*Vy; Vz=scale*Vz;
+
+	pos=find(value>=0);
+	q1=quiver3(x(pos),y(pos),z(pos),Vx(pos),Vy(pos),Vz(pos),'Color','r','ShowArrowHead','off','AutoScale','off');
+	hold on
+	pos=find(value<0);
+	q2=quiver3(x(pos),y(pos),z(pos),Vx(pos),Vy(pos),Vz(pos),'Color','b','ShowArrowHead','off','AutoScale','off');
+end
+
+%legend
+if strcmpi(type(1:6),'strain')
+	legend([q1 q2],'extension','compression')
+elseif strcmpi(type(1:6),'stress')
+	legend([q1 q2],'compression','traction')
+end
+
+%apply options
+strings=strsplit(type,'_');
+string=strings{1};
+options=addfielddefault(options,'title',[upper(string(1)) string(2:end) ' principal axis ' type(end)]);
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_thermaltransient_results.m
===================================================================
--- /issm/trunk/src/m/plot/plot_thermaltransient_results.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_thermaltransient_results.m	(revision 13395)
@@ -0,0 +1,24 @@
+function plot_thermaltransient_results(md,options,width,i)
+%PLOT_THERMALTRANSIENT_RESULTS - plot  results of a thermal transient solution
+%
+%   Usage:
+%      plot_thermaltransient_results(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+string='plot(md';
+for i=1:length(md.thermaltransient_results),
+	string=[string ',''data'',''thermaltransient_results(' num2str(i) ').temperature'',''view'',3,''title'',''Temperature at time ' num2str(md.thermaltransient_results(i).time) ' a'''];
+end
+string=[string ',''figure'',1,''colorbar#all'',''on'',''view'',3,''fontsize'',' num2str(options.fontsize) ',''fontweight'',' options.fontweight ');'];
+eval(string);
+clear string;
+
+string='plot(md';
+for i=2:length(md.thermaltransient_results),
+	string=[string ',''data'',md.thermaltransient_results(' num2str(i) ').temperature-md.thermaltransient_results(' num2str(i-1) ').temperature,''view'',3,''title'',''Delta temperature at time ' num2str(md.thermaltransient_results(i).time) ' a'''];
+end
+string=[string ',''figure'',2,''colorbar#all'',''on'',''fontsize'',' num2str(options.fontsize) ',''fontweight'',' options.fontweight ');'];
+eval(string);
+clear string;
+
Index: /issm/trunk/src/m/plot/plot_transient_field.m
===================================================================
--- /issm/trunk/src/m/plot/plot_transient_field.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_transient_field.m	(revision 13395)
@@ -0,0 +1,43 @@
+function plot_transient_field(md,options,width,i,data)
+%PLOT_TRANSIENT_FIELD - plot transient results
+%
+%   Usage:
+%      plot_transient_field(md,options,width,i,data);
+%
+%   See also: PLOTMODEL
+
+%Check that they are transient results
+if (~isfield(md.results,'TransientSolution')),
+	error('plot_transient_field error message: no transient results in the model');
+end
+
+%Figure out the iterations to plot and check if it is possible
+transient=md.results.TransientSolution;
+maxiteration=size(transient,2);
+steps=getfieldvalue(options,'steps',1:1:maxiteration);
+
+if max(steps)>maxiteration | min(steps)<1,
+	error(['plot_transient_field error message: problem with the steps requested, must be an interger between 0 and ' num2str(maxiteration)]);
+end
+subplotwidth=ceil(sqrt(length(steps)));
+
+%Figure out the field to plot
+
+field=getfieldvalue(options,'field','Vel');
+
+%process mes only once
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+
+%plot data for all steps
+for i=1:length(steps),
+
+	%process data and change title if needed
+	[data datatype]=processdata(md,transient(steps(i)).(field),options);
+	options=changefieldvalue(options,'title',[field ' at time ' num2str(transient(steps(i)).time/md.constants.yts) ' a']);
+
+	%create plot of step i
+	subplot(subplotwidth,subplotwidth,i);
+	plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
+	applyoptions(md,data,options);
+
+end
Index: /issm/trunk/src/m/plot/plot_transient_movie.m
===================================================================
--- /issm/trunk/src/m/plot/plot_transient_movie.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_transient_movie.m	(revision 13395)
@@ -0,0 +1,70 @@
+function plot_transient_movie(md,options,width,i);
+%PLOT_TRANSIENT_MOVIE - plot a transient result as a movie
+%   Usage:
+%      plot_transient_movie(md,options,width,i);
+%
+%   See also: PLOTMODEL, PLOT_UNIT, PLOT_MANAGER
+
+	%prepare subplot
+	subplot(width,width,i); 
+
+	%xlim
+	if exist(options,'transient_movie_field'),
+		field=getfieldvalue(options,'transient_movie_field');
+	else
+		error('specify transient_movie_field in options list');
+	end
+
+	results=md.results.TransientSolution;
+	%loop over the time steps
+	if exist(options,'transient_movie_limit'),
+		limit=getfieldvalue(options,'transient_movie_limit');
+		steps=[limit(1):limit(end)];
+	else
+		steps=1:length(results);
+	end
+	results=md.results.TransientSolution;
+	nstep=1;
+	for i=steps
+
+		if ~isempty(results(i).(field)),
+			%process data
+			[x y z elements is2d isplanet]=processmesh(md,results(i).(field),options);
+			[data datatype]=processdata(md,results(i).(field),options);
+
+			titlestring=[field ' at time ' num2str(results(i).time/md.constants.yts) ' year'];
+			plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
+			apply_options_movie(md,options,titlestring);
+
+			if exist(options,'transient_movie_output'),
+				set(gcf,'Renderer','zbuffer','color','white'); %fixes a bug on Mac OS X (not needed in future Matlab version)
+				if nstep==1,
+					%initialize images and frame
+					frame=getframe(gcf);
+					[images,map]=rgb2ind(frame.cdata,256,'nodither');
+					images(1,1,1,length(steps))=0;
+				else
+					frame=getframe(gcf);
+					images(:,:,1,nstep) = rgb2ind(frame.cdata,map,'nodither');
+				end
+			else
+				pause(0.1)
+			end
+			nstep=nstep+1;
+		end
+	end
+
+	%output movie if requested.
+	if exist(options,'transient_movie_output'),
+		filename=getfieldvalue(options,'transient_movie_output');
+		imwrite(images,map,filename,'DelayTime',getfieldvalue(options,'transient_movie_time',2),'LoopCount',inf)
+	end
+
+end %function
+
+function apply_options_movie(md,options,titlestring)
+	%apply options
+	options=addfielddefault(options,'title',titlestring);
+	options=addfielddefault(options,'colorbar',1);
+	applyoptions(md,[],options);
+end
Index: /issm/trunk/src/m/plot/plot_transient_results.m
===================================================================
--- /issm/trunk/src/m/plot/plot_transient_results.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_transient_results.m	(revision 13395)
@@ -0,0 +1,77 @@
+function plot_transient_results(md,options,width,i)
+%PLOT_TRANSIENT_RESULTS - plot transient results
+%
+%   Usage:
+%      plot_transient_results(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+fontsize=getfieldvalue(options,'fontsize',14);
+fontweight=getfieldvalue(options,'fontweight','n');
+
+%Prepare window distribution
+%Get screen geometry
+mp = get(0, 'MonitorPositions');
+%Build window sizes
+if size(mp,1)>=2        %several monitors, use the second one
+	bdwidth=mp(2,1)+5; topbdwidth=mp(2,2)+20; W=mp(2,3)/3; H=mp(2,4)/2;
+else                    %only one monitor
+	bdwidth=5;         topbdwidth=20;         W=mp(1,3)/3; H=mp(1,4)/2;
+end
+pos1=[bdwidth  H+bdwidth  W-2*bdwidth  H-bdwidth-topbdwidth];
+pos2=pos1+[W 0 0 0]; pos3=pos1+[2*W 0 0 0]; pos4=pos1+[0 -H 0 0]; pos5=pos1+[W -H 0 0]; pos6=pos1+[2*W -H 0 0];
+%Create windows
+figure(1);close;
+figure('Position',pos1); figure('Position',pos2);figure('Position',pos3);figure('Position',pos4);figure('Position',pos5);figure('Position',pos6);
+
+string='plotmodel(md';
+for i=1:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').thickness,''title'',''Thickness at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',1,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight ''');'];
+eval(string);
+clear string;
+
+string='plotmodel(md';
+for i=1:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').vel,''view'',3,''title'',''Velocity at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',2,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+eval(string);
+clear string;
+
+if md.mesh.dimension==3,
+	string='plotmodel(md';
+	for i=1:length(md.results.transient),
+		string=[string ',''data'',md.results.transient(' num2str(i) ').temperature,''view'',3,''title'',''Temperature at time ' num2str(md.results.transient(i).time) ' a'''];
+	end
+	string=[string ',''figure'',3,''colorbar#all'',''on'',''view'',3,''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+	eval(string);
+	clear string;
+end
+
+string='plotmodel(md';
+for i=2:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').thickness-md.results.transient(' num2str(i-1) ').thickness,''title'',''Delta thickness at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',4,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+eval(string);
+clear string;
+
+string='plotmodel(md';
+for i=2:length(md.results.transient),
+	string=[string ',''data'',md.results.transient(' num2str(i) ').vel-md.results.transient(' num2str(i-1) ').vel,''view'',3,''title'',''Delta velocity at time ' num2str(md.results.transient(i).time) ' a'''];
+end
+string=[string ',''figure'',5,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+eval(string);
+clear string;
+
+if md.mesh.dimension==3,
+	string='plotmodel(md';
+	for i=2:length(md.results.transient),
+		string=[string ',''data'',md.results.transient(' num2str(i) ').temperature-md.results.transient(' num2str(i-1) ').temperature,''view'',3,''title'',''Delta temperature at time ' num2str(md.results.transient(i).time) ' a'''];
+	end
+	string=[string ',''figure'',6,''colorbar#all'',''on'',''fontsize'',' num2str(fontsize) ',''fontweight'',''' fontweight  ''');'];
+	eval(string);
+	clear string;
+end
Index: /issm/trunk/src/m/plot/plot_unit.m
===================================================================
--- /issm/trunk/src/m/plot/plot_unit.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_unit.m	(revision 13395)
@@ -0,0 +1,92 @@
+function plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
+%PLOT_UNIT - unit plot, display data
+%
+%   Usage:
+%      plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options);
+%
+%   See also: PLOTMODEL, PLOT_MANAGER
+
+%edgecolor
+edgecolor=getfieldvalue(options,'edgecolor','none');
+
+switch datatype,
+
+	%element plot
+	case 1,
+
+		pos=find(~isnan(data)); %needed for element on water
+		if is2d,
+			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+		else
+			A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
+			patch( 'Faces', [A B C],  'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', data(pos),'FaceColor','flat','EdgeColor',edgecolor);
+		end
+
+	%node plot
+	case 2,
+
+		if is2d,
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+		else
+			if ~isplanet,
+				A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+				patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+				patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+				patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+				patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+				patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			else
+				A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+				if size(elements,2)==4, D=elements(:,4); else D=C; end
+				patch( 'Faces', [A B C D],  'Vertices', [x y z],'FaceVertexCData', data(:),'FaceColor','interp','EdgeColor',edgecolor);
+			end
+		end
+
+	%quiver plot
+	case 3,
+
+		if is2d,
+			plot_quiver(x,y,data(:,1),data(:,2),options);
+		else
+			plot_quiver3(x,y,z,data(:,1),data(:,2),data(:,3),options);
+		end
+
+	%Patch plot P1
+	case 4,
+
+		if is2d,
+			patch( 'Faces',elements,'Vertices',[x y],'CData',data,'FaceColor','interp','EdgeColor',edgecolor);
+		else
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [D E F], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [A B E D], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [B E F C ], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+			patch( 'Faces', [C A D F ], 'Vertices', [x y z],'CData', data,'FaceColor','interp','EdgeColor',edgecolor);
+		end
+
+	%Patch plot P0
+	case 5,
+
+		if is2d,
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+			patch( 'Faces', [A B C], 'Vertices', [x y z],'CData', data(:),'FaceColor','flat','EdgeColor',edgecolor);
+		else
+			A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+			patch( 'Faces', [A B C],  'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [D E F],  'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [A B E D],'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+			patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', data,'FaceColor','flat','EdgeColor',edgecolor);
+		end
+
+	otherwise,
+		error(['case ' num2str(datatype) ' not supported']);
+
+	end
+end
Index: /issm/trunk/src/m/plot/plot_vertexnumbering.m
===================================================================
--- /issm/trunk/src/m/plot/plot_vertexnumbering.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plot_vertexnumbering.m	(revision 13395)
@@ -0,0 +1,51 @@
+function plot_vertexnumbering(md,options,width,i);
+%PLOT_VERTEXNUMBERING - plot vertex numbering
+%
+%   Usage:
+%      plot_vertexnumbering(md,options,width,i);
+%
+%   See also: PLOTMODEL
+
+%process data and model
+[x y z elements is2d isplanet]=processmesh(md,[],options);
+[vertexnumbers datatype]=processdata(md,[1:md.mesh.numberofvertices]',options);
+
+%plot
+subplot(width,width,i); 
+
+if is2d
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3);
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%numbering
+	text(x,y,z,num2str(transpose(1:size(x,1))),...
+		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+else
+	%plot mesh 
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
+	patch( 'Faces', [A B C],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+
+	%numbering
+	text(x,y,z,num2str(transpose(1:size(x,1))),...
+		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
+
+	%Highlight
+	pos=getfieldvalue(options,'highlight',[]);
+	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
+end
+
+%apply options
+options=addfielddefault(options,'title','Node numbering');
+options=addfielddefault(options,'colorbar',0);
+applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plotdoc.m
===================================================================
--- /issm/trunk/src/m/plot/plotdoc.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plotdoc.m	(revision 13395)
@@ -0,0 +1,174 @@
+function plotdoc()
+%PLOTDOC - plot documentation
+%
+%   Usage:
+%      plotdoc()
+
+disp(' ');
+disp('   Plot usage: plotm(model,varargin)');
+disp('   Options: ');
+disp('       ''figure'': figure number');
+disp('       ''data'' : what we want to plot');
+disp('                Available values for ''data'' are: ');
+disp('                  - any field of the model structure. ex: plot(md,''data'',''vel''), or plot(md,''data'',md.initialization.vel)');
+disp('                  - ''basal_drag'': plot the basal drag on the bed (in kPa)');
+disp('                  - ''basal_dragx'' or ''basal_dragy'' : plot a component of the basal drag on the bed (in kPa)');
+disp('                  - ''boundaries'': this will draw all the segment boundaries to the model, including rifts.');
+disp('                  - ''icefront'': this will show segments that are used to define the icefront of the model (Neumann boundary conditions).');
+disp('                  - ''BC'': this will draw all the boundary conditions (Dirichlet and Neumann).');
+disp('                  - ''deviatoricstress_tensor'': plot the components of the deviatoric stress tensor (tauxx,tauyy,tauzz,tauxy,tauxz,tauyz) if computed');
+disp('                  - ''deviatoricstress_principal'': plot the deviatoricstress tensor principal axis and principal values');
+disp('                  - ''deviatoricstress_principalaxis1'': arrow plot the first principal axis of the deviatoricstress tensor(replace 1 by 2 or 3 if needed)');
+disp('                  - ''driving_stress'': plot the driving stress (in kPa)');
+disp('                  - ''elements_type'': model used for each element');
+disp('                  - ''elementnumbering'': numbering of elements');
+disp('                  - ''vertexnumbering'': numbering of vertices');
+disp('                  - ''highlightelements'': to highlight elements to highlight the element list');
+disp('                  - ''highlightvertices'': to highlight vertices (use highlight option to enter the vertex list');
+disp('                  - ''mesh'': draw mesh using trisurf');
+disp('                  - ''referential'': diagnostic referential');
+disp('                  - ''riftvel'': velocities along rifts');
+disp('                  - ''riftrelvel'': relative velocities along rifts');
+disp('                  - ''riftpenetration'': penetration levels for a fault');
+disp('                  - ''riftfraction'': fill fractions for every node of the rifts');
+disp('                  - ''rifts'': plot mesh with an offset so that rifts are visible');
+disp('                  - ''strainrate_tensor'': plot the components of the strainrate tensor (exx,eyy,ezz,exy,exz,eyz) if computed');
+disp('                  - ''strainrate_principal'': plot the strainrate tensor principal axis and principal values)');
+disp('                  - ''strainrate_principalaxis1'': arrow plot the first principal axis of the strainrate tensor(replace 1 by 2 or 3 if needed)');
+disp('                  - ''stress_tensor'': plot the components of stress tensor (sxx,syy,szz,sxy,sxz,syz) if computed');
+disp('                  - ''stress_principal'': plot the stress tensor principal axis and principal values');
+disp('                  - ''stress_principalaxis1'': arrow plot the first principal axis of the stress tensor(replace 1 by 2 or 3 if needed)');
+disp('                  - ''transient_results'': this will display all the time steps of a transient run (use steps to specify the steps requested)');
+disp('                  - ''transient_vel'': this will display the velocity for the time steps requested in ''steps'' of a transient run');
+disp('                  - ''transient_vel'': vel can be by any field of the transient results (vx, vy, vz, vel, temperature, melting, pressure, bed, thickness, surface)');
+disp('                  - ''transient_field'': dynamic plot of results. specify ''steps'' option, as fell as ''field'' (defaults are all steps, for ''Vel'' field)');
+disp('                  - ''transient_movie'': this will display the time steps of a given field of a transient run');
+disp('                  - ''transient_movie_field'': field to be displayed when doing  transient_movie data display');
+disp('                  - ''transient_movie_output'': filename if output is desired for movie');
+disp('                  - ''transient_movie_time'': time for each image (default 2 seconds)');
+disp('                  - ''thermaltransient_results'': this will display all the time steps of a thermal transient run');
+disp('                  - ''qmuhistnorm'': histogram normal distribution. needs option qmudata');
+disp('                  - ''qmumean'': plot of mean distribution in sampling analysis with scaled response. needs option qmudata for descriptor');
+disp('                  - ''qmustddev'': plot of stddev distribution in sampling analysis with scaled response. needs option qmudata for descriptor');
+disp('                  - ''part_hist'': partitioning node and area histogram');
+disp('                  - ''quiver'': quiver plot');
+
+disp('       ''alloptions'': apply the options to all subplots if ''on''');
+disp('       ''axis'': same as standard matlab option (''equal'',''off'',''equal on'',...)');
+disp('       ''basin'': zoom on a given basin (''pineislandglacier'',''ronneiceshelf'', use isbasin to identify a basin');
+disp('                 ''hemisphere'': specify +1 or -1');
+disp('                 ''basindeltax'': in m');
+disp('                 ''showbasins'': write lables for every existing basin name around the center of the plot');
+disp('       ''caxis'': modify  colorbar range. (array of type [a b] where b>=a)');
+disp('       ''backgroundcolor'': plot background color. (default is ''w'')');
+disp('       ''figurebackgroundcolor'': figure background color. (default is ''none'')');
+disp('       ''coord'':  ''xy'' (default) or ''latlon''');
+disp('       ''colorlevels'':  N or {value1,valu2,value3,...} used if quiver, use different colors for the given number of colors or limits');
+disp('       ''colorbar'': add colorbar (string ''on'' or ''off'')');
+disp('       ''colorbartitle'': colorbar title (string)');
+disp('       ''colorbarYlabel'': colorbar Y label (string)');
+disp('       ''colorbarpos'': [x,y,dx,dy] where x,y,dx and dy are within [0 1]');
+disp('       ''colorbarcornerposition'': ''West'',''North'',etc ...');
+disp('       ''colorbartitlerotation'': -90, etc ...');
+disp('       ''colorbarfontsize'': specify colorbar fontsize');
+disp('       ''colorbarwidth'': multiplier (default 1) to the default width colorbar');
+disp('       ''colorbarheight'': multiplier (default 1) to the default height colorbar');
+disp('       ''colormap'': same as standard matlab option (''jet'',''hsv'',''cool'',''spring'',''gray'',''Ala'',''Rignot'',...)');
+disp('       ''contourlevels'': N or {value1,valu2,value3,...} add the contours of the specified values or N contours');
+disp('       ''contourticks'': ''on'' or ''off'' to display the ticks of the contours');
+disp('       ''contouronly'': ''on'' or ''off'' to display the contours on a white background');
+disp('       ''contourcolor'': ticks and contour color');
+disp('       ''density'': density of quivers (one arrow every N nodes, N integer)');
+disp('       ''inset'': add an inset (zoom) of the current figure if 1 (use ''insetx'', ''insety'' and ''insetpos'' to determine the inset position and content)');
+disp('       ''insetx'': [min(x) max(x)] where min(x) and max(x) are values determining the inset content');
+disp('       ''insety'': [min(y) max(y)] where min(y) and max(y) are values determining the inset content');
+disp('       ''insetpos'': [x,y,dx,dy] where x,y,dx and dy are within [0 1]');
+disp('       ''streamlines'': N (number of stream lines) or {[x1 y1],...} (coordinates of seed points) add streanlines on current figure');
+disp('       ''edgecolor'': same as standard matlab option EdgeColor (color name: ''black'' or RGB array: [0.5 0.2 0.8])');
+disp('       ''fontsize'': same as standard matlab option (10,14,...)');
+disp('       ''fontweight'': same as standard matlab option (normal: ''n'',bold: ''b'',light: ''l'',demi: ''d'')');
+disp('       ''fontcolor'': same as standard matlab option');
+disp('       ''highlight'': highlights certain nodes or elements when using ''nodenumbering'' or ''elementnumbering'' or ''highlightnodes '' or ''highlightelements'' option');
+disp('       ''resolution'': resolution used by section value (array of type [horizontal_resolution vertical_resolution])');
+disp('                       horizontal_resolution must be in meter, and vertical_resolution a number of layers');
+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');
+disp('       ''view'': same as standard matlab option (ex: 2, 3 or [90 180]');
+disp('       ''xlim'': same as standard matlab option (ex: [0 500])');
+disp('       ''ylim'': same as standard matlab option');
+disp('       ''zlim'': same as standard matlab option');
+disp('       ''xlabel'': same as standard matlab option (ex:''km'')');
+disp('       ''ylabel'': same as standard matlab option');
+disp('       ''xticklabel'': specifiy xticklabel');
+disp('       ''yticklabel'': specifiy yticklabel');
+disp('       ''overlay'': yes or no. This will overlay a radar amplitude image behind');
+disp('       ''overlay_image'': path to overlay image. provide overlay_xlim, overlay_ylim, overlay_xposting and overlay_yposting options also');
+disp('       ''contrast'': (default 1) coefficient to add contrast to the radar amplitude image used in overlays');
+disp('       ''highres'': resolution of overlayed radar amplitude image (default is 0, high resolution is 1).');
+disp('       ''hem'': specify hemisphere ''n'' or ''s'' (default is ''s'').');
+disp('       ''alpha'': transparency coefficient (the higher, the more transparent). Default is 1.5');
+disp('       ''scaling'': scaling factor used by quiver plots. Default is 0.4');
+disp('       ''autoscale'': set to ''off'' to have all the quivers with the same size. Default is ''on''');
+disp('       ''expdisp'': plot exp file on top of a data plot. provide exp file as an argument (use a cell of strings if more than one)');
+disp('       ''expstyle'': marker style for expdisp plot (use a cell of strings if more than one)');
+disp('       ''linewidth'': line width for expdisp plot');
+disp('       ''border'': size of display border (in pixels). active only for overlay plots');
+disp('       ''text'': print string, use a cell of strings if more than one');
+disp('       ''textposition'': [x y] position of text, use a cell of strings if more than one');
+disp('       ''textsize'':  same as standard ''FontSize'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''textweight'':  same as standard ''FontWeight'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''textcolor'':  same as standard ''color'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''textrotation'':  same as standard ''Rotation'' matlab option applied to text, use a cell of strings if more than one');
+disp('       ''mask'': list of flags of size numberofnodes or numberofelements. Only ''true'' values are plotted ');
+disp('       ''nan'': value assigned to NaNs (convenient when plotting BC)');
+disp('       ''partitionedges'': ''off'' by default. overlay plot of partition edges');
+disp('       ''log'': value of log');
+disp('       ''latlon'': ''on'' or {latstep lonstep [resolution [color]]} where latstep,longstep and resolution are in degrees, color is a [r g b] array');
+disp('       ''latlonnumbering'': ''on'' or {latgap longap colornumber latangle lonangle} where latgap and longap are pixel gaps for the numbers,'); 
+disp('       ''latlonclick'': ''on'' to click on latlon ticks positions');
+disp('                   colornumber is a [r g b] array and latangle and lonangle are angles to flip the numbers');
+disp('       ''northarrow'': add an arrow pointing north, ''on'' for default value or [x0 y0 length [ratio width fontsize]] where (x0,y0) are the coordinates of the base, ratio=headlength/length');
+disp('       ''offset'': mesh offset used by ''rifts'', default is 500');
+disp('       ''scaleruler'': add a scale ruler, ''on'' for default value or [x0 y0 length width numberofticks] where (x0,y0) are the coordinates of the lower left corner');
+disp('       ''showregion'': show domain in Antarctica on an inset, use ''insetpos'' properties');
+disp('       ''visible'': ''off'' to make figure unvisible, default is ''on''');
+disp('       ''wrapping'': repeat ''n'' times the colormap (''n'' must be an integer)');
+disp('       ''unit'': by default, in m, otherwise, ''km'' is available');
+disp('       ''legend_position'': by default, ''NorthEasth''');
+disp('       ''qmudata'': data for qmu  plots.');
+disp('                  {dresp1   ,dresp2  ,hmin,hmax,hnint} or {samp,desc,mu,sigma,hmin,hmax,hnint}');
+disp('                  where dresp1 is a structure array of responses (where we need samp and desc), ');
+disp('                  dresp2 is a structure array of responses (where we only need mu and sigma)');
+disp('                  hmin,hmax and hnint are the minimum, maximum and number of intervals of the histogram (optional)');
+disp('       ''figposition'': position of figure: ''fullscreen'', ''halfright'', ''halfleft'', ''portrait'', ''landscape'',... (hardcoded in applyoptions.m)');
+disp('       ''offsetaxispos'': offset of current axis position to get more space (ex: [-0.02 0  0.04 0])');
+disp('       ''axispos'': axis position to get more space');
+disp('       ''hmin'': (numeric, minimum for histogram)');
+disp('       ''hmax'': (numeric, maximum for histogram)');
+disp('       ''hnint'': (numeric, number of intervals for histogram)');
+disp('       ''ymin1'': (numeric, minimum of histogram y-axis)');
+disp('       ''ymax1'': (numeric, maximum of histogram y-axis)');
+disp('       ''ymin2'': (numeric, minimum of cdf y-axis)');
+disp('       ''ymax2'': (numeric, maximum of cdf y-axis)');
+disp('       ''cdfplt'': (char, ''off'' to turn off cdf line plots)');
+disp('       ''cdfleg'': (char, ''off'' to turn off cdf legends)');
+disp('       ''segmentnumbering'': (''off'' by default)');
+disp('       ''kmlgroundoverlay'': (''off'' by default)');
+disp('       ''kmlfilename'': (''tempfile.kml'' by default)');
+disp('       ''kmlroot'': (''./'' by default)');
+disp('       ''kmlimagename'': (''tempimage'' by default)');
+disp('       ''kmlimagetype'': (''png'' by default)');
+disp('       ''kmlresolution'': (1 by default)');
+disp('       ''kmlfolder'': (''Ground Overlay'' by default)');
+disp('       ''kmlfolderdescription'': ('''' by default)');
+disp('       ''kmlgroundoverlayname'': ('''' by default)');
+disp('       ''kmlgroundoverlaydescription'': ('''' by default)');
+
+disp('       any options (except ''data'') can be followed by ''#i'' where ''i'' is the subplot number, or ''#all'' if applied to all plots');
+disp('  ');
+disp('   Examples:');
+disp('       plotmodel(md,''data'',''vel'',''data'',''mesh'',''view#2'',3,''colorbar#all'',''on'',''axis#1'',''off equal'')');
+disp('       plotmodel(md,''data'',''highlightelements'',''highlight'',[1 4 10],''expdisp'',{''domain1.exp'' ''domain2.exp'' ''domain3.exp''})');
Index: /issm/trunk/src/m/plot/plotmodel.m
===================================================================
--- /issm/trunk/src/m/plot/plotmodel.m	(revision 13395)
+++ /issm/trunk/src/m/plot/plotmodel.m	(revision 13395)
@@ -0,0 +1,57 @@
+function plotmodel(md,varargin)
+%At command prompt, type plotdoc for help on documentation.
+
+%First process options
+options=plotoptions(varargin{:});
+
+%get number of subplots
+subplotwidth=ceil(sqrt(options.numberofplots));
+
+%if nlines and ncols specified, then bypass.
+if exist(options.list{1},'nlines'),
+	nlines=getfieldvalue(options.list{1},'nlines');
+else 
+	nlines=subplotwidth;
+end
+
+if exist(options.list{1},'ncols'),
+	ncols=getfieldvalue(options.list{1},'ncols');
+else 
+	ncols=subplotwidth;
+end
+
+%check that nlines and ncols were given at the same time!
+if ((exist(options.list{1},'ncols') & ~exist(options.list{1},'ncols')) | (~exist(options.list{1},'ncols') & exist(options.list{1},'ncols')))
+	error('plotmodel error message: nlines and ncols  need to be specified together, or not at all');
+end
+
+%Get figure number and number of plots
+figurenumber=options.figurenumber;
+numberofplots=options.numberofplots;
+
+%go through subplots
+if numberofplots,
+		
+	%Create figure 
+	if strcmpi(getfieldvalue(options.list{1},'visible','on'),'off'),
+		F=figure(figurenumber);clf;
+		set(F,'Visible','Off');
+	else
+		figure(figurenumber);clf;
+	end
+
+	%Use zbuffer renderer (snoother colors)
+	set(gcf,'Renderer','zbuffer');
+
+	%Go through all data plottable and close window if an error occurs
+	try,
+		for i=1:numberofplots,
+			plot_manager(getfieldvalue(options.list{i},'model',md),options.list{i},subplotwidth,nlines,ncols,i);
+		end
+	catch me,
+		%figure(figurenumber),close;
+		rethrow(me);
+	end
+else
+	error('plotmodel error message: no output data found. ');
+end
Index: /issm/trunk/src/m/plot/processdata.m
===================================================================
--- /issm/trunk/src/m/plot/processdata.m	(revision 13395)
+++ /issm/trunk/src/m/plot/processdata.m	(revision 13395)
@@ -0,0 +1,202 @@
+function [data datatype]=processdata(md,data,options);
+%PROCESSDATA - process data to be plotted
+%
+%   datatype = 1 -> elements
+%   datatype = 2 -> nodes
+%   datatype = 3 -> node quivers
+%   datatype = 4 -> patch
+%
+%   Usage:
+%      [data datatype]=processdata(md,data,options);
+%
+%   See also: PLOTMODEL, PROCESSMESH
+
+%check format
+if (iscell(data) | isempty(data) | length(data)==0 | (length(data)==1 & ~isstruct(data) & isnan(data))),
+	error('plotmodel error message: data provided is empty');
+end
+
+%needed later on
+if isprop(md.mesh,'numberofvertices2d'), 
+	numberofvertices2d=md.mesh.numberofvertices2d; 
+	numberofelements2d=md.mesh.numberofelements2d; 
+else 
+	numberofvertices2d=NaN;
+	numberofelements2d=NaN;
+end
+
+%Process Patch
+if isstruct(data) 
+	if (isprop(data,'index') & isprop(data,'value')),
+		if data.interpolation(1)==P1Enum(),
+			data=data.value;
+			data=data';
+			data=data(:);
+			datatype=4;
+		elseif data.interpolation(1)==P0Enum(),
+			data=data.value;
+			datatype=5;
+		else
+			error(['interpolation ' data.interpolation(1) ' not supported yet']);
+		end
+	else
+		error('structure other than Patch not supported yet');
+	end
+else
+	%initialize datatype
+	datatype=0;
+end
+
+%get datatype
+datasize=size(data);
+
+%Process NaN if any (do not now before mask is applied)
+if exist(options,'nan')
+	data(find(isnan(data)))=getfieldvalue(options,'nan',0);
+end
+%non patch processing
+if datatype~=4 & datatype~=5,
+
+	%transpose data if necessary
+	if (size(data,2) > size(data,1)),
+		data=data';
+	end
+	datasize=size(data);
+
+	%convert to double if necessary
+	if ~isnumeric(data);
+		disp('processdata info message: data is not numeric (logical?). Converted to double');
+		data=double(data);
+	end
+
+	%check length
+	if datasize(1)~=md.mesh.numberofvertices & datasize(1)~=md.mesh.numberofelements & datasize(1)~=md.mesh.numberofvertices*6 & (md.mesh.dimension==3 & ~(datasize(1)==numberofelements2d | datasize(1)==numberofvertices2d))
+		error('plotmodel error message: data not supported yet');
+	end
+	
+	%quiver?
+	if datasize(2)>1,
+		datatype=3;
+
+		%check number of columns, add zeros if necessary,
+		if (md.mesh.dimension==3)
+			if datasize(2)==2,
+				data=[data, zeros(datasize(1),1)];
+			elseif datasize(2)~=3,
+				error('plotmodel error message: data provided should have 2 or 3 columns for quiver plot, and 1 for regular plot');
+			end
+		%elseif ((md.mesh.dimension==2) & datasize(2)~=2),
+		%	error('plotmodel error message: data provided should have 2 columns for quiver plot, and 1 for regular plot');
+		end
+	end
+
+	%treat the case datasize(1)=6*nodes
+	if datasize(1)==6*md.mesh.numberofvertices
+		%keep the only norm of data
+		data1=data(1:6:md.mesh.numberofvertices*6,:);
+		data2=data(2:6:md.mesh.numberofvertices*6,:);
+		data=sqrt(data1.^2+data2.^2);
+		datasize(1)=md.mesh.numberofvertices;
+		%---> go to node data
+	end
+
+	%treat the case datasize(1)=nodes2d
+	if (md.mesh.dimension==3 & datasize(1)==numberofvertices2d),
+		data=project3d(md,'vector',data,'type','node');
+		datasize(1)=md.mesh.numberofvertices;
+		%---> go to node data
+	end
+
+	%treat the case datasize(1)=nodes2d
+	if (md.mesh.dimension==3 & datasize(1)==numberofelements2d),
+		data=project3d(md,'vector',data,'type','element');
+		datasize(1)=md.mesh.numberofelements;
+		%---> go to node data
+	end
+
+	%smoothing?
+	if exist(options,'smooth')
+		data=averaging(md,data,getfieldvalue(options,'smooth'));
+		datasize(1)=md.mesh.numberofvertices;
+		%---> go to node data
+	end
+end
+
+%element data
+if (datasize(1)==md.mesh.numberofelements & datasize(2)==1),
+
+	%Initialize datatype if non patch
+	if datatype~=4 & datatype~=5,
+		datatype=1;
+	end
+
+	%Mask?
+	if exist(options,'mask'),
+		flags=getfieldvalue(options,'mask');
+		pos=find(~flags);
+		if length(flags)==md.mesh.numberofvertices,
+			[pos2 dummy]=find(ismember(md.mesh.elements,pos));
+			data(pos2,:)=NaN;
+		elseif length(flags)==md.mesh.numberofelements
+			data(pos,:)=NaN;
+		else
+			disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+		end
+	end
+
+	%log?
+	if exist(options,'log'),
+		bounds=getfieldvalue(options,'caxis',[min(data(:)) max(data(:))]);
+		data(find(data<bounds(1)))=bounds(1);
+		if any(data<=0),
+			error('Log option cannot be applied on negative values. Use caxis option (Rignot''s settings: [1.5 max(data)])');
+		end
+		pos=find(~isnan(data));
+		data(pos)=log(data(pos))/log(getfieldvalue(options,'log'));
+	end
+end
+
+%node data
+if (datasize(1)==md.mesh.numberofvertices & datasize(2)==1),
+	datatype=2;
+
+	%Mask?
+	if exist(options,'mask'),
+		flags=getfieldvalue(options,'mask');
+		pos=find(~flags);
+		if length(flags)==md.mesh.numberofvertices,
+			data(pos,:)=NaN;
+		elseif length(flags)==md.mesh.numberofelements
+			data(md.mesh.elements(pos,:),:)=NaN;
+		else
+			disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+		end
+	end
+
+	%log?
+	if exist(options,'log'),
+		%if any(data<=0),
+		%	error('Log option cannot be applied on negative values. Use caxis option (Rignot''s settings: [1.5 max(data)])');
+		%end
+		data=log(data)/log(getfieldvalue(options,'log'));
+	end
+end
+
+%layer projection? 
+if getfieldvalue(options,'layer',0)>=1,
+	data=project2d(md,data,getfieldvalue(options,'layer')); %project onto 2d mesh
+end
+
+%control arrow density if quiverplot
+if datatype==3 & exist(options,'density')
+	databak=data;
+	data=NaN*ones(datasize);
+	density=getfieldvalue(options,'density');
+	data(1:density:end,:)=databak(1:density:end,:);
+	clear databak
+end
+
+%OK, if datatype=0 error out
+if datatype==0,
+	error(['data provided not recognized or not supported']);
+end
Index: /issm/trunk/src/m/plot/processmesh.m
===================================================================
--- /issm/trunk/src/m/plot/processmesh.m	(revision 13395)
+++ /issm/trunk/src/m/plot/processmesh.m	(revision 13395)
@@ -0,0 +1,96 @@
+function [x y z elements is2d isplanet]=processmesh(md,data,options);
+%PROCESSMESH - process mesh to be plotted
+%
+%   Usage:
+%      [x y z elements is2d]=processmesh(md,data,options)
+%
+%   See also: PLOTMODEL, PROCESSDATA
+
+%some checks
+if md.mesh.numberofvertices==0,
+	error('plot error message: mesh is empty')
+end
+if md.mesh.numberofvertices==md.mesh.numberofelements
+	error(['plot error message: the number of elements is the same as the number of nodes...']);
+end
+
+if (isempty(data) | ~isstruct(data)),
+	%first load x,y, etc ... to speed up plot
+
+	if ~strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
+		x=md.mesh.x;
+		if isprop(md.mesh,'x2d'), x2d=md.mesh.x2d; end
+		y=md.mesh.y;
+		if isprop(md.mesh,'y2d'), y2d=md.mesh.y2d; end
+	else
+		x=md.mesh.long;
+		y=md.mesh.lat;
+	end
+
+	z_field=getfieldvalue(options,'z',md.mesh.z);
+	if ischar(z_field),
+		z=md.(z_field);
+	elseif isnumeric(z_field),
+		z=z_field;
+	else
+		z=md.mesh.z;
+	end
+
+
+	if isprop(md.mesh,'elements2d'), elements2d=md.mesh.elements2d; end
+	elements=md.mesh.elements;
+
+	%is it a 2d plot?
+	if (md.mesh.dimension==2);
+		is2d=1;
+	elseif (md.mesh.dimension==3),
+		if getfieldvalue(options,'layer',0)>=1,
+			is2d=1;
+		else
+			is2d=0;
+		end
+	else
+		error(['dim = ' num2str(md.mesh.dimension) ' not supported yet']);
+	end
+
+	%layer projection? 
+	if getfieldvalue(options,'layer',0)>=1,
+		if strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
+			error('processmesh error message: cannot work with 3D meshes for now');
+		end
+		%we modify the mesh temporarily to a 2d mesh from which the 3d mesh was extruded. 
+		x=x2d;
+		y=y2d;
+		z=zeros(size(x2d));
+		elements=elements2d;
+	end
+else
+	%Process Patch
+	if (md.mesh.dimension==2),
+		elements=transpose(reshape(1:3*md.mesh.numberofelements,3,md.mesh.numberofelements));
+		x=transpose(reshape(md.mesh.x(data.index)',1,3*md.mesh.numberofelements));
+		y=transpose(reshape(md.mesh.y(data.index)',1,3*md.mesh.numberofelements));
+		z=zeros(3*md.mesh.numberofelements,1);
+		is2d=1;
+	else
+		elements=transpose(reshape(1:6*md.mesh.numberofelements,6,md.mesh.numberofelements));
+		x=transpose(reshape(md.mesh.x(data.index)',1,6*md.mesh.numberofelements));
+		y=transpose(reshape(md.mesh.y(data.index)',1,6*md.mesh.numberofelements));
+		z=transpose(reshape(md.mesh.z(data.index)',1,6*md.mesh.numberofelements));
+		is2d=0;
+	end
+end
+
+%units
+if exist(options,'unit'),
+	unit=getfieldvalue(options,'unit');
+	x=x*unit;
+	y=y*unit;
+	z=z*unit;
+end
+
+if isa(md,'planet'),
+	isplanet=1;
+else
+	isplanet=0;
+end
Index: /issm/trunk/src/m/plot/quiver_colorbar.m
===================================================================
--- /issm/trunk/src/m/plot/quiver_colorbar.m	(revision 13395)
+++ /issm/trunk/src/m/plot/quiver_colorbar.m	(revision 13395)
@@ -0,0 +1,41 @@
+function quiver_colorbar(quivers,options)
+%QUIVER_COLORBAR - colorbar for quiver plots
+%
+%   Usage:
+%      quiver_colorbar(quivers,options)
+
+if  strcmpi(getfieldvalue(options,'colorbar','on'),'on'),
+
+	%build ticks
+	hcb=colorbar('peer',gca,'location','EastOutside');
+	ticklabel=cell(1,length(quivers.levels));
+	for i=1:length(quivers.levels),
+		ticklabel{i}=num2str(round_ice(quivers.levels(i),3));
+	end
+	tickpos=1:quivers.numcolors+1;
+
+	%remove ticks if to many have been created
+	proportion=round(length(quivers.levels)/4);
+	if proportion>1,
+		ticklabel=ticklabel(1:proportion:end);
+		tickpos=tickpos(1:proportion:end);
+	end
+
+	%draw colorbar
+	set(hcb,'YTickLabel',ticklabel,'YTick',tickpos);
+	%position
+	if exist(options,'colorbarpos'),
+		set(hcb,'Position',getfieldvalue(options,'colorbarpos'));
+	end
+	%fontsize
+	fontsize=getfieldvalue(options,'fontsize',14);
+	set(hcb,'FontSize',fontsize);
+	
+	if exist(options,'colorbartitle'),
+		backup=gca;
+		axes(hcb);lab=title(getfieldvalue(options,'colorbartitle'));
+		set(lab,'Rotation',getfieldvalue(options,'colorbartitlerotation',0));
+		set(lab,'VerticalAlignment','bottom');
+		axes(backup);
+	end
+end
Index: /issm/trunk/src/m/plot/quiver_process.m
===================================================================
--- /issm/trunk/src/m/plot/quiver_process.m	(revision 13395)
+++ /issm/trunk/src/m/plot/quiver_process.m	(revision 13395)
@@ -0,0 +1,70 @@
+function [quivers,palette]=quiver_process(x,y,u,v,options)
+%QUIVER_PROCESS - process data for color quiver plot
+%
+%   Usage:
+%      [quivers,palette]=quiver_process(x,y,u,v,options)
+
+%keep only non NaN elements
+pos=find(~isnan(x) & ~isnan(y) & ~isnan(u) & ~isnan(v));
+x=x(pos); y=y(pos);
+u=u(pos); v=v(pos);
+
+%get Norm Min and Max
+Norm=sqrt(u.^2+v.^2);
+Min=min(Norm);
+Max=max(Norm);
+
+%Scale data
+scalingfactor=getfieldvalue(options,'scaling',0.40);
+if strcmpi(getfieldvalue(options,'autoscale','on'),'off'),
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./Norm;
+	v=scalingfactor*sqrt(delta)*v./Norm;
+else
+	delta=((min(x)-max(x))^2+(min(y)-max(y))^2)/numel(x);
+	u=scalingfactor*sqrt(delta)*u./max(Norm);
+	v=scalingfactor*sqrt(delta)*v./max(Norm);
+end
+
+%number of colors?
+colorlevels=getfieldvalue(options,'colorlevels',30);
+if isnumeric(colorlevels),
+	if isnan(colorlevels),
+		numcolors=30;
+	else
+		numcolors=colorlevels;
+	end
+	levels=round_ice(linspace(Min,Max,numcolors+1),2);
+else
+	levels=zeros(1,length(colorlevels)+2);
+	levels(1)=Min;
+	for i=1:length(colorlevels)
+		levels(i+1)=colorlevels{i};
+	end
+	levels(end)=Max;
+	levels=sort(unique(levels));
+	numcolors=length(levels)-1;
+end
+
+%create colorind for colors
+colorind=ones(length(u),1);
+for i=1:numcolors
+	pos=find((Norm>=levels(i)) & (Norm<=levels(i+1)) );
+	colorind(pos)=i;
+end
+colorind(find(Norm>levels(end)))=numcolors;
+
+%build output
+quivers=struct('x',x,'y',y,'u',u,'v',v,'levels',levels,'colorind',colorind,'numcolors',numcolors);
+
+%set the colormap 
+if numcolors==2;
+	%blue and red
+	palette=colormap([0 0 1;1 0 0]);
+elseif numcolors==3,
+	%blue yellow and red
+	palette=colormap([0 0 1;1 1 0;1 0 0]);
+else
+	%let jet choose
+	palette=colormap(jet(numcolors));
+end
Index: /issm/trunk/src/m/plot/radarpower.m
===================================================================
--- /issm/trunk/src/m/plot/radarpower.m	(revision 13395)
+++ /issm/trunk/src/m/plot/radarpower.m	(revision 13395)
@@ -0,0 +1,146 @@
+function md=radarpower(md,varargin)
+%RADARPOWER - overlay a power radar image on an existing mesh
+%
+%   This routine will overlay a power radar image on an existing mesh.
+%   The power amplitude will be output to vel for now.
+%   In the future, think about a field to hold this value.
+%
+%   Usage:
+%      md=radarpower(md,options);
+%      md=radarpower(md)
+
+%Parse inputs
+if nargin==1,
+	options=pairoptions;
+else
+	options=varargin{:};
+	if ~isa(options,'pairoptions'),
+		options=pairoptions(varargin{:});
+	end
+end
+
+highres = getfieldvalue(options,'highres',0);
+xlim    = getfieldvalue(options,'xlim',[min(md.mesh.x) max(md.mesh.x)]);
+ylim    = getfieldvalue(options,'ylim',[min(md.mesh.y) max(md.mesh.y)]);
+posting = getfieldvalue(options,'posting',0); % 0 -> image posting default
+
+%find gdal coordinates
+x0=min(xlim); x1=max(xlim);
+y0=min(ylim); y1=max(ylim);
+
+%figure out if we should go look for Greenland or Antarctica geotiff, or if user provided one.
+if ~exist(options,'overlay_image'),
+	if strcmpi(md.mesh.hemisphere,'n'),
+		%if ~exist([jplsvn() '/projects/ModelData/MOG/mog150_greenland_map.jpg']),
+		%	error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MOG/mog150_greenland_map.jpg not found.']);
+		%end
+		%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');
+		%%jpgim='/u/astrid-r1b/morlighe/issmjpl/projects/MorlighemGRL2012/Data/Mosaic_amp_asar2010.jpg';
+		%%geom=load('/u/astrid-r1b/morlighe/issmjpl/projects/MorlighemGRL2012/Data/Mosaic_amp_asar2010.jpgw');
+		%jpgim='/u/astrid-r1b/morlighe/issmjpl/projects/MorlighemGRL2012/Data/Russel_asar2010.png';
+		%geom=load('/u/astrid-r1b/morlighe/issmjpl/projects/MorlighemGRL2012/Data/Russel_asar2010.pngw');
+
+		%%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(3)*geom(4),y0);
+		%ymax=min(geom(6),y1);
+
+		%firstcol=max(1,floor((xmin-geom(5))/geom(1))); %x min
+		%firstrow=max(1,floor((geom(6)-ymax)/geom(4))); %y max
+		%numcols=floor((xmax-xmin)/geom(1)); % x posting
+		%numrows=floor((ymax-ymin)/geom(4)); % y posting
+		%pixelskip=max(1,ceil(posting/geom(1)));
+
+		%%Read and crop file
+		%disp('Warning: expecting coordinates in polar stereographic (Std Latitude: 70ºN Meridian: 45º)');
+		%im=imread(jpgim);
+		%im=im(firstrow:firstrow+numrows-1,firstcol:firstcol+numcols-1);
+		%md.radaroverlay.pwr=double(flipud(im(1:pixelskip:end,1:pixelskip:end)));
+		%md.radaroverlay.x=(xmin:(xmax-xmin)/(size(md.radaroverlay.pwr,2)-1):xmax);
+		%md.radaroverlay.y=(ymin:(ymax-ymin)/(size(md.radaroverlay.pwr,1)-1):ymax);
+		if highres,
+			if ~exist([jplsvn() '/projects/ModelData/MOG/mog100g_r2_hp1.tif']),
+				error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MOG/mog100g_r2_hp1.tif not found.']);
+			end
+			geotiff_name=[jplsvn() '/projects/ModelData/MOG/mog100_r2_hp1.tif'];
+		else
+			if ~exist([jplsvn() '/projects/ModelData/MOG/mog500g_r2_hp1.tif']),
+				error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MOG/mog500g_r2_hp1.tif not found.']);
+			end
+			geotiff_name=[jplsvn() '/projects/ModelData/MOG/mog500_r2_hp1.tif'];
+		end
+
+		%Name of image
+		inputname='./temp.tif';
+		eval(['!gdal_translate -quiet -projwin ' num2str(x0) ' ' num2str(y1) ' ' num2str(x1) ' ' num2str(y0) ' ' geotiff_name ' ' inputname ]);
+
+		%Read in temp.tif:
+		im=imread('temp.tif','TIFF');
+		pixelskip=max(1,ceil(posting/((x1-x0)/(size(im,2)))));
+		md.radaroverlay.pwr=double(flipud(im(1:pixelskip:end,1:pixelskip:end)));
+		md.radaroverlay.x=(x0:(x1-x0)/(size(md.radaroverlay.pwr,2)-1):x1);
+		md.radaroverlay.y=(y0:(y1-y0)/(size(md.radaroverlay.pwr,1)-1):y1);
+
+		%Erase image
+		system('rm -rf ./temp.tif');
+
+
+	elseif strcmpi(md.mesh.hemisphere,'s'),
+		if highres,
+			if ~exist([jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif']),
+				error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif not found.']);
+			end
+			geotiff_name=[jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif'];
+		else
+			if ~exist([jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif']),
+				error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif not found.']);
+			end
+			geotiff_name=[jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif'];
+		end
+
+		%Name of image
+		inputname='./temp.tif';
+		eval(['!gdal_translate -quiet -projwin ' num2str(x0) ' ' num2str(y1) ' ' num2str(x1) ' ' num2str(y0) ' ' geotiff_name ' ' inputname ]);
+
+		%Read in temp.tif:
+		im=imread('temp.tif','TIFF');
+		pixelskip=max(1,ceil(posting/((x1-x0)/(size(im,2)))));
+		md.radaroverlay.pwr=double(flipud(im(1:pixelskip:end,1:pixelskip:end)));
+		md.radaroverlay.x=(x0:(x1-x0)/(size(md.radaroverlay.pwr,2)-1):x1);
+		md.radaroverlay.y=(y0:(y1-y0)/(size(md.radaroverlay.pwr,1)-1):y1);
+
+		%Erase image
+		system('rm -rf ./temp.tif');
+
+	else
+		error('field hemisphere should either be ''n'' or ''s''');
+	end
+else
+	%user provided an image. check we also have overlay_xlim and overlay_ylim  options, to know what range of coordinates the image covers.
+	if (~exist(options,'overlay_xlim') | ~exist(options,'overlay_xlim')| ~exist(options,'overlay_xposting')| ~exist(options,'overlay_yposting')),
+		error('radarpower error message: please provide overlay_xlim, overlay_ylim, overlay_xposting and overlay_yposting options together with overlay_image option');
+	end
+	overlay_image=getfieldvalue(options,'overlay_image');
+	overlay_xlim=getfieldvalue(options,'overlay_xlim');
+	overlay_ylim=getfieldvalue(options,'overlay_ylim');
+	overlay_xposting=getfieldvalue(options,'overlay_xposting');
+	overlay_yposting=getfieldvalue(options,'overlay_yposting');
+
+	sizex=floor((x1-x0)/overlay_xposting);
+	sizey=floor((y1-y0)/overlay_yposting);
+	topleftx=floor((x0-overlay_xlim(1))/overlay_xposting); % x min
+	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º)');
+	im=imread(overlay_image);
+	im=im(toplefty:toplefty+sizey,topleftx:topleftx+sizex);
+	md.radaroverlay.pwr=double(flipud(im));
+	md.radaroverlay.x=(x0:(x1-x0)/(size(md.radaroverlay.pwr,2)-1):x1);
+	md.radaroverlay.y=(y0:(y1-y0)/(size(md.radaroverlay.pwr,1)-1):y1);
+end
Index: /issm/trunk/src/m/plot/scaleruler.m
===================================================================
--- /issm/trunk/src/m/plot/scaleruler.m	(revision 13395)
+++ /issm/trunk/src/m/plot/scaleruler.m	(revision 13395)
@@ -0,0 +1,61 @@
+function scaleruler(options)
+%SCALERULER - overlay a scale ruler on current plot
+%
+%   Usage:
+%      scaleruler(options)
+
+%get options
+structure=getfieldvalue(options,'scaleruler');
+fontsize=getfieldvalue(options,'scaleruler_fontsize',16);
+
+%Go through structure and fill missing arguments
+if length(structure)~=5
+	error('plotmodel error message: bad number of input arguments for scaleruler: [x0 y0 length thickness numberofticks]');
+end
+
+%retrieve north arrow parameters
+x0=structure(1);
+y0=structure(2);
+lengthscale=structure(3);
+widthscale=structure(4);
+numberofticks=structure(5);
+
+%initialize some coordinates
+unitlength=lengthscale/(numberofticks -1);
+flag=-1;
+
+Bd=[x0 y0];
+Bu=[x0 y0+widthscale];
+Tick=0;
+
+%Text
+xt=Bu(1);
+yt=Bu(2)+widthscale;
+text(xt,yt,num2str(Tick),'FontSize',fontsize,'FontWeight','n','HorizontalAlignment','left','VerticalAlignment','baseline');
+
+%loope over the patches
+for i=1:numberofticks-1,
+	Au=Bu;
+	Ad=Bd;
+	Bu=[Au(1)+unitlength Ad(2)+widthscale];
+	Bd=[Ad(1)+unitlength Ad(2)];
+	Tick=Tick+unitlength;
+
+	%pathes
+	if flag==-1
+		p=patch([Ad(1) Bd(1) Bu(1) Au(1)],[Ad(2) Bd(2) Bu(2) Au(2)],'Black','FaceAlpha',0.5);
+	else
+		p=patch([Ad(1) Bd(1) Bu(1) Au(1)],[Ad(2) Bd(2) Bu(2) Au(2)],'White','FaceAlpha',0.3);
+	end
+
+	%flip flag
+	flag=-flag;
+
+	%Text
+	xt=Bu(1);
+	yt=Bu(2)+widthscale;
+	if i~=numberofticks-1,
+		text(xt,yt,num2str(round_ice(Tick/1000,3)),'FontSize',fontsize,'FontWeight','n','HorizontalAlignment','left','VerticalAlignment','baseline');
+	end
+end
+text(xt,yt,[num2str(round_ice(Tick/1000,3)) ' km'],'FontSize',fontsize,'FontWeight','n','HorizontalAlignment','left','VerticalAlignment','baseline');
Index: /issm/trunk/src/m/plot/showregion.m
===================================================================
--- /issm/trunk/src/m/plot/showregion.m	(revision 13395)
+++ /issm/trunk/src/m/plot/showregion.m	(revision 13395)
@@ -0,0 +1,34 @@
+function showregion(md,insetpos)
+%SHOWREGION - show region on plot
+%
+%   Usage:
+%      showregion(md,insetpos);
+
+%get inset relative position (x,y,width,height)
+%insetpos=getfieldvalue(options,'insetpos',[0.02 0.70 0.18 0.18]);
+
+%get current plos position
+cplotpos=get(gca,'pos');
+%compute inset position
+PosInset=[cplotpos(1)+insetpos(1)*cplotpos(3),cplotpos(2)+insetpos(2)*cplotpos(4), insetpos(3)*cplotpos(3), insetpos(4)*cplotpos(4)];
+axes('pos',PosInset);
+axis equal off
+%box off
+if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
+	A=expread([issmdir() 'projects/Exp/Greenland.exp']);
+elseif strcmpi(md.mesh.hemisphere,'s') | strcmpi(md.mesh.hemisphere,'south'),
+	A=expread([issmdir() '/projects/Exp/Antarctica.exp']);
+else
+	error('applyoptions error message: hemisphere not defined');
+end
+
+Ax=[min(A.x) max(A.x)];
+Ay=[min(A.y) max(A.y)];
+
+mdx=[min(md.mesh.x) max(md.mesh.x)];
+mdy=[min(md.mesh.y) max(md.mesh.y)];
+
+line(A.x,A.y,'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)
+colorbar('off');
Index: /issm/trunk/src/m/plot/squarezoom.m
===================================================================
--- /issm/trunk/src/m/plot/squarezoom.m	(revision 13395)
+++ /issm/trunk/src/m/plot/squarezoom.m	(revision 13395)
@@ -0,0 +1,20 @@
+function squarezoom()
+%SQUAREZOOM - zoom on a part of a figure
+%
+%   Usage:
+%      squarezoom()
+
+disp('Click twice to define a square where you want to zoom. First click for upper left corner, second for lower right corner');
+[x,y]=ginput(2);
+dx=x(2)-x(1);
+dy=y(1)-y(2);
+
+if dx>dy,
+	delta=dx-dy;
+	xlim([x(1) x(2)]);
+	ylim([y(2)-delta/2 y(1)+delta/2]);
+else
+	delta=dy-dx;
+	xlim([x(1)-delta/2 x(2)+delta/2]);
+	ylim([y(2) y(1)]);
+end
Index: /issm/trunk/src/m/plot/subplotmodel.m
===================================================================
--- /issm/trunk/src/m/plot/subplotmodel.m	(revision 13395)
+++ /issm/trunk/src/m/plot/subplotmodel.m	(revision 13395)
@@ -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/trunk/src/m/print/printmodel.m
===================================================================
--- /issm/trunk/src/m/print/printmodel.m	(revision 13395)
+++ /issm/trunk/src/m/print/printmodel.m	(revision 13395)
@@ -0,0 +1,100 @@
+function printmodel(filename,format,varargin)
+%PRINTMODEL - save an image of current figure
+%
+%   filename: output name of image file (no extension)
+%   format: image format (ex: 'tiff','jpg','pdf') 
+%
+%   List of options to printfmodel: 
+%
+%   figure: number of figure to print (default: current figure)
+%   resolution: use higher resolution to anti-alias (default 2)
+%   margin: add margin around final image  
+%   marginsize: size of margin around final image (default 5)
+%   frame: add frame around final image
+%   framesize: size of frame around final image (default 5)
+%   framecolor: color of frame around final image (default 'black')
+%   trim: trim empty space around image (default 'off')
+%   hardcopy: 'off' to impose MATLAB to use the same colors (default 'off')
+%   
+%   Usage:
+%      printmodel(filename,format,varargin);
+%
+%   Examples:
+%      printmodel('image','tiff')
+%      printmodel('image','eps','margin','on','frame','on','hardcopy','on')
+
+
+%get options: 
+options=pairoptions(varargin{:});
+
+%set defaults
+options=addfielddefault(options,'figure','gcf');
+options=addfielddefault(options,'format','tiff');
+options=addfielddefault(options,'resolution',1);
+options=addfielddefault(options,'margin','on');
+options=addfielddefault(options,'marginsize',25);
+options=addfielddefault(options,'frame','on');
+options=addfielddefault(options,'framesize',3);
+options=addfielddefault(options,'framecolor','black');
+options=addfielddefault(options,'trim','on');
+options=addfielddefault(options,'hardcopy','off');
+
+%get fig: 
+fig=getfieldvalue(options,'figure');
+if ischar(fig),
+	fig=gcf;
+else
+	figure(fig);
+	fig=gcf;
+end
+
+%In auto mode, MATLAB prints the figure the same size as it appears on the computer screen, centered on the page
+set(fig, 'PaperPositionMode', 'auto');
+
+%InvertHardcopy off imposes MATLAB to use the same colors
+set(fig, 'InvertHardcopy', getfieldvalue(options,'hardcopy'));
+
+
+%we could have several formats, as a cell array of strings.
+formats=format;
+if ~iscell(formats),
+	formats={formats};
+end
+
+%loop on formats:
+for i=1:length(formats),
+	format=formats{i};
+
+	%Use higher resolution to anti-alias and use zbuffer to have smooth colors
+	print(fig, '-zbuffer','-dtiff',['-r' num2str(get(0,'ScreenPixelsPerInch')*getfieldvalue(options,'resolution'))],filename);
+
+	%some trimming involved? 
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'trim'),'on'),
+			system(['convert -trim ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	%margin?
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'margin'),'on'),
+			marginsize=getfieldvalue(options,'marginsize');
+			system(['convert -border ' num2str(marginsize) 'x' num2str(marginsize) ' -bordercolor "white" ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	%frame?
+	if ~strcmpi(format,'pdf'),
+		if strcmpi(getfieldvalue(options,'frame'),'on'),
+			framesize=getfieldvalue(options,'framesize');
+			framecolor=getfieldvalue(options,'framecolor');
+			system(['convert -border ' num2str(framesize) 'x' num2str(framesize) ' -bordercolor "' framecolor '" ' filename '.tif ' filename '.tif']);
+		end
+	end
+
+	%convert image to correct format
+	if ~strcmpi(format,'tiff') & ~strcmpi(format,'tif'),
+		system(['convert ' filename '.tif ' filename '.' format]);
+		delete([ filename '.tif']);
+	end
+end
Index: /issm/trunk/src/m/qmu/lclist_write.m
===================================================================
--- /issm/trunk/src/m/qmu/lclist_write.m	(revision 13395)
+++ /issm/trunk/src/m/qmu/lclist_write.m	(revision 13395)
@@ -0,0 +1,62 @@
+%
+%  function to write linear constraint list
+%
+function []=lclist_write(fidi,cstring,cstring2,dvar)
+
+if isempty(dvar)
+    return;
+end
+
+%  put linear constraints into lists for writing
+
+nvar=0;
+pmatrix=[];
+plower =[];
+pupper =[];
+ptarget=[];
+pstype =[];
+pscale =[];
+
+fnames=fieldnames(dvar);
+for i=1:numel(fnames)
+    nvar=nvar+numel(dvar.(fnames{i}));
+    pmatrix=[pmatrix prop_matrix(dvar.(fnames{i}))];
+    plower =[plower  prop_lower(dvar.(fnames{i})) ];
+    pupper =[pupper  prop_upper(dvar.(fnames{i})) ];
+    ptarget=[ptarget prop_target(dvar.(fnames{i}))];
+    pstype =[pstype  prop_stype(dvar.(fnames{i})) ];
+    pscale =[pscale  prop_scale(dvar.(fnames{i})) ];
+end
+
+%  write linear constraints
+
+disp(sprintf('  Writing %d %s linear constraints.',...
+    nvar,cstring));
+
+if ~isempty(pmatrix)
+    fprintf(fidi,'\t  %s_matrix =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pmatrix,6,76);
+end
+if ~isempty(plower)
+    fprintf(fidi,'\t  %s_lower_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),plower ,6,76);
+end
+if ~isempty(pupper)
+    fprintf(fidi,'\t  %s_upper_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pupper ,6,76);
+end
+if ~isempty(ptarget)
+    fprintf(fidi,'\t  %s_targets =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),ptarget,6,76);
+end
+if ~isempty(pstype)
+    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+end
+if ~isempty(pscale)
+    fprintf(fidi,'\t  %s_scales =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pscale ,6,76);
+end
+
+end
+
Index: /issm/trunk/src/m/qmu/param_write.m
===================================================================
--- /issm/trunk/src/m/qmu/param_write.m	(revision 13395)
+++ /issm/trunk/src/m/qmu/param_write.m	(revision 13395)
@@ -0,0 +1,24 @@
+%
+%  function to write a parameter
+%
+function []=param_write(fidi,sbeg,pname,smid,send,params)
+
+if ~isfield(params,pname)
+    warning('param_write:param_not_found',...
+        'Parameter ''%s'' not found in structure.',pname);
+    return
+end
+
+if islogical(params.(pname)) && ~params.(pname)
+    return
+end
+
+if     islogical(params.(pname))
+    fprintf(fidi,[sbeg '%s' send],pname);
+elseif ischar   (params.(pname))
+    fprintf(fidi,[sbeg '%s' smid '%s' send],pname,params.(pname));
+elseif isnumeric(params.(pname))
+    fprintf(fidi,[sbeg '%s' smid '%g' send],pname,params.(pname));
+end
+
+end
Index: /issm/trunk/src/m/qmu/rlev_write.m
===================================================================
--- /issm/trunk/src/m/qmu/rlev_write.m	(revision 13395)
+++ /issm/trunk/src/m/qmu/rlev_write.m	(revision 13395)
@@ -0,0 +1,66 @@
+%
+%  function to write response levels
+%
+function []=rlev_write(fidi,dresp,params)
+
+if isempty(dresp)
+    return;
+end
+
+%  put responses into lists for writing
+
+nresp=0;
+respl={};
+probl={};
+rell ={};
+grell={};
+
+fnames=fieldnames(dresp);
+for i=1:numel(fnames)
+    nresp=nresp+numel(dresp.(fnames{i}));
+    [respli,probli,relli,grelli]=prop_levels(dresp.(fnames{i}));
+    respl=[respl respli];
+    probl=[probl probli];
+    rell =[rell  relli ];
+    grell=[grell grelli];
+end
+
+%  write response levels
+
+param_write(fidi,'\t  ','distribution',' ','\n',params);
+if ~isempty(respl)
+    rlevi_write(fidi,'response_levels',respl);
+    param_write(fidi,'\t  ','compute',' ','\n',params);
+end 
+if ~isempty(probl)
+    rlevi_write(fidi,'probability_levels',probl);
+end
+if ~isempty(rell)
+    rlevi_write(fidi,'reliability_levels',rell);
+end
+if ~isempty(grell)
+    rlevi_write(fidi,'gen_reliability_levels',grell);
+end
+
+end
+
+%
+%  function to each type of response level
+%
+function []=rlevi_write(fidi,ltype,levels)
+
+fprintf(fidi,'\t  num_%s =',ltype);
+for i=1:numel(levels)
+    fprintf(fidi,' %d',length(levels{i}));
+end
+fprintf(fidi,'\n');
+
+fprintf(fidi,'\t  %s =\n',ltype);
+
+for i=1:numel(levels)
+    if ~isempty(levels{i})
+        vector_write(fidi,sprintf('\t    '),levels{i},8,76);
+    end
+end
+
+end
Index: /issm/trunk/src/m/qmu/rlist_write.m
===================================================================
--- /issm/trunk/src/m/qmu/rlist_write.m	(revision 13395)
+++ /issm/trunk/src/m/qmu/rlist_write.m	(revision 13395)
@@ -0,0 +1,70 @@
+%
+%  function to write response list
+%
+function [rdesc]=rlist_write(fidi,cstring,cstring2,dresp,rdesc)
+
+if isempty(dresp)
+    return;
+end
+
+%  put responses into lists for writing
+%  (and accumulate descriptors into list for subsequent writing)
+
+nresp=0;
+pstype =[];
+pscale =[];
+pweight=[];
+plower =[];
+pupper =[];
+ptarget=[];
+
+fnames=fieldnames(dresp);
+for i=1:numel(fnames)
+    nresp=nresp+numel(dresp.(fnames{i}));
+    pstype =[pstype  prop_stype(dresp.(fnames{i})) ];
+    pscale =[pscale  prop_scale(dresp.(fnames{i})) ];
+    pweight=[pweight prop_weight(dresp.(fnames{i}))];
+    plower =[plower  prop_lower(dresp.(fnames{i})) ];
+    pupper =[pupper  prop_upper(dresp.(fnames{i})) ];
+    ptarget=[ptarget prop_target(dresp.(fnames{i}))];
+    rdesc  =[rdesc   prop_desc(dresp.(fnames{i}),fnames{i})];
+end
+
+%  write responses
+
+disp(sprintf('  Writing %d %s responses.',nresp,cstring));
+
+fprintf(fidi,'\tnum_%s = %d\n',cstring,nresp);
+if ~isempty(pstype)
+    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+end
+if ~isempty(pscale)
+    fprintf(fidi,'\t  %s_scales =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pscale ,6,76);
+end
+if ~isempty(pweight)
+    switch cstring2
+        case 'objective_function'
+            fprintf(fidi,'\t  %s_weights =\n','multi_objective');
+            vector_write(fidi,sprintf('\t    '),pweight,6,76);
+        case 'least_squares_term'
+            fprintf(fidi,'\t  %s_weights =\n','least_squares');
+            vector_write(fidi,sprintf('\t    '),pweight,6,76);
+    end
+end
+if ~isempty(plower)
+    fprintf(fidi,'\t  %s_lower_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),plower ,6,76);
+end
+if ~isempty(pupper)
+    fprintf(fidi,'\t  %s_upper_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pupper ,6,76);
+end
+if ~isempty(ptarget)
+    fprintf(fidi,'\t  %s_targets =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),ptarget,6,76);
+end
+
+end
+
Index: /issm/trunk/src/m/qmu/sensitivities.m
===================================================================
--- /issm/trunk/src/m/qmu/sensitivities.m	(revision 13394)
+++ /issm/trunk/src/m/qmu/sensitivities.m	(revision 13395)
@@ -42,5 +42,8 @@
 
 	%ipick up the variable in the model
-	variable=md.(EnumToModelField(StringToEnum(variablename)));
+	switch variablename,
+		case 'thickness', variable = md.geometry.thickness; 
+		otherwise, error(['scaled variable ' variablename  ' not associated to any model field']);
+	end
 
 	%average it onto the partition
Index: /issm/trunk/src/m/qmu/vector_write.m
===================================================================
--- /issm/trunk/src/m/qmu/vector_write.m	(revision 13395)
+++ /issm/trunk/src/m/qmu/vector_write.m	(revision 13395)
@@ -0,0 +1,52 @@
+
+%%  function to write a vector on multiple lines
+
+function []=vector_write(fidi,sbeg,vec,nmax,cmax)
+
+if ~exist('nmax','var') || isempty(nmax)
+    nmax=Inf;
+end
+if ~exist('cmax','var') || isempty(cmax)
+    cmax=Inf;
+end
+
+%  set up first iteration
+
+svec =[];
+nitem=nmax;
+lsvec=cmax;
+
+%  transpose vector from column-wise to row-wise
+
+vec=vec';
+
+%  assemble each line, flushing when necessary
+
+for i=1:numel(vec)
+    if isnumeric(vec(i))
+        sitem=sprintf('%g'    ,vec(i));
+    else
+        sitem=sprintf('''%s''',char(vec(i)));
+    end
+    nitem=nitem+1;
+    lsvec=lsvec+1+length(sitem);
+    
+    if (nitem <= nmax) && (lsvec <= cmax)
+        svec=[svec ' ' sitem];
+    else
+        if ~isempty(svec)
+            fprintf(fidi,'%s\n',svec);
+        end
+        svec=[sbeg sitem];
+        nitem=1;
+        lsvec=length(svec);
+    end
+end
+
+%  flush buffer at end, if necessary
+
+if ~isempty(svec)
+    fprintf(fidi,'%s\n',svec);
+end
+
+end
Index: /issm/trunk/src/m/qmu/vlist_write.m
===================================================================
--- /issm/trunk/src/m/qmu/vlist_write.m	(revision 13395)
+++ /issm/trunk/src/m/qmu/vlist_write.m	(revision 13395)
@@ -0,0 +1,80 @@
+%
+%  function to write variable list
+%
+function []=vlist_write(fidi,cstring,cstring2,dvar)
+
+if isempty(dvar)
+    return;
+end
+
+%  put variables into lists for writing
+
+nvar=0;
+pinitpt=[];
+plower =[];
+pupper =[];
+pmean  =[];
+pstddev=[];
+pinitst=[];
+pstype =[];
+pscale =[];
+pdesc  =[];
+
+fnames=fieldnames(dvar);
+for i=1:numel(fnames)
+    nvar=nvar+numel(dvar.(fnames{i}));
+    pinitpt=[pinitpt prop_initpt(dvar.(fnames{i}))];
+    plower =[plower  prop_lower(dvar.(fnames{i})) ];
+    pupper =[pupper  prop_upper(dvar.(fnames{i})) ];
+    pmean  =[pmean   prop_mean(dvar.(fnames{i}))  ];
+    pstddev=[pstddev prop_stddev(dvar.(fnames{i}))];
+    pinitst=[pinitst prop_initst(dvar.(fnames{i}))];
+    pstype =[pstype  prop_stype(dvar.(fnames{i})) ];
+    pscale =[pscale  prop_scale(dvar.(fnames{i})) ];
+    pdesc  =[pdesc   prop_desc(dvar.(fnames{i}),fnames{i})];
+end
+
+%  write variables
+%  (using Dakota 4.1 syntax for backward compatability)
+
+disp(sprintf('  Writing %d %s variables.',nvar,cstring));
+
+fprintf(fidi,'\t%s = %d\n',cstring,nvar);
+if ~isempty(pinitpt)
+    fprintf(fidi,'\t  %s_initial_point =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pinitpt,6,76);
+end
+if ~isempty(plower)
+    fprintf(fidi,'\t  %s_lower_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),plower ,6,76);
+end
+if ~isempty(pupper)
+    fprintf(fidi,'\t  %s_upper_bounds =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pupper ,6,76);
+end
+if ~isempty(pmean)
+    fprintf(fidi,'\t  %s_means =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pmean  ,6,76);
+end
+if ~isempty(pstddev)
+    fprintf(fidi,'\t  %s_std_deviations =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstddev,6,76);
+end
+if ~isempty(pinitst)
+    fprintf(fidi,'\t  %s_initial_state =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pinitst,6,76);
+end
+if ~isempty(pstype)
+    fprintf(fidi,'\t  %s_scale_types =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pstype ,6,76);
+end
+if ~isempty(pscale)
+    fprintf(fidi,'\t  %s_scales =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pscale ,6,76);
+end
+if ~isempty(pdesc)
+    fprintf(fidi,'\t  %s_descriptors =\n',cstring2);
+    vector_write(fidi,sprintf('\t    '),pdesc  ,6,76);
+end
+
+end
Index: /issm/trunk/src/m/regional/BasinConstrain.m
===================================================================
--- /issm/trunk/src/m/regional/BasinConstrain.m	(revision 13395)
+++ /issm/trunk/src/m/regional/BasinConstrain.m	(revision 13395)
@@ -0,0 +1,63 @@
+function md=BasinConstrain(md,domain);
+%BASINCONSTRAIN - constrain basin
+%
+%   Constrain basin using a constraint domain outline, 
+%   to dirichlet boundary conditions.
+%   constraindomain is an Argus domain outline file enclosing 
+%   the geographical area of interest.
+%
+%   Usage: 
+%      md=BasinConstrain(md,constraindomain)
+%
+%   Example:
+%      md=BasinConstrain(md,'DomainOutline.exp');
+%      md=BasinConstrain(md,'~Iceshelves.exp');
+
+%now, flag nodes and elements outside the domain outline.
+if ischar(domain),
+	if isempty(domain),
+		elementondomain=zeros(md.mesh.numberofelements,1);
+		vertexondomain=zeros(md.mesh.numberofvertices,1);
+		invert=0;
+	elseif strcmpi(domain,'all')
+		elementondomain=ones(md.mesh.numberofelements,1);
+		vertexondomain=ones(md.mesh.numberofvertices,1);
+		invert=0;
+	else
+		%make sure that we actually don't want the elements outside the domain outline!
+		if strcmpi(domain(1),'~'),
+			domain=domain(2:end);
+			invert=1;
+		else
+			invert=0;
+		end
+		%ok, flag elements and nodes
+		[vertexondomain elementondomain]=ContourToMesh(md.mesh.elements(:,1:3),md.mesh.x,md.mesh.y,domain,'element and node',2);
+	end
+	if invert,
+		vertexondomain=~vertexondomain;
+		elementondomain=~elementondomain;
+	end
+else
+	error('BasinConstrain error message: domain type not supported yet');
+end
+
+%list of elements and nodes not on domain
+vertexnotondomain=find(~vertexondomain);
+elementnotondomain=find(~elementondomain);
+
+%all elements outside the constraint domain are equivalent to water. all nodes outside are spc'd.
+md.diagnostic.spcvx(vertexnotondomain)=md.inversion.vx_obs(vertexnotondomain);
+md.diagnostic.spcvy(vertexnotondomain)=md.inversion.vy_obs(vertexnotondomain);
+md.mask.elementonwater(elementnotondomain)=1;
+
+%now, make sure all elements on water have nodes that are spc'd, otherwise, we'll get a singular problem.
+pos=find(~md.mask.elementonwater);
+numpos=unique(md.mesh.elements(pos,:));
+nodes=setdiff(1:1:md.mesh.numberofvertices,numpos);
+md.diagnostic.spcvx(nodes)=md.inversion.vx_obs(nodes);
+md.diagnostic.spcvy(nodes)=md.inversion.vy_obs(nodes);
+
+%make sure icefronts that are completely spc'd are taken out:
+free_segments=find((~isnan(md.diagnostic.spcvx(md.diagnostic.icefront(:,1:2))) + ~isnan(md.diagnostic.spcvy(md.diagnostic.icefront(:,1:2))))~=2);
+md.diagnostic.icefront=md.diagnostic.icefront(free_segments,:);
Index: /issm/trunk/src/m/regional/BasinConstrainShelf.m
===================================================================
--- /issm/trunk/src/m/regional/BasinConstrainShelf.m	(revision 13395)
+++ /issm/trunk/src/m/regional/BasinConstrainShelf.m	(revision 13395)
@@ -0,0 +1,74 @@
+function md=BasinConstrainShelf(md,domain);
+%BASINCONSTRAIN - constrain basin
+%
+%   Constrain basin using a constraint domain outline, 
+%   to dirichlet boundary conditions.
+%   constraindomain is an Argus domain outline file enclosing 
+%   the geographical area of interest.
+%
+%   Usage: 
+%      md=BasinConstrain(md,constraindomain)
+%
+%   Example:
+%      md=BasinConstrain(md,'DomainOutline.exp');
+%      md=BasinConstrain(md,'~Iceshelves.exp');
+
+%now, flag nodes and elements outside the domain outline.
+if ischar(domain),
+	if isempty(domain),
+		elementondomain=zeros(md.mesh.numberofelements,1);
+		vertexondomain=zeros(md.mesh.numberofvertices,1);
+		invert=0;
+	elseif strcmpi(domain,'all')
+		elementondomain=ones(md.mesh.numberofelements,1);
+		vertexondomain=ones(md.mesh.numberofvertices,1);
+		invert=0;
+	else
+		%make sure that we actually don't want the elements outside the domain outline!
+		if strcmpi(domain(1),'~'),
+			domain=domain(2:end);
+			invert=1;
+		else
+			invert=0;
+		end
+		%ok, flag elements and nodes
+		[vertexondomain elementondomain]=ContourToMesh(md.mesh.elements(:,1:3),md.mesh.x,md.mesh.y,domain,'element and node',2);
+	end
+	if invert,
+		vertexondomain=~vertexondomain;
+		elementondomain=~elementondomain;
+	end
+else
+	error('BasinConstrain error message: domain type not supported yet');
+end
+
+%list of elements and nodes not on domain
+vertexnotondomain=find(~vertexondomain);
+elementnotondomain=find(~elementondomain);
+
+%all elements outside the constraint domain are equivalent to water. all nodes outside are spc'd.
+md.diagnostic.spcvx(vertexnotondomain)=md.inversion.vx_obs(vertexnotondomain);
+md.diagnostic.spcvy(vertexnotondomain)=md.inversion.vy_obs(vertexnotondomain);
+md.mask.elementonwater(elementnotondomain)=1;
+
+%now, make sure all elements on water have nodes that are spc'd, otherwise, we'll get a singular problem.
+pos=find(~md.mask.elementonwater);
+numpos=unique(md.mesh.elements(pos,:));
+nodes=setdiff(1:1:md.mesh.numberofvertices,numpos);
+md.diagnostic.spcvx(nodes)=md.inversion.vx_obs(nodes);
+md.diagnostic.spcvy(nodes)=md.inversion.vy_obs(nodes);
+
+%make sure any node with NaN velocity is spc'd:
+%we spc to the smoothed value, so that control methods don't go berserk trying to figure out what reaction force to apply for the spc to stand.
+pos=find(isnan(md.inversion.vel_obs_raw));
+md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos); 
+md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos); 
+
+%iceshelves: any vertex on floating ice is spc'd
+pos=find(md.mask.vertexongroundedice);
+md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos); 
+md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos); 
+
+%make sure icefronts that are completely spc'd are taken out:
+free_segments=find((~isnan(md.diagnostic.spcvx(md.diagnostic.icefront(:,1:2))) + ~isnan(md.diagnostic.spcvy(md.diagnostic.icefront(:,1:2))) )~=2);
+md.diagnostic.icefront=md.diagnostic.icefront(free_segments,:);
Index: /issm/trunk/src/m/regional/basinzoom.m
===================================================================
--- /issm/trunk/src/m/regional/basinzoom.m	(revision 13395)
+++ /issm/trunk/src/m/regional/basinzoom.m	(revision 13395)
@@ -0,0 +1,94 @@
+function varargout=basinzoom(varargin)
+%ANTZOOM - zoom on a basin in Antarctica or Greenland.
+%
+%   This function zooms on an existing figure describing Antarctica or Greenland 
+%   The zooming depends on the region name provided as input. 
+%
+%   Usage:
+%      varargout=basinzoom(options)
+
+%recover some options, and set defaults
+
+%is varargin an options database already?
+if nargin==0,
+	options=pairoptions(varargin{:});
+elseif (isa(varargin{1},'plotoptions') | isa(varargin{1},'pairoptions')),
+	%do nothing to the varargin: 
+	options=varargin{1};
+else
+	%process varargin for options: 
+	options=pairoptions(varargin{:});
+end
+
+unitmultiplier=getfieldvalue(options,'unit',NaN);
+basin=getfieldvalue(options,'basin');
+
+if exist(options,'basindelta'),
+
+	basindeltax=getfieldvalue(options,'basindelta',300); 
+	basindeltay=getfieldvalue(options,'basindelta',300); 
+else
+	basindeltax=getfieldvalue(options,'basindeltax',300); 
+	basindeltay=getfieldvalue(options,'basindeltay',300);
+end
+
+%multiply by 1000 to get kms
+basindeltax=basindeltax*1000;
+basindeltay=basindeltay*1000;
+
+%Ok, find basin we are talking about: 
+load([jplsvn() '/projects/ModelData/Names/Names.mat']);
+		
+%Go through names: 
+found=0;
+for i=1:size(names,1),
+	if strcmpi(names{i,1},basin),
+		%ok, we've got the region. Get lat and long: 
+		long=names{i,2};
+		lat=names{i,3};
+		hemisphere=names{i,4};
+		found=1;
+		break;
+	end
+end
+
+if ~found,
+	error(['basinzoom error message: cannot find basin ' basin '. Use isbasin to determine a basin name.']);
+end
+
+if hemisphere==+1,
+	central_meridian=getfieldvalue(options,'central_meridian',45);
+	standard_parallel=getfieldvalue(options,'standard_parallel',70);
+else
+	central_meridian=getfieldvalue(options,'central_meridian',0);
+	standard_parallel=getfieldvalue(options,'standard_parallel',71);
+end
+
+%Transform lat long into x,y: 
+[xc,yc]=ll2xy(lat,long,hemisphere,central_meridian,standard_parallel);
+
+%compute x0,x1 and y0,y1 using basindeltax and basindeltay
+x0=xc-basindeltax/2;
+x1=xc+basindeltax/2;
+y0=yc-basindeltay/2;
+y1=yc+basindeltay/2;
+
+if ~isnan(unitmultiplier)
+	x0=x0*unitmultiplier;
+	x1=x1*unitmultiplier;
+	y0=y0*unitmultiplier;
+	y1=y1*unitmultiplier;
+end
+
+%if output arguments are present, return the limits, 
+%otherwise, set them on the current graphic. 
+if nargout==2,
+	found=1;
+	varargout{1}=[x0 x1];
+	varargout{2}=[y0 y1];
+else
+	xlim([x0 x1]);
+	ylim([y0 y1]);
+	found=1;
+	daspect([1;1;1]);
+end
Index: /issm/trunk/src/m/regional/isbasin.m
===================================================================
--- /issm/trunk/src/m/regional/isbasin.m	(revision 13395)
+++ /issm/trunk/src/m/regional/isbasin.m	(revision 13395)
@@ -0,0 +1,17 @@
+function isbasin(name)
+%ISBASIN: figure out if a basin name exists.
+%
+%
+%        Usage:  index=isbasin('jks');
+%
+%
+
+%First, load basin names:
+load([jplsvn '/projects/ModelData/Names/Names.mat']);
+
+%go through names: 
+for i=1:length(names),
+	if ~isempty(strfind(names{i,1},name)),
+		disp(['''' names{i,1} ''' Long:' num2str(names{i,2}) ' Lat:' num2str(names{i,3}) ]);
+	end
+end
Index: /issm/trunk/src/m/regional/plotbasins.m
===================================================================
--- /issm/trunk/src/m/regional/plotbasins.m	(revision 13395)
+++ /issm/trunk/src/m/regional/plotbasins.m	(revision 13395)
@@ -0,0 +1,18 @@
+%display all the domain outlines in a directory
+
+basins=listfiles;
+
+hold on
+for i=1:length(basins), 
+	%check whether this is a .exp file
+	basin=basins{i};
+	if strcmpi(basin(end-3:end),'.exp'),
+
+		contour=expread(basin,0);
+		x=contour(1).x;
+		y=contour(1).y;
+		x0=mean(x); y0=mean(y);
+		text(x0,y0,basin(1:end-4),'Fontsize',14);
+		expdisp(basin);
+	end
+end
Index: /issm/trunk/src/m/regional/regionaltransient2d.m
===================================================================
--- /issm/trunk/src/m/regional/regionaltransient2d.m	(revision 13395)
+++ /issm/trunk/src/m/regional/regionaltransient2d.m	(revision 13395)
@@ -0,0 +1,158 @@
+function md2=regionaltransient2d(md1,area,hmin,hmax,err,stepres)
+%regionaltransient2d - extract a model according to an Argus contour or flag list and remesh
+%               at new resolution res
+%
+%   This routine extracts a submodel from a bigger model with respect to a given contour
+%   md must be followed by the corresponding exp domain file (argus type, .exp extension). 
+%   The model will be remeshed at high rsolution hmin and low resolution hmax.  The ice 
+%   boundary velocities will be spc'd to the transient velocities at saved transient steps
+%   at the resolution optionally provided for stepres.  A stepres of 2 means that you wish
+%   to skip every other saved transient step.  This is useful when extracting a long transient.
+%
+%   Usage:
+%      md2=regionaltransient2d(md1,area,hmin,hmax,err);
+%
+%   Examples:
+%      md2=regionaltransient2d(md,'Domain.exp',500,10000,[15 250]);
+%      md2=regionaltransient2d(md,'Domain.exp',3000,15000,[10 300],2);
+%
+%   See also: MODELEXTRACT, EXTRUDE, COLLAPSE
+
+%some checks
+if ((nargin~=5) & (nargin~=6)),
+	help regionaltransient2d 
+	error('regionaltransient2d error message: bad usage');
+end
+
+%get check option
+if (nargin==5),
+	stepres=1;
+end
+
+%take every fields from model
+mde=modelextract(md1,area);
+mde.private.bamg=[];
+mde.mesh.extractedvertices=nan;
+mde.mesh.extractedelements=nan;
+
+%remesh
+md2=bamg(mde,'hmin',hmin,'hmax',hmax,'field',[mde.inversion.vel_obs mde.geometry.surface],'splitcorner',1,'KeepVertices',0,'err',err);
+md2=setmask(md2,'','');
+
+%automatically modify fields
+
+	%loop over model fields
+	model_fields=fields(md1);
+	for i=1:length(model_fields),
+
+		%get field
+		field=md1.(model_fields{i});
+		fieldsize=size(field);
+
+		%copy field, interpolated to new mesh
+		if isobject(field), %recursive call
+			object_fields=fields(md1.(model_fields{i}));
+			fname=['(model_fields{i}).(object_fields{j})'];
+		else
+			object_fields=field;
+			fname=['(model_fields{i})'];
+		end
+		for j=1:length(object_fields),
+			%get field
+			field=eval(['md2.' fname]);
+			fieldsize=size(field);
+
+			%size = number of nodes * n
+			for n=1:fieldsize(2)
+				if fieldsize(1)==mde.mesh.numberofvertices
+					if(sum(field(:,n) ~= field(1,n)) == 0)
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices,n)=field(1,n)*ones(md2.mesh.numberofvertices,1);']);
+					else
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices,n)=InterpFromMeshToMesh2d(mde.mesh.elements,mde.mesh.x,mde.mesh.y,field(:,n),md2.mesh.x,md2.mesh.y);']);
+					end
+					eval(['md2.' fname '(:,n)=md2.' fname '(1:md2.mesh.numberofvertices,n);']);
+				elseif fieldsize(1)==mde.mesh.numberofvertices+1
+					if(sum(field(1:end-1,n) ~= field(1,n)) == 0)
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices+1,n)=[field(1,n)*ones(md2.mesh.numberofvertices,1); field(end,n)];']);
+					else
+						eval(['md2.' fname '(1:md2.mesh.numberofvertices+1,n)=[InterpFromMeshToMesh2d(mde.mesh.elements,mde.mesh.x,mde.mesh.y,field(1:end-1,n),md2.mesh.x,md2.mesh.y); field(end,n)];']);
+					end
+					eval(['md2.' fname '(:,n)=md2.' fname '(1:md2.mesh.numberofvertices+1,n)']);
+					%size = number of elements * n
+				elseif fieldsize(1)==mde.mesh.numberofelements
+					if(sum(field(1:end-1,n) ~= field(1,n)) == 0)
+						eval(['md2.' fname '(1:md2.mesh.numberofelements,n)=field(1,n)*ones(md2.mesh.numberofelements,1);']);
+					else
+						eval(['md2.' fname '(1:md2.mesh.numberofelements,n)=InterpFromMeshToMesh2d(mde.mesh.elements,mde.mesh.x,mde.mesh.y,field(:,n),md2.mesh.x,md2.mesh.y);']);
+					end
+					eval(['md2.' fname '(:,n)=md2.' fname '(1:md2.mesh.numberofelements,n);']);
+				end
+			end
+		end
+	end
+
+	%Read transient velocities and thickness, looping through only the populated times
+	spcx=[];
+	spcy=[];
+	spct=[];
+	steps=[];
+	nsteps=length(md1.results.TransientSolution);
+	count=0;
+	numElements=arrayfun(@(x) numel(x.step), md1.results.TransientSolution);
+	for t=find(numElements==1)
+		if ~isempty(md1.results.TransientSolution(t).Vel) & mod(count,stepres)==0,
+			vx=PatchToVec(md1.results.TransientSolution(t).Vx);
+			vy=PatchToVec(md1.results.TransientSolution(t).Vy);
+			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,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];
+		end
+		count=count+1;
+	end
+
+	%As long as there are recorded time steps, spc the boundaries with velocities
+	if nsteps > 0
+		md2.diagnostic.spcvx=md2.diagnostic.spcvx*ones(1,size(spcx,2));
+		md2.diagnostic.spcvy=md2.diagnostic.spcvy*ones(1,size(spcy,2));
+		md2.diagnostic.spcvz=md2.diagnostic.spcvz*ones(1,size(spcx,2));
+		md2.prognostic.spcthickness=md2.prognostic.spcthickness*ones(1,size(spct,2));
+		md2.diagnostic.spcvx(find(md2.mesh.vertexonboundary),:)=spcx(find(md2.mesh.vertexonboundary),:);
+		md2.diagnostic.spcvy(find(md2.mesh.vertexonboundary),:)=spcy(find(md2.mesh.vertexonboundary),:);
+		md2.diagnostic.spcvz(find(md2.mesh.vertexonboundary),:)=0;
+		md2.prognostic.spcthickness(find(md2.mesh.vertexonboundary),:)=spct(find(md2.mesh.vertexonboundary),:);
+		md2.diagnostic.spcvx=[md2.diagnostic.spcvx; steps];
+		md2.diagnostic.spcvy=[md2.diagnostic.spcvy; steps];
+		md2.diagnostic.spcvz=[md2.diagnostic.spcvz; steps];
+		md2.prognostic.spcthickness=[md2.prognostic.spcthickness; steps];
+	end
+
+	%Diagnostic.  Don't spc the icefront vertices.
+	if ~isnan(md2.diagnostic.icefront)
+		md1s=modelextract(md1,area);
+		%md2.diagnostic.icefront=[md2.mesh.segments 2];
+		e2=md2.mesh.segments(:,end);
+		e1=md1s.mesh.segments(:,end);
+
+		pload = nan*ones(size(md1s.mesh.elements,1),1);
+		pload(md1s.diagnostic.icefront(:,end-1))=md1s.diagnostic.icefront(:,end);
+
+		x2=mean(md2.mesh.x(md2.mesh.elements(e2,:)),2);
+      y2=mean(md2.mesh.y(md2.mesh.elements(e2,:)),2);
+		x1=mean(md1s.mesh.x(md1s.mesh.elements),2);
+      y1=mean(md1s.mesh.y(md1s.mesh.elements),2);
+
+		pload2=griddata(x1,y1,pload,x2,y2,'nearest');
+		md2.diagnostic.icefront=[md2.mesh.segments(~isnan(pload2),:) pload2(~isnan(pload2))];
+		md2.diagnostic.spcvx(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+		md2.diagnostic.spcvy(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+		md2.diagnostic.spcvz(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+		md2.prognostic.spcthickness(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+	end
+
+	%Clear results fields
+	if isstruct(md1.results),
+		md2.results=[];
+	end
+
Index: /issm/trunk/src/m/regional/showbasins.m
===================================================================
--- /issm/trunk/src/m/regional/showbasins.m	(revision 13395)
+++ /issm/trunk/src/m/regional/showbasins.m	(revision 13395)
@@ -0,0 +1,69 @@
+function showbasins(varargin)
+%SHOWBASINS - return basins that are within the xlim and ylim
+%
+%   Usage:
+%      names=showbasins(options);
+%   Options: 
+%      'unit' default 1
+%      'hemisphere': default +1;
+%      'central_meridian: 45 for Greenland and 0 for Antarctica
+%      'standard_parallel: 70 for Greenland and 71 for Antarctica
+%
+
+%is varargin an options database already?
+if nargin==0,
+	options=pairoptions(varargin{:});
+elseif (isa(varargin{1},'plotoptions') | isa(varargin{1},'pairoptions')),
+	%do nothing to the varargin: 
+	options=varargin{1};
+else
+	%process varargin for options: 
+	options=pairoptions(varargin{:});
+end
+
+
+%recover some options, and set defaults
+unitmultiplier=getfieldvalue(options,'unit',1);
+fontsize=getfieldvalue(options,'fontsize',12);
+hemisphere=getfieldvalue(options,'hemisphere');
+
+if strcmpi(hemisphere,'s'),
+	hemisphere=-1;
+elseif strcmpi(hemisphere,'n'),
+	hemisphere=+1;
+else
+	error('showbasins error message: hemispehre should be either ''n'' or ''s''');
+	end
+
+if hemisphere==+1,
+	central_meridian=getfieldvalue(options,'central_meridian',45);
+	standard_parallel=getfieldvalue(options,'standard_parallel',70);
+else
+	central_meridian=getfieldvalue(options,'central_meridian',0);
+	standard_parallel=getfieldvalue(options,'standard_parallel',71);
+end
+
+%Ok, find basin we are talking about: 
+load([jplsvn '/projects/ModelData/Names/Names.mat']);
+
+%Get xlim and ylim, and convert into lat,long: 
+xlimits=xlim; x0=xlimits(1); x1=xlimits(2);
+ylimits=ylim; y0=ylimits(1); y1=ylimits(2);
+
+%Convert names lat and long into x,y:
+lat=cell2mat(names(:,3));
+long=cell2mat(names(:,2));
+
+%Now, convert lat,long into x,y:
+[x,y]=ll2xy(lat,long,hemisphere,central_meridian,standard_parallel);
+
+%Find  x,y within xlimits and ylimits: 
+locations=find(x>x0 & x<x1 & y>y0 & y<y1);
+
+%Go through locations, and display the names: 
+for i=1:size(locations,1),
+	hold on,
+	plot(x(locations(i)),y(locations(i)),'r.');
+	t=text(x(locations(i)),y(locations(i)),names{locations(i),1}); 
+	set(t,'FontSize',fontsize);
+end
Index: /issm/trunk/src/m/solve/MatlabProcessPatch.m
===================================================================
--- /issm/trunk/src/m/solve/MatlabProcessPatch.m	(revision 13395)
+++ /issm/trunk/src/m/solve/MatlabProcessPatch.m	(revision 13395)
@@ -0,0 +1,65 @@
+function structure=MatlabProcessPatch(structure);
+%PROCESSPATCH - create a structure from a patch
+%
+%   Usage:
+%      Result=ProcessPatch(Result);
+
+%return if there is no field Patch
+if (~isfield(structure,'Patch')),
+	return;
+end
+
+%loop over steps
+for i=1:length(structure),
+
+	%Get Patch for current step
+	Patch=structure(i).Patch;
+	numvertices=structure(i).PatchVertices;
+
+	%check that Patch is not empty
+	if length(Patch)==0 continue; end
+
+	%Get number of fields;
+	fields=unique(Patch(:,1));
+	steps=unique(Patch(:,2));
+
+	%parse steps
+	for j=1:length(steps),
+
+		posstep=find(Patch(:,2)==steps(j));
+
+		%Take all the lines of the Patch for this timestep
+		temporarypatch=Patch(posstep,:);
+		time=temporarypatch(1,3);
+		step=temporarypatch(1,2);
+
+		%parse fields
+		for i=1:length(fields),
+
+			%get name
+			fieldname=EnumToString(fields(i));
+
+			%get line positions
+			pos=find(temporarypatch(:,1)==fields(i));
+
+			%Fill Result structure
+			structure(step).steps=step;
+			structure(step).time=time;
+			structure(step).(fieldname).element=temporarypatch(pos,4);
+			structure(step).(fieldname).interpolation=temporarypatch(pos,5);
+			structure(step).(fieldname).index=temporarypatch(pos,6:5+numvertices);
+			if structure(step).(fieldname).interpolation==P1Enum(),
+				structure(step).(fieldname).value=temporarypatch(pos,6+numvertices:end);
+			end
+			if structure(step).(fieldname).interpolation==P0Enum(),
+				structure(step).(fieldname).value=temporarypatch(pos,6+numvertices);
+			end
+
+		end
+	end
+end
+
+%remove fields
+structure=rmfield(structure,'Patch');
+structure=rmfield(structure,'PatchVertices');
+structure=rmfield(structure,'PatchNodes');
Index: /issm/trunk/src/m/solve/MatlabProcessPatch.py
===================================================================
--- /issm/trunk/src/m/solve/MatlabProcessPatch.py	(revision 13395)
+++ /issm/trunk/src/m/solve/MatlabProcessPatch.py	(revision 13395)
@@ -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 'Patch' not in structurei:
+			continue
+
+		raise SystemError("MatlabProcessPatch not implemented in Python.")
+
+	return structure
+
Index: /issm/trunk/src/m/solve/WriteData.m
===================================================================
--- /issm/trunk/src/m/solve/WriteData.m	(revision 13395)
+++ /issm/trunk/src/m/solve/WriteData.m	(revision 13395)
@@ -0,0 +1,260 @@
+function WriteData(fid,varargin)
+%WRITEDATA - write model field in binary file
+%
+%   Usage:
+%      WriteData(fid,varargin);
+
+%process options
+options=pairoptions(varargin{:});
+
+%Get data properties
+if exist(options,'object');
+	%This is a object field, construct enum and data
+	obj       = getfieldvalue(options,'object');
+	fieldname = getfieldvalue(options,'fieldname');
+	classname = getfieldvalue(options,'class',class(obj));
+
+	enum      = BuildEnum([classname '_' fieldname]);
+	data      = obj.(fieldname);
+else
+	%No processing required
+	data = getfieldvalue(options,'data');
+	enum = getfieldvalue(options,'enum');
+end
+format  = getfieldvalue(options,'format');
+mattype = getfieldvalue(options,'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
+fwrite(fid,enum,'int'); 
+
+%Step 2: write the data itself.
+if     strcmpi(format,'Boolean'),% {{{
+	if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
+
+	%first write length of record
+	fwrite(fid,4+4,'int');  %1 bool (disguised as an int)+code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write integer
+	fwrite(fid,data,'int');  %send an int, not easy to send a bool
+	% }}}
+elseif strcmpi(format,'Integer'), % {{{
+	if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
+
+	%first write length of record
+	fwrite(fid,4+4,'int');  %1 integer + code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write integer
+	fwrite(fid,data,'int'); 
+	% }}}
+elseif strcmpi(format,'Double'), % {{{
+	if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
+
+	%first write length of record
+	fwrite(fid,8+4,'int');  %1 double+code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write double
+	fwrite(fid,data,'double'); 
+	% }}}
+elseif strcmpi(format,'String'), % {{{
+	%first write length of record
+	fwrite(fid,length(data)+4+4,'int');  %string + string size + code
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write string
+	fwrite(fid,length(data),'int'); 
+	fwrite(fid,data,'char'); 
+	% }}}
+elseif strcmpi(format,'BooleanMat'), % {{{
+
+	%Get size
+	s=size(data);
+	%if matrix = NaN, then do not write anything
+	if (s(1)==1 & s(2)==1 & isnan(data)),
+		s(1)=0; s(2)=0;
+	end
+
+	%first write length of record
+	fwrite(fid,4+4+8*s(1)*s(2)+4+4,'int');  %2 integers (32 bits) + the double matrix + code + matrix type
+
+	%write data code and matrix type: 
+	fwrite(fid,FormatToCode(format),'int'); 
+	fwrite(fid,mattype,'int');
+
+	%now write matrix
+	fwrite(fid,s(1),'int'); 
+	fwrite(fid,s(2),'int'); 
+	if s(1)*s(2),
+		fwrite(fid,data','double'); %get to the "c" convention, hence the transpose
+	end
+	% }}}
+elseif strcmpi(format,'IntMat'), % {{{
+
+	%Get size
+	s=size(data);
+	%if matrix = NaN, then do not write anything
+	if (s(1)==1 & s(2)==1 & isnan(data)),
+		s(1)=0; s(2)=0;
+	end
+
+	%first write length of record
+	fwrite(fid,4+4+8*s(1)*s(2)+4+4,'int');  %2 integers (32 bits) + the double matrix + code + matrix type
+
+	%write data code and matrix type: 
+	fwrite(fid,FormatToCode(format),'int'); 
+	fwrite(fid,mattype,'int');
+
+	%now write matrix
+	fwrite(fid,s(1),'int'); 
+	fwrite(fid,s(2),'int'); 
+	if s(1)*s(2),
+		fwrite(fid,data','double'); %get to the "c" convention, hence the transpose
+	end
+	% }}}
+elseif strcmpi(format,'DoubleMat'), % {{{
+
+	%Get size
+	s=size(data);
+	%if matrix = NaN, then do not write anything
+	if (s(1)==1 & s(2)==1 & isnan(data)),
+		s(1)=0; s(2)=0;
+	end
+
+	%first write length of record
+	fwrite(fid,4+4+8*s(1)*s(2)+4+4,'int');  %2 integers (32 bits) + the double matrix + code + matrix type
+
+	%write data code and matrix type: 
+	fwrite(fid,FormatToCode(format),'int'); 
+	fwrite(fid,mattype,'int');
+
+	%now write matrix
+	fwrite(fid,s(1),'int'); 
+	fwrite(fid,s(2),'int'); 
+	if s(1)*s(2),
+		fwrite(fid,data','double'); %get to the "c" convention, hence the transpose
+	end
+	% }}}
+elseif strcmpi(format,'MatArray'), % {{{
+
+	numrecords=numel(data);
+
+	%first get length of record
+	recordlength=4+4; %number of records + code
+	for i=1:numrecords,
+		matrix=data{i};
+		s=size(matrix);
+		recordlength=recordlength+4*2+... %row and col of matrix
+			s(1)*s(2)*8; %matrix of doubles
+	end
+
+	%write length of record
+	fwrite(fid,recordlength,'int'); 
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%write data, first number of records
+	fwrite(fid,numrecords,'int'); 
+
+	%write each matrix: 
+	for i=1:numrecords,
+		matrix=data{i};
+		s=size(matrix);
+		fwrite(fid,s(1),'int'); 
+		fwrite(fid,s(2),'int'); 
+		fwrite(fid,matrix','double');
+	end
+	% }}}
+elseif strcmpi(format,'StringArray'), % {{{
+
+	%first get length of string array: 
+	num=numel(data);
+	%now get length of record: 
+	recordlength=4+4; %for length of array + code
+	for i=1:num,
+		string=data{i};
+		recordlength=recordlength+4+length(string); %for each string
+	end
+
+	%write length of record
+	fwrite(fid,recordlength,'int'); 
+
+	%write data code: 
+	fwrite(fid,FormatToCode(format),'int'); 
+
+	%now write length of string array
+	fwrite(fid,num,'int'); 
+
+	%now write the strings
+	for i=1:num,
+		string=data{i};
+		fwrite(fid,length(string),'int'); 
+		fwrite(fid,string,'char'); 
+	end
+	% }}}
+else  % {{{
+	error(['WriteData error message: data type: ' num2str(format) ' not supported yet! (' EnumToString(enum) ')']);
+end % }}}
+end
+
+function enum=BuildEnum(string) % {{{
+%BUILDENUM - build enum out of string
+%
+%   Usage:
+%      enum=BuildEnum(string)
+
+	if findstr(string,'_'),
+		indices=findstr(string,'_');
+		for i=1:length(indices),
+			string(indices(i)+1)=upper(string(indices(i)+1));
+		end
+		string(indices)=[];
+	end
+
+	%take first letter of string and make it uppercase: 
+	string(1)=upper(string(1));
+
+	%Get Enum
+	enum=eval([string 'Enum();']); 
+end % }}}
+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 
+%sent.
+	if     strcmpi(format,'Boolean'),
+		code=1;
+	elseif strcmpi(format,'Integer'), 
+		code=2;
+	elseif strcmpi(format,'Double'), 
+		code=3;
+	elseif strcmpi(format,'String'), 
+		code=4;
+	elseif strcmpi(format,'BooleanMat'),
+		code=5;
+	elseif strcmpi(format,'IntMat'),
+		code=6;
+	elseif strcmpi(format,'DoubleMat'),
+		code=7;
+	elseif strcmpi(format,'MatArray'), 
+		code=8;
+	elseif strcmpi(format,'StringArray'),
+		code=9;
+	else 
+		error('FormatToCode error message: data type not supported yet!');
+	end
+end% }}}
Index: /issm/trunk/src/m/solve/WriteData.py
===================================================================
--- /issm/trunk/src/m/solve/WriteData.py	(revision 13395)
+++ /issm/trunk/src/m/solve/WriteData.py	(revision 13395)
@@ -0,0 +1,313 @@
+import numpy
+import math
+import struct
+from pairoptions import *
+from MatlabFuncs import *
+from EnumDefinitions import *
+from EnumToString import EnumToString
+
+def WriteData(fid,*args):
+	"""
+	WRITEDATA - write model field in binary file
+ 
+	   Usage:
+	      WriteData(fid,varargin)
+	"""
+
+	#process options
+	#  the import above the function level doesn't work?
+	from pairoptions import *
+	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 = options.getfieldvalue('class',str(type(obj)).rsplit('.')[-1].split("'")[0])
+
+		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)[0])
+
+		#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',int(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)[0])
+
+		#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)[0])
+
+		#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'):    # {{{
+
+		if isinstance(data,bool):
+			data=numpy.array([data])
+		if len(data.shape) == 1:
+			if numpy.size(data):
+				data=data.reshape(numpy.size(data),1)
+			else:
+				data=data.reshape(0,0)
+
+		#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)
+
+		#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',float(data[i][j])))    #get to the "c" convention, hence the transpose
+		# }}}
+
+	elif strcmpi(format,'IntMat'):    # {{{
+
+		if isinstance(data,(int,long)):
+			data=numpy.array([data])
+		if len(data.shape) == 1:
+			if numpy.size(data):
+				data=data.reshape(numpy.size(data),1)
+			else:
+				data=data.reshape(0,0)
+
+		#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)
+
+		#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',float(data[i][j])))    #get to the "c" convention, hence the transpose
+		# }}}
+
+	elif strcmpi(format,'DoubleMat'):    # {{{
+
+		if isinstance(data,(bool,int,long,float)):
+			data=numpy.array([data])
+		if len(data.shape) == 1:
+			if numpy.size(data):
+				data=data.reshape(numpy.size(data),1)
+			else:
+				data=data.reshape(0,0)
+
+		#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)
+
+		#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',float(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:
+			if isinstance(matrix,(bool,int,long,float)):
+				matrix=numpy.array([matrix])
+			if len(matrix.shape) == 1:
+				if numpy.size(matrix):
+					matrix=matrix.reshape(numpy.size(matrix),1)
+				else:
+					matrix=matrix.reshape(0,0)
+
+			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:
+			if isinstance(matrix,(bool,int,long,float)):
+				matrix=numpy.array([matrix])
+			if len(matrix.shape) == 1:
+				matrix=matrix.reshape(numpy.size(matrix),1)
+
+			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',float(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)[0]))
+	# }}}
+
+def BuildEnum(string): # {{{
+	"""
+	BUILDENUM - build enum out of string
+ 
+    Usage:
+       enum=BuildEnum(string)
+	"""
+
+	if '_' in string:
+		substrs=string.split('_')
+		string=''
+		for substr in substrs:
+			string+=substr[0].upper()+substr[1:]
+	else:
+		#take first letter of string and make it uppercase: 
+		string=string[0].upper()+string[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/trunk/src/m/solve/loadmultipleresultsfromcluster.m
===================================================================
--- /issm/trunk/src/m/solve/loadmultipleresultsfromcluster.m	(revision 13395)
+++ /issm/trunk/src/m/solve/loadmultipleresultsfromcluster.m	(revision 13395)
@@ -0,0 +1,34 @@
+function md_list=loadmultipleresultsfromcluster(md_list)
+%LOADMULTIPLERESULTSFROMCLUSTER - load multiple results of solution sequences from cluster
+%
+%   Usage:
+%      md_list=loadresultsfromcluster(md_list);
+
+nummodels=length(md_list);
+
+%Get cluster settings
+cluster=md_list{1}.cluster;
+name=md_list{1}.name;
+cluster_rc_location=which('cluster.rc');
+[codepath,executionpath,login]=ClusterParameters(cluster,cluster_rc_location);
+
+%Remote tar: 
+disp('tarring results');
+issmssh(cluster,['"cd ' executionpath ' && rm -rf file_list.txt ModelResults.tar.gz && find -iname ''*_*vs*.outbin'' > file_list.txt && tar zcvf ModelResults.tar.gz --files-from file_list.txt  && rm -rf file_list.txt "']);
+
+%copy results from cluster to present directory
+scpin(cluster, executionpath, {'ModelResults.tar.gz'});
+
+%untar:
+!tar -zxvf ModelResults.tar.gz
+
+%ok, go through list and load results from disk: 
+for i=1:nummodels,
+	%load  results for this model
+	md_list{i}=loadresultsfromdisk(md_list{i},[md_list{i}.name '.outbin']);
+
+	delete([name '.outbin']);
+end
+
+%erase files 
+delete('ModelResults.tar.gz');
Index: /issm/trunk/src/m/solve/loadresultsfromcluster.m
===================================================================
--- /issm/trunk/src/m/solve/loadresultsfromcluster.m	(revision 13395)
+++ /issm/trunk/src/m/solve/loadresultsfromcluster.m	(revision 13395)
@@ -0,0 +1,60 @@
+function md=loadresultsfromcluster(md,runtimename)
+%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 nargin==2,
+	md.private.runtimename=runtimename;
+end
+
+%Download outputs from the cluster
+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
+	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.
+md=loadresultsfromdisk(md,[md.miscellaneous.name '.outbin']);
+
+%erase the log and output files
+if md.qmu.isdakota,
+	delete([['qmu' num2str(feature('GetPid')) '/'] md.miscellaneous.name '.outlog']);
+	delete([['qmu' num2str(feature('GetPid')) '/']  md.miscellaneous.name '.errlog']);
+else
+	delete([md.miscellaneous.name '.outlog']);
+	delete([md.miscellaneous.name '.errlog']);
+	delete([md.miscellaneous.name '.outbin']);
+	if ~ispc(),
+		delete([md.private.runtimename '.tar.gz']);
+	end
+end
+
+%erase input file if run was carried out on same platform.
+hostname=oshostname();
+if strcmpi(hostname,cluster.name),
+	if md.qmu.isdakota,
+		delete([['qmu' num2str(feature('GetPid')) '/'] md.miscellaneous.name '.bin']);
+		delete([['qmu' num2str(feature('GetPid')) '/'] md.miscellaneous.name '.queue']);
+	else
+		delete([md.miscellaneous.name '.bin']);
+		delete([md.miscellaneous.name '.petsc']);
+		if ~ispc(),
+			delete([md.miscellaneous.name '.queue']);
+		else
+			delete([md.miscellaneous.name '.bat']);
+		end
+	end
+end
Index: /issm/trunk/src/m/solve/loadresultsfromcluster.py
===================================================================
--- /issm/trunk/src/m/solve/loadresultsfromcluster.py	(revision 13395)
+++ /issm/trunk/src/m/solve/loadresultsfromcluster.py	(revision 13395)
@@ -0,0 +1,61 @@
+import os
+import socket
+from MatlabFuncs import *
+from loadresultsfromdisk 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
+
+	#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')
+	else:
+		filelist.append(md.miscellaneous.name+'.outbin')
+	cluster.Download(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 ispc():
+			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 ispc():
+				os.remove(md.miscellaneous.name+'.queue')
+			else:
+				os.remove(md.miscellaneous.name+'.bat')
+
+	return md
+
Index: /issm/trunk/src/m/solve/loadresultsfromdisk.m
===================================================================
--- /issm/trunk/src/m/solve/loadresultsfromdisk.m	(revision 13395)
+++ /issm/trunk/src/m/solve/loadresultsfromdisk.m	(revision 13395)
@@ -0,0 +1,61 @@
+function md=loadresultsfromdisk(md,filename)
+%LOADRESULTSFROMDISK - load results of solution sequence from disk file "filename"            
+%
+%   Usage:
+%      md=loadresultsfromdisk(md,filename);
+
+%check number of inputs/outputs
+if ((nargin~=2) | (nargout~=1)),
+	help loadresultsfromdisk;
+	error('loadresultsfromdisk: error message.');
+end
+
+if ~md.qmu.isdakota,
+
+	%Check that file exists
+	if ~exist(filename,'file'),
+		error(['binary file ' filename ' not found.']);
+	end
+
+	%initialize md.results if not a structure yet
+	if ~isstruct(md.results),
+		md.results=struct();
+	end
+
+	%load results onto model
+	structure=parseresultsfromdisk(filename,~md.settings.io_gather);
+	if isempty(fieldnames(structure)),
+		error(['No result found in binary file ' filename '. Check for solution crash.']);
+	end
+	md.results.(structure(1).SolutionType)=structure;
+
+	%recover solution_type from results
+	md.private.solution=structure(1).SolutionType;
+
+	%read log files onto  fields
+	if exist([md.miscellaneous.name '.errlog'],'file'),
+		md.results.(structure(1).SolutionType)(1).errlog=char(textread([md.miscellaneous.name '.errlog'],'%s','delimiter','\n'));
+	else
+		md.results.(structure(1).SolutionType)(1).errlog='';
+	end
+
+	if exist([md.miscellaneous.name '.outlog'],'file'),
+		md.results.(structure(1).SolutionType)(1).outlog=char(textread([md.miscellaneous.name '.outlog'],'%s','delimiter','\n'));
+	else
+		md.results.(structure(1).SolutionType)(1).outlog='';
+	end
+
+	if ~isempty(md.results.(structure(1).SolutionType)(1).errlog),
+		disp(['loadresultsfromcluster info message: error during solution. Check your errlog and outlog model fields']);
+	end
+
+
+%post processes qmu results if necessary
+else
+
+	if isscalar(md.private.solution),
+		md.private.solution=EnumToString(md.private.solution);
+	end
+	md=postqmu(md);
+	cd ..
+end
Index: /issm/trunk/src/m/solve/loadresultsfromdisk.py
===================================================================
--- /issm/trunk/src/m/solve/loadresultsfromdisk.py	(revision 13395)
+++ /issm/trunk/src/m/solve/loadresultsfromdisk.py	(revision 13395)
@@ -0,0 +1,62 @@
+import os
+from collections import OrderedDict
+from parseresultsfromdisk import *
+from EnumToString import EnumToString
+
+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 OSError("binary file '%s' not found." % filename)
+
+		#initialize md.results if not a structure yet
+		if not isinstance(md.results,dict):
+			md.results=OrderedDict()
+
+		#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)
+		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,unicode)):
+			[md.private.solution]=EnumToString(md.private.solution)
+		md=postqmu(md)
+		os.chdir('..')
+
+	return md
+
Index: /issm/trunk/src/m/solve/marshall.m
===================================================================
--- /issm/trunk/src/m/solve/marshall.m	(revision 13395)
+++ /issm/trunk/src/m/solve/marshall.m	(revision 13395)
@@ -0,0 +1,49 @@
+function 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)
+
+disp(['marshalling file ' md.miscellaneous.name '.bin']);
+
+%open file for binary writing
+fid=fopen([ md.miscellaneous.name '.bin'],'wb');
+if fid==-1,
+	error(['marshall error message: could not open ' [md.miscellaneous.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');
+
+%Go through all model fields: check that it is a class and call checkconsistency
+fields=properties('model');
+for i=1:length(fields),
+	field=fields{i};
+
+	%Some properties do not need to be marshalled
+	if ismember(field,{'results' 'radaroverlay' 'solver' 'cluster'  'flaim' 'private'}),
+		continue;
+	end
+
+	%Check that current field is an object
+	if ~isobject(md.(field))
+		error(['field ''' char(field) ''' is not an object']);
+	end
+
+	%Marshall current object
+	%disp(['marshalling ' field '...']);
+	if verLessThan('matlab', '7.6')
+		marshall(md.(field),fid);
+	else
+		md.(field).marshall(fid);
+	end
+end
+
+%close file
+st=fclose(fid);
+if st==-1,
+	error(['marshall error message: could not close file ' [md.miscellaneous.name '.bin']]);
+end
Index: /issm/trunk/src/m/solve/marshall.py
===================================================================
--- /issm/trunk/src/m/solve/marshall.py	(revision 13395)
+++ /issm/trunk/src/m/solve/marshall.py	(revision 13395)
@@ -0,0 +1,49 @@
+from WriteData import *
+from EnumDefinitions 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.iterkeys():
+	for field in md.properties():
+
+		#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:
+		fid.close()
+	except IOError as e:
+		raise IOError("marshall error message: could not close file '%s.bin'." % md.miscellaneous.name)
+
Index: /issm/trunk/src/m/solve/parseresultsfromdisk.m
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 13395)
+++ /issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 13395)
@@ -0,0 +1,212 @@
+function results=parseresultsfromdisk(filename,iosplit)
+%PARSERESULTSFROMDISK - ...
+%
+%   Usage:
+%      results=parseresultsfromdisk(filename,iosplit)
+
+if iosplit,
+	results=parseresultsfromdiskiosplit(filename);
+else
+	results=parseresultsfromdiskioserial(filename);
+end
+
+%process patch if necessary
+results=MatlabProcessPatch(results);
+
+function results=parseresultsfromdiskioserial(filename) % {{{
+%PARSERESULTSFROMDISK - ...
+%
+%   Usage:
+%      results=parseresultsfromdiskioserial(filename)
+
+
+%Open file
+fid=fopen(filename,'rb');
+if(fid==-1),
+	error(['loadresultsfromdisk error message: could not open ',filename,' for binary reading']);
+end
+results=struct();
+
+%Read fields until the end of the file.
+result=ReadData(fid);
+while ~isempty(result), 
+	%Get time and step
+	results(result.step).step=result.step;
+	results(result.step).time=result.time; 
+
+	%Add result
+	if (length(results)>=result.step & isfield(results,result.fieldname) & ~strcmp(result.fieldname,'SolutionType')),
+			results(result.step).(result.fieldname)=[ results(result.step).(result.fieldname); result.field];
+	else
+		results(result.step).(result.fieldname)=result.field;
+	end
+
+	%read next result
+	result=ReadData(fid);
+
+end
+
+fclose(fid);
+% }}}
+function results=parseresultsfromdiskiosplit(filename) % {{{
+%PARSERESULTSFROMDISKIOSPLIT - ...
+%
+%   Usage:
+%      results=parseresultsfromdiskiosplit(filename)
+
+
+%Open file
+fid=fopen(filename,'rb');
+if(fid==-1),
+	error(['loadresultsfromdisk error message: could not open ',filename,' for binary reading']);
+end
+results=struct();
+
+%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 ~isempty(result),
+
+	%Get time and 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)=NaN;
+	end
+
+	%read next result
+	result=ReadDataDimensions(fid);
+end
+
+%do a second pass, and figure out the size of the patches
+fseek(fid,0,-1); %rewind
+result=ReadDataDimensions(fid);
+while ~isempty(result),
+
+	%Add result
+	if strcmpi(result.fieldname,'Patch'),
+		patchdimensions=results(result.step).(result.fieldname);
+		results(result.step).(result.fieldname)=[patchdimensions(1)+result.M result.N];
+	end
+
+	%read next result
+	result=ReadDataDimensions(fid);
+end
+
+%allocate patches
+for i=1:length(results),
+	results(i).Patch=zeros(results(i).Patch(1),results(i).Patch(2));
+	results(i).counter=1; %use to index into the patch
+end
+
+%third pass, this time to read the real information
+fseek(fid,0,-1); %rewind
+result=ReadData(fid);
+while ~isempty(result),
+
+	%Get time and 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+size(result.field,1)-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;
+	end
+
+	%read next result
+	result=ReadData(fid);
+
+end
+
+%close file
+fclose(fid);
+	% }}}
+function result=ReadData(fid) % {{{
+%READDATA - ...
+%
+%   Usage:
+%      field=ReadData(fid)
+
+%read field
+[length,count]=fread(fid,1,'int');
+
+if count==0,
+	result=struct([]);
+else
+	fieldname=fread(fid,length,'char');
+	fieldname=fieldname(1:end-1)';
+	fieldname=char(fieldname);
+	time=fread(fid,1,'double');
+	step=fread(fid,1,'int');
+
+	type=fread(fid,1,'int');
+	M=fread(fid,1,'int');
+	if type==1,
+		field=fread(fid,M,'double');
+	elseif type==2,
+		field=fread(fid,M,'char');
+		field=char(field(1:end-1)');
+	elseif type==3,
+		N=fread(fid,1,'int');
+		field=transpose(fread(fid,[N M],'double'));
+	else
+		error(['cannot read data of type ' num2str(type) ]);
+	end
+
+	result.fieldname=fieldname;
+	result.time=time;
+	result.step=step;
+	result.field=field;
+end
+% }}}
+function result=ReadDataDimensions(fid) % {{{
+%READDATADIMENSIONS - read data dimensions, step and time, but not the data itself.
+%
+%   Usage:
+%      field=ReadDataDimensions(fid)
+
+
+%read field
+[length,count]=fread(fid,1,'int');
+
+if count==0,
+	result=struct([]);
+else
+	fieldname=fread(fid,length,'char');
+	fieldname=fieldname(1:end-1)';
+	fieldname=char(fieldname);
+	time=fread(fid,1,'double');
+	step=fread(fid,1,'int');
+
+	type=fread(fid,1,'int');
+	M=fread(fid,1,'int');
+	N=1; %default
+	if type==1,
+		fseek(fid,M*8,0);
+	elseif type==2,
+		fseek(fid,M,0);
+	elseif type==3,
+		N=fread(fid,1,'int');
+		fseek(fid,N*M*8,0);
+	else
+		error(['cannot read data of type ' num2str(type) ]);
+	end
+
+	result.fieldname=fieldname;
+	result.time=time;
+	result.step=step;
+	result.M=M;
+	result.N=N;
+end
+% }}}
Index: /issm/trunk/src/m/solve/parseresultsfromdisk.py
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 13395)
+++ /issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 13395)
@@ -0,0 +1,236 @@
+import struct
+import numpy
+from collections import OrderedDict
+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=OrderedDict()
+
+	#Read fields until the end of the file.
+	result=ReadData(fid)
+	while result:
+		#Get time and step
+		if result['step'] not in results:
+			results[result['step']]=OrderedDict()
+			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=OrderedDict()
+
+	#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 result['step'] not in results:
+			results[result['step']]=OrderedDict()
+			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 result['step'] not in results:
+			results[result['step']]=OrderedDict()
+			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=OrderedDict()
+		result['fieldname']=fieldname
+		result['time']=time
+		result['step']=step
+		result['field']=field
+
+	except struct.error as e:
+		result=OrderedDict()
+
+	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=OrderedDict()
+		result['fieldname']=fieldname
+		result['time']=time
+		result['step']=step
+		result['M']=M
+		result['N']=N
+
+	except struct.error as e:
+		result=OrderedDict()
+
+	return result
+	# }}}
+
Index: /issm/trunk/src/m/solve/process_solve_options.m
===================================================================
--- /issm/trunk/src/m/solve/process_solve_options.m	(revision 13395)
+++ /issm/trunk/src/m/solve/process_solve_options.m	(revision 13395)
@@ -0,0 +1,39 @@
+function outoptions=process_solve_options(options)
+%DEFAULT_SOLVE_OPTIONS - set up default options for solve phase
+%
+%   Usage:
+%      options=process_solve_options(options)
+%
+%   See also: SOLVE
+
+%solution_type: check on this option, error out otherwise
+solution_type=getfieldvalue(options,'solution_type');
+if ~ismember(solution_type,[DiagnosticSolutionEnum(),PrognosticSolutionEnum(),ThermalSolutionEnum(),...
+		SteadystateSolutionEnum(),TransientSolutionEnum(),EnthalpySolutionEnum(),...
+		BalancethicknessSolutionEnum(),BedSlopeSolutionEnum(),SurfaceSlopeSolutionEnum(),HydrologySolutionEnum(),FlaimSolutionEnum()]),
+	error(['process_solve_options error message: solution_type ' EnumToString(solution_type) ' not supported yet!']);
+end
+outoptions.solution_type=solution_type;
+
+outoptions.upload=getfieldvalue(options,'upload','off');
+outoptions.batch=getfieldvalue(options,'batch','no');
+outoptions.loadonly=getfieldvalue(options,'loadonly',false);
+outoptions.directory=getfieldvalue(options,'directory','');
+
+%  process qmu arguments
+outoptions.qmudir=getfieldvalue(options,'qmudir',['qmu' num2str(feature('GetPid'))]);  % qmudir =['qmu_' datestr(now,'yyyymmdd_HHMMSS')];
+outoptions.qmufile=getfieldvalue(options,'qmufile','qmu');% qmufile cannot be changed unless ????script.sh is also changed
+outoptions.overwrite=getfieldvalue(options,'overwrite','n');
+outoptions.keep=getfieldvalue(options,'keep','n');
+outoptions.ivar=getfieldvalue(options,'ivar',1);
+outoptions.iresp=getfieldvalue(options,'iresp',1);
+outoptions.imethod=getfieldvalue(options,'imethod',1);
+outoptions.iparams=getfieldvalue(options,'iparams',1);
+outoptions.runmpi=getfieldvalue(options,'runmpi',false);
+
+%  process flaim arguments
+outoptions.fmdir=getfieldvalue(options,'fmdir',['fm' num2str(feature('GetPid'))]);
+outoptions.overwrite=getfieldvalue(options,'overwrite','n');
+outoptions.keep=getfieldvalue(options,'keep','y');
+outoptions.latsgn=getfieldvalue(options,'latsgn',0);
+outoptions.cmap=getfieldvalue(options,'cmap',[]);
Index: /issm/trunk/src/m/solve/process_solve_options.py
===================================================================
--- /issm/trunk/src/m/solve/process_solve_options.py	(revision 13395)
+++ /issm/trunk/src/m/solve/process_solve_options.py	(revision 13395)
@@ -0,0 +1,50 @@
+import os
+from collections import OrderedDict
+from EnumDefinitions import *
+from EnumToString import EnumToString
+
+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=OrderedDict()
+
+	#solution_type: check on this option, error out otherwise
+	solution_type=options.getfieldvalue('solution_type')
+	if solution_type not 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)[0])
+	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',[])
+
+	return outoptions
+
Index: /issm/trunk/src/m/solve/solve.m
===================================================================
--- /issm/trunk/src/m/solve/solve.m	(revision 13395)
+++ /issm/trunk/src/m/solve/solve.m	(revision 13395)
@@ -0,0 +1,121 @@
+function md=solve(md,solutionenum,varargin)
+%SOLVE - apply solution sequence for this model
+%
+%   Usage:
+%      md=solve(md,solutionenum,varargin)
+%      where varargin is a lit 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(varargin{:},'solution_type',solutionenum);
+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())
+	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
+	ismodelselfconsistent(md),
+end
+
+%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
+
+%flaim analysis
+if (options.solution_type == FlaimSolutionEnum())
+	md=flaim_sol(md,options);
+	md.private.solution=EnumToString(options.solution_type);
+	return;
+end
+
+%Do we load results only?
+if options.loadonly,  
+	md=loadresultsfromcluster(md);
+	return;
+end
+
+%we need to make sure we have PETSC support, otherwise, we run with only one cpu: 
+if ~ispetsc(),
+	disp('PETSc support not included, running on 1 cpu only!');
+	cluster.np=1;
+end
+
+
+%Write all input files
+marshall(md);                                          % bin file
+PetscFile(md.solver,[md.miscellaneous.name '.petsc']); % petsc file
+BuildQueueScript(cluster,md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof); % queue file
+
+
+%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,
+	if ~strncmpi(options.keep,'y',1)
+		system(['rm -rf qmu' num2str(feature('GetPid'))]);
+	end
+end
Index: /issm/trunk/src/m/solve/solve.py
===================================================================
--- /issm/trunk/src/m/solve/solve.py	(revision 13395)
+++ /issm/trunk/src/m/solve/solve.py	(revision 13395)
@@ -0,0 +1,124 @@
+import datetime
+import os
+import shutil
+from pairoptions import *
+from process_solve_options import *
+from EnumDefinitions import *
+from EnumToString import EnumToString
+from ismodelselfconsistent import *
+from marshall import *
+from ispetsc import *
+from waitonlock import *
+from loadresultsfromcluster import *
+
+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
+
+	#Write all input files
+	marshall(md)                                           # bin file
+	md.solver.PetscFile(md.miscellaneous.name+'.petsc')    # petsc file
+	cluster.BuildQueueScript(md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof)    # queue file
+
+	#we need to make sure we have PETSC support, otherwise, we run with only one cpu: 
+	if not ispetsc():
+		print "PETSC support not included, running on 1 cpu only!"
+		cluster.np=1
+
+	#Stop here if batch mode
+	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: /issm/trunk/src/m/solve/waitonlock.m
===================================================================
--- /issm/trunk/src/m/solve/waitonlock.m	(revision 13395)
+++ /issm/trunk/src/m/solve/waitonlock.m	(revision 13395)
@@ -0,0 +1,58 @@
+function flag=waitonlock(md)
+%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)
+
+%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=[executionpath '/' md.private.runtimename '/' md.miscellaneous.name '.lock'];
+
+%waitonlock will work if the lock is on the same machine only: 
+if ~strcmpi(oshostname(),cluster),
+
+	disp('solution launched on remote cluster. log in to detect job completion.');
+	choice=input('Is the job successfully completed? (y/n)','s');
+	if ~strcmp(choice,'y'), 
+		disp('Results not loaded... exiting'); 
+		flag=0;
+	else
+		flag=1;
+	end
+
+%job is running on the same machine
+else
+
+	if ismember('interactive',properties(md.cluster)) & md.cluster.interactive
+		%We are in interactive mode, no need to check for job completion
+		flag=1;
+		return;
+	end
+	%initialize time and file presence test flag
+	time=0; ispresent=0;
+	disp(['waiting for ' filename ' hold on... (Ctrl+C to exit)'])
+
+	%loop till file .lock exist or time is up
+	while (ispresent==0 & time<timelimit)
+		ispresent=exist(filename,'file');
+		pause(1);
+		time=time+1/60;
+	end
+
+	%build output
+	if (time>timelimit),
+		disp('Time limit exceeded. Increase md.settings.waitonlock');
+		disp('The results must be loaded manually with md=loadresultsfromcluster(md).');
+		error(['waitonlock error message: time limit exceeded']);
+		flag=0;
+	else
+		flag=1;
+	end
+end
Index: /issm/trunk/src/m/solve/waitonlock.py
===================================================================
--- /issm/trunk/src/m/solve/waitonlock.py	(revision 13395)
+++ /issm/trunk/src/m/solve/waitonlock.py	(revision 13395)
@@ -0,0 +1,64 @@
+import os
+import socket
+import time
+from MatlabFuncs import *
+
+def waitonlock(md):
+	"""
+	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)
+	"""
+
+	#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/trunk/src/m/solvers/asmoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/asmoptions.m	(revision 13395)
+++ /issm/trunk/src/m/solvers/asmoptions.m	(revision 13395)
@@ -0,0 +1,18 @@
+function asm=asmoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method petsc options
+%
+%   Usage:
+%      options=asmoptions;
+			 
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+asm=struct();
+
+%default asm options
+asm.mat_type=getfieldvalue(options,'mat_type','aij');
+asm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+asm.pc_type=getfieldvalue(options,'pc_type','asm');
+asm.sub_pc_type=getfieldvalue(options,'sub_pc_type','lu');
+asm.pc_asm_overlap=getfieldvalue(options,'pc_asm_overlap',3);
+asm.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
+asm.ksp_rtol=getfieldvalue(options,'ksp_rtol',1e-30);
Index: /issm/trunk/src/m/solvers/asmoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/asmoptions.py	(revision 13395)
+++ /issm/trunk/src/m/solvers/asmoptions.py	(revision 13395)
@@ -0,0 +1,31 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def asmoptions(*args):
+	#ASMOPTIONS - return ASM petsc options
+	#
+	#   Usage:
+	#      options=asmoptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','lu'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-30]];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/trunk/src/m/solvers/iluasmoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/iluasmoptions.m	(revision 13395)
+++ /issm/trunk/src/m/solvers/iluasmoptions.m	(revision 13395)
@@ -0,0 +1,18 @@
+function iluasm=iluasmoptions(varargin)
+%ILUASMOPTIONS - 
+%
+%   Usage:
+%      options=iluasmoptions;
+			 
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+iluasm=struct();
+
+%default iluasm options
+iluasm.mat_type=getfieldvalue(options,'mat_type','aij');
+iluasm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+iluasm.pc_type=getfieldvalue(options,'pc_type','asm');
+iluasm.sub_pc_type=getfieldvalue(options,'sub_pc_type','ilu');
+iluasm.pc_asm_overlap=getfieldvalue(options,'pc_asm_overlap',5);
+iluasm.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
+iluasm.ksp_rtol=getfieldvalue(options,'ksp_rtol',1e-15);
Index: /issm/trunk/src/m/solvers/iluasmoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/iluasmoptions.py	(revision 13395)
+++ /issm/trunk/src/m/solvers/iluasmoptions.py	(revision 13395)
@@ -0,0 +1,26 @@
+from collections import OrderedDict
+from pairoptions import *
+
+def iluasmoptions(*args):
+	"""
+	ILUASMOPTIONS - 
+
+	   Usage:
+	      options=iluasmoptions;
+	"""
+			 
+	#retrieve options provided in varargin
+	options=pairoptions(*args)
+	iluasm=OrderedDict()
+
+	#default iluasm options
+	iluasm['mat_type']=options.getfieldvalue('mat_type','aij')
+	iluasm['ksp_type']=options.getfieldvalue('ksp_type','gmres')
+	iluasm['pc_type']=options.getfieldvalue('pc_type','asm')
+	iluasm['sub_pc_type']=options.getfieldvalue('sub_pc_type','ilu')
+	iluasm['pc_asm_overlap']=options.getfieldvalue('pc_asm_overlap',5)
+	iluasm['ksp_max_it']=options.getfieldvalue('ksp_max_it',100)
+	iluasm['ksp_rtol']=options.getfieldvalue('ksp_rtol',1e-15)
+
+	return iluasm
+
Index: /issm/trunk/src/m/solvers/jacobiasmoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/jacobiasmoptions.m	(revision 13395)
+++ /issm/trunk/src/m/solvers/jacobiasmoptions.m	(revision 13395)
@@ -0,0 +1,18 @@
+function jacobiasm=jacobiasmoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+%
+%   Usage:
+%      options=jacobiasmoptions;
+			 
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+jacobiasm=struct();
+
+%default jacobiasm options
+jacobiasm.mat_type=getfieldvalue(options,'mat_type','aij');
+jacobiasm.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+jacobiasm.pc_type=getfieldvalue(options,'pc_type','asm');
+jacobiasm.sub_pc_type=getfieldvalue(options,'sub_pc_type','jacobi');
+jacobiasm.pc_asm_overlap=getfieldvalue(options,'pc_asm_overlap',3);
+jacobiasm.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
+jacobiasm.ksp_rtol=getfieldvalue(options,'ksp_rtol',1e-15);
Index: /issm/trunk/src/m/solvers/jacobiasmoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/jacobiasmoptions.py	(revision 13395)
+++ /issm/trunk/src/m/solvers/jacobiasmoptions.py	(revision 13395)
@@ -0,0 +1,31 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def jacobiasmoptions(*args):
+	#ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+	#
+	#   Usage:
+	#      options=jacobiasmoptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','jacobi'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-15]];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/trunk/src/m/solvers/jacobicgoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/jacobicgoptions.m	(revision 13395)
+++ /issm/trunk/src/m/solvers/jacobicgoptions.m	(revision 13395)
@@ -0,0 +1,15 @@
+function jacobicg=jacobiacgoptions(varargin)
+%ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+%
+%   Usage:
+%      options=jacobiasmoptions;
+			 
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+jacobicg=struct();
+
+%default jacobiasm options
+jacobicg.mat_type=getfieldvalue(options,'mat_type','aij');
+jacobicg.ksp_type=getfieldvalue(options,'ksp_type','cg');
+jacobicg.ksp_max_it=getfieldvalue(options,'ksp_max_it',100);
+jacobicg.ksp_rtol=getfieldvalue(options,'ksp_rtol',1e-15);
Index: /issm/trunk/src/m/solvers/jacobicgoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/jacobicgoptions.py	(revision 13395)
+++ /issm/trunk/src/m/solvers/jacobicgoptions.py	(revision 13395)
@@ -0,0 +1,31 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def jacobicgoptions(*args):
+	#ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
+	#
+	#   Usage:
+	#      options=jacobicgoptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['mat_type','aij'],['ksp_type','cg'],['ksp_max_it',100],['ksp_rtol',1e-15]];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/trunk/src/m/solvers/matlaboptions.m
===================================================================
--- /issm/trunk/src/m/solvers/matlaboptions.m	(revision 13395)
+++ /issm/trunk/src/m/solvers/matlaboptions.m	(revision 13395)
@@ -0,0 +1,12 @@
+function maltab=matlaboptions(varargin)
+%MATLABOPTIONS - return Matlab petsc options
+%
+%   Usage:
+%      options=matlaboptions;
+			 
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+maltab=struct();
+
+%default matlab options
+maltab.ksp_type='matlab';
Index: /issm/trunk/src/m/solvers/matlaboptions.py
===================================================================
--- /issm/trunk/src/m/solvers/matlaboptions.py	(revision 13395)
+++ /issm/trunk/src/m/solvers/matlaboptions.py	(revision 13395)
@@ -0,0 +1,31 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def matlaboptions(*args):
+	#MATLABOPTIONS - return Matlab petsc options
+	#
+	#   Usage:
+	#      options=matlaboptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['ksp_type','matlab']];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/trunk/src/m/solvers/mumpsoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/mumpsoptions.m	(revision 13395)
+++ /issm/trunk/src/m/solvers/mumpsoptions.m	(revision 13395)
@@ -0,0 +1,27 @@
+function mumps=mumpsoptions(varargin)
+%MUMPSOPTIONS - return MUMPS direct solver  petsc options
+%
+%   Usage:
+%      options=mumpsoptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+mumps=struct();
+
+%default mumps options
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==2,
+	mumps.mat_type=getfieldvalue(options,'mat_type','aijmumps');
+	mumps.ksp_type=getfieldvalue(options,'ksp_type','preonly');
+	mumps.pc_type=getfieldvalue(options,'pc_type','lu');
+	mumps.mat_mumps_icntl_14=getfieldvalue(options,'mat_mumps_icntl_14',120);
+	mumps.pc_factor_shift_positive_definite=getfieldvalue(options,'pc_factor_shift_positive_definite','true');
+end
+if PETSC_VERSION==3,
+	mumps.mat_type=getfieldvalue(options,'mat_type','mpiaij');
+	mumps.ksp_type=getfieldvalue(options,'ksp_type','preonly');
+	mumps.pc_type=getfieldvalue(options,'pc_type','lu');
+	mumps.pc_factor_mat_solver_package=getfieldvalue(options,'pc_factor_mat_solver_package','mumps');
+	mumps.mat_mumps_icntl_14=getfieldvalue(options,'mat_mumps_icntl_14',120);
+	mumps.pc_factor_shift_positive_definite=getfieldvalue(options,'pc_factor_shift_positive_definite','true');
+end
Index: /issm/trunk/src/m/solvers/mumpsoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/mumpsoptions.py	(revision 13395)
+++ /issm/trunk/src/m/solvers/mumpsoptions.py	(revision 13395)
@@ -0,0 +1,34 @@
+from collections import OrderedDict
+from pairoptions import *
+from petscversion import *
+
+def mumpsoptions(*args):
+	"""
+	MUMPSOPTIONS - return MUMPS direct solver  petsc options
+
+	   Usage:
+	      options=mumpsoptions;
+	"""
+
+	#retrieve options provided in varargin
+	options=pairoptions(*args)
+	mumps=OrderedDict()
+
+	#default mumps options
+	PETSC_VERSION=petscversion()
+	if PETSC_VERSION==2:
+		mumps['mat_type']=options.getfieldvalue('mat_type','aijmumps')
+		mumps['ksp_type']=options.getfieldvalue('ksp_type','preonly')
+		mumps['pc_type']=options.getfieldvalue('pc_type','lu')
+		mumps['mat_mumps_icntl_14']=options.getfieldvalue('mat_mumps_icntl_14',120)
+		mumps['pc_factor_shift_positive_definite']=options.getfieldvalue('pc_factor_shift_positive_definite','true')
+	if PETSC_VERSION==3:
+		mumps['mat_type']=options.getfieldvalue('mat_type','mpiaij')
+		mumps['ksp_type']=options.getfieldvalue('ksp_type','preonly')
+		mumps['pc_type']=options.getfieldvalue('pc_type','lu')
+		mumps['pc_factor_mat_solver_package']=options.getfieldvalue('pc_factor_mat_solver_package','mumps')
+		mumps['mat_mumps_icntl_14']=options.getfieldvalue('mat_mumps_icntl_14',120)
+		mumps['pc_factor_shift_positive_definite']=options.getfieldvalue('pc_factor_shift_positive_definite','true')
+
+	return mumps
+
Index: /issm/trunk/src/m/solvers/soroptions.m
===================================================================
--- /issm/trunk/src/m/solvers/soroptions.m	(revision 13395)
+++ /issm/trunk/src/m/solvers/soroptions.m	(revision 13395)
@@ -0,0 +1,16 @@
+function sor=soroptions(varargin)
+%SOROPTIONS - return Relaxation Solver petsc options
+%
+%   Usage:
+%      options=soroptions;
+			 
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+sor=struct();
+
+%default sor options
+sor.mat_type=getfieldvalue(options,'mat_type','aij');
+sor.ksp_type=getfieldvalue(options,'ksp_type','cg');
+sor.pc_type=getfieldvalue(options,'pc_type','sor');
+sor.pc_sor_omega=getfieldvalue(options,'pc_sor_omega',1.1);
+sor.pc_sor_its=getfieldvalue(options,'pc_sor_its',2);
Index: /issm/trunk/src/m/solvers/soroptions.py
===================================================================
--- /issm/trunk/src/m/solvers/soroptions.py	(revision 13395)
+++ /issm/trunk/src/m/solvers/soroptions.py	(revision 13395)
@@ -0,0 +1,31 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def soroptions(*args):
+	#SOROPTIONS - return Relaxation Solver petsc options
+	#
+	#   Usage:
+	#      options=soroptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+	
+	options=[['mat_type','aij'],['ksp_type','cg'],['pc_type','sor'],['pc_sor_omega',1.1],['pc_sor_its',2]];
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/trunk/src/m/solvers/stokesoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/stokesoptions.m	(revision 13395)
+++ /issm/trunk/src/m/solvers/stokesoptions.m	(revision 13395)
@@ -0,0 +1,28 @@
+function stokes=stokesoptions(varargin)
+%STOKESOPTIONS - return STOKES multi-physics solver petsc options
+%
+%   Usage:
+%      options=stokesoptions;
+
+%retrieve options provided in varargin
+options=pairoptions(varargin{:});
+stokes=struct();
+
+%default stokes options
+PETSC_VERSION=petscversion();
+if PETSC_VERSION==2,
+	error('stokesoptions error message: multi-physics options not supported in Petsc 2');
+end
+if PETSC_VERSION==3,
+	stokes.mat_type=getfieldvalue(options,'mat_type','mpiaij');
+	stokes.ksp_max_it=getfieldvalue(options,'ksp_max_it',1000);
+	stokes.ksp_type=getfieldvalue(options,'ksp_type','gmres');
+	stokes.pc_type=getfieldvalue(options,'pc_type','fieldsplit');
+	stokes.pc_field_split_type=getfieldvalue(options,'pc_field_split_type','schur');
+	stokes.fieldsplit_0_pc_type=getfieldvalue(options,'fieldsplit_0_pc_type','hypre');
+	stokes.fieldsplit_0_ksp_type=getfieldvalue(options,'fieldsplit_0_ksp_type','gmres');
+	stokes.fieldsplit_0_pc_hypre_type=getfieldvalue(options,'fieldsplit_0_pc_hypre_type','boomerang');
+	stokes.fieldsplit_1_pc_type=getfieldvalue(options,'fieldsplit_1_pc_type','jacobi');
+	stokes.fieldsplit_1_ksp_type=getfieldvalue(options,'fieldsplit_1_ksp_type','preonly');
+	stokes.issm_option_solver=getfieldvalue(options,'issm_option_solver','stokes');
+end
Index: /issm/trunk/src/m/solvers/stokesoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/stokesoptions.py	(revision 13395)
+++ /issm/trunk/src/m/solvers/stokesoptions.py	(revision 13395)
@@ -0,0 +1,40 @@
+#module imports {{{
+from pairoptions import *
+from petscversion  import *
+#}}}
+def stokesoptions(*args):
+	#STOKESOPTIONS - return STOKES multi-physics solver petsc options
+	#
+	#   Usage:
+	#      options=stokesoptions;
+	
+	#retrieve options provided in varargin
+	arguments=pairoptions(*args) 
+
+
+	#default stokes options
+	PETSC_VERSION=petscversion()
+
+	if PETSC_VERSION==2:
+		raise RuntimeError('stokesoptions error message: multi-physics options not supported in Petsc 2')
+	if PETSC_VERSION==3:
+		options=[['mat_type','mpiaij'],['ksp_max_it',1000],['ksp_type','gmres'],['pc_type','fieldsplit'],['pc_field_split_type','schur'],\
+	['fieldsplit_0_pc_type','hypre'],['fieldsplit_0_ksp_type','gmres'],['fieldsplit_0_pc_hypre_type','boomerang'],\
+	['fieldsplit_1_pc_type','jacobi'],['fieldsplit_1_ksp_type','preonly'],['issm_option_solver','stokes']]
+
+	#now, go through our arguments, and write over default options.
+	for i in range(len(arguments.list)):
+		arg1=arguments.list[i][0]
+		arg2=arguments.list[i][1]
+		found=0;
+		for j in range(len(options)):
+			joption=options[j][0]
+			if joption==arg1:
+				joption[1]=arg2;
+				options[j]=joption;
+				found=1;
+				break
+		if not found:
+			#this option did not exist, add it: 
+			options.append([arg1,arg2])
+	return options
Index: /issm/trunk/src/m/string/ddewhite.m
===================================================================
--- /issm/trunk/src/m/string/ddewhite.m	(revision 13395)
+++ /issm/trunk/src/m/string/ddewhite.m	(revision 13395)
@@ -0,0 +1,30 @@
+function sout = ddewhite(s)
+%DDEWHITE Double dewhite. Strip both leading and trailing whitespace.
+%
+%   DDEWHITE(S) removes leading and trailing white space and any null
+%   characters from the string S.  A null character is one that has an absolute
+%   value of 0.
+%
+%   See also DEWHITE, DEBLANK, DDEBLANK.
+
+%   Author:      Peter J. Acklam
+%   Time-stamp:  2003-10-13 11:12:57 +0200
+%   E-mail:      pjacklam@online.no
+%   URL:         http://home.online.no/~pjacklam
+
+   error(nargchk(1, 1, nargin));
+   if ~ischar(s)
+      error('Input must be a string (char array).');
+   end
+
+   if isempty(s)
+      sout = s;
+      return;
+   end
+
+   [r, c] = find(~isspace(s));
+   if size(s, 1) == 1
+      sout = s(min(c) : max(c));
+   else
+      sout = s(:, min(c) : max(c));
+   end
Index: /issm/trunk/src/m/string/dewhite.m
===================================================================
--- /issm/trunk/src/m/string/dewhite.m	(revision 13395)
+++ /issm/trunk/src/m/string/dewhite.m	(revision 13395)
@@ -0,0 +1,30 @@
+function sout = dewhite(s)
+%DEWHITE Dewhite. Strip trailing whitespace.
+%
+%   DEWHITE(S) removes leading and trailing white space and any null characters
+%   from the string S.  A null character is one that has an absolute value of
+%   0.
+%
+%   See also DDEWHITE, DEBLANK, DDEBLANK.
+
+%   Author:      Peter J. Acklam
+%   Time-stamp:  2003-10-13 11:12:52 +0200
+%   E-mail:      pjacklam@online.no
+%   URL:         http://home.online.no/~pjacklam
+
+   error(nargchk(1, 1, nargin));
+   if ~ischar(s)
+      error( 'Input must be a string (char array).' );
+   end
+
+   if isempty(s)
+      sout = s;
+      return;
+   end
+
+   [r, c] = find(~isspace(s));
+   if size(s, 1) == 1
+      sout = s(1:max(c));
+   else
+      sout = s(:,1:max(c));
+   end
Index: /issm/trunk/src/m/string/discardnum.m
===================================================================
--- /issm/trunk/src/m/string/discardnum.m	(revision 13395)
+++ /issm/trunk/src/m/string/discardnum.m	(revision 13395)
@@ -0,0 +1,14 @@
+function string2=discardnum(string)
+%DISCARDNUM -  ??????
+%
+%   Usage:
+%      string2=discardnum(string)
+
+string2=string;
+
+for i=1:length(string),
+	if (((string(i)-0) <=57) & ((string(i)-0) >=48)),
+		string2=string(1:i-1);
+		break;
+	end
+end
Index: /issm/trunk/src/m/string/ismemberi.m
===================================================================
--- /issm/trunk/src/m/string/ismemberi.m	(revision 13395)
+++ /issm/trunk/src/m/string/ismemberi.m	(revision 13395)
@@ -0,0 +1,26 @@
+function flag=ismemberi(string,list),
+%ISMEMBERI - return 1 if a string belongs to a list (case insensitive)
+%
+%   same function as Matlab's ismember except that it
+%   is case insensitive
+%
+%   Usage:
+%      flag=ismemberi(string,list);
+%
+%   Example:
+%      flag=ismemberi('test','{'test1','test2','test3'});
+
+if ~iscell(list)
+	error('ismemberi error message: the list of string must be a cell!')
+end
+
+%initialize output
+flag=0;
+
+%go through the list
+for i=1:length(list),
+	if strcmpi(string,list{i}),
+		flag=i;
+		return
+	end
+end
Index: /issm/trunk/src/m/string/issmprintf.m
===================================================================
--- /issm/trunk/src/m/string/issmprintf.m	(revision 13395)
+++ /issm/trunk/src/m/string/issmprintf.m	(revision 13395)
@@ -0,0 +1,13 @@
+function issmprintf(flag,format,varargin)
+%ISSMPRINTF -  display string in solution sequences. wrapper to disp and sprintf.  
+%
+%   Usage:
+%      issmprintf(flag,format,string)
+%      flag can be used to switch display on and off
+%
+%   Example:
+%      issmprintf(1,'%s\n','string to display');
+	
+if flag,
+	disp(sprintf(format,varargin{:}));
+end
Index: /issm/trunk/src/m/string/strsplit.m
===================================================================
--- /issm/trunk/src/m/string/strsplit.m	(revision 13395)
+++ /issm/trunk/src/m/string/strsplit.m	(revision 13395)
@@ -0,0 +1,91 @@
+function splittedstring = strsplit(inpstr,delimiter)
+%STRSPLIT - split a tring of delimiter separated values
+%
+%   This function should be used to split a string of delimiter separated
+%   values.  If all values are numerical values the returned matrix is a
+%   double array but if there is one non numerical value a cell array is
+%   returned.  You can check this with the iscell() function.
+%   inpstr: string containing delimiter separatede numerical values, eg
+%           3498,48869,23908,34.67
+%   Output: An x by 1 matrix containing the splitted values
+%   Delimiter: optional, if omitted the delimiter is , (comma)
+%
+%   Usage:
+%      output = strsplit(inpstr[,delimiter])
+%
+
+%   mailto:    gie.spaepen@ua.ac.be
+
+
+
+%Check input arguments
+if(nargin < 1)
+    error('There is no argument defined');
+else
+    if(nargin == 1)
+        strdelim = ',';
+        %Verbose off!! disp 'Delimiter set to ,';
+    else
+        strdelim = delimiter;
+    end
+end
+
+%deblank string
+deblank(inpstr);
+
+%Get number of substrings
+idx  = findstr(inpstr,strdelim);
+if size(idx) == 0
+    disp 'No delimiter in string, inputString is returned';
+    splittedstring = inpstr;
+else
+    %Define size of the indices
+    sz = size(idx,2);
+    %Define splittedstring
+    tempsplit = {};
+    %Loop through string and itinerate from delimiter to delimiter
+    for i = 1:sz
+        %Define standard start and stop positions for the start position,
+        %choose 1 as startup position because otherwise you get an array
+        %overflow, for the endposition you can detemine it from the
+        %delimiter position
+        strtpos = 1;
+        endpos = idx(i)-1;
+        %If i is not the beginning of the string get it from the delimiter
+        %position
+        if i ~= 1
+            strtpos = idx(i-1)+1;
+        end
+        %If i is equal to the number of delimiters get the last element
+        %first by determining the lengt of the string and then replace the
+        %endpos back to a standard position
+        if i == sz
+            endpos = size(inpstr,2); 
+            tempsplit(i+1) = {inpstr(idx(i)+1 : endpos)};
+            endpos = idx(i)-1;
+        end
+        %Add substring to output: splittedstring a cell array
+        tempsplit(i) = {inpstr(strtpos : endpos)};   
+    end
+    %Flag 
+    isallnums = 1;
+    %Check is there are NaN values if matrix elements are converted to
+    %doubles
+    for i = 1:size(tempsplit,2)
+        tempdouble = str2double(tempsplit(i));
+        if(isnan(tempdouble))
+            isallnums = 0;
+        end
+    end
+    %If isallnums = 1 then return a double array otherwise return a cell
+    %array
+    if(isallnums == 1)
+        for i = 1:size(tempsplit,2)
+            splittedstring(i) = str2double(tempsplit(i));
+        end
+    else
+        splittedstring = tempsplit;
+    end
+    
+        
+end
Index: /issm/trunk/src/m/string/strsplit_strict.m
===================================================================
--- /issm/trunk/src/m/string/strsplit_strict.m	(revision 13395)
+++ /issm/trunk/src/m/string/strsplit_strict.m	(revision 13395)
@@ -0,0 +1,37 @@
+function splittedstring = strsplit(inpstr,delimiter)
+%STRSPLIT - split a tring of delimiter separated values
+%
+%   Usage:
+%      output = strsplit_strict(inpstr,delimiter)
+
+
+%Check input arguments
+if(nargin ~= 2)
+    error('There is no argument defined');
+end
+
+%deblank string
+deblank(inpstr);
+
+%Get number of substrings
+idx  = findstr(inpstr,delimiter);
+if size(idx) == 0
+    splittedstring = {inpstr};
+else
+    sz = size(idx,2);
+    splittedstring = {};
+    %Loop through string and itinerate from delimiter to delimiter
+    for i = 1:sz
+        strtpos = 1;
+        endpos = idx(i)-1;
+        if i ~= 1
+            strtpos = idx(i-1)+1;
+        end
+        if i == sz
+            endpos = size(inpstr,2); 
+            splittedstring(i+1) = {inpstr(idx(i)+1 : endpos)};
+            endpos = idx(i)-1;
+        end
+        splittedstring(i) = {inpstr(strtpos : endpos)};   
+    end
+end
Index: /issm/trunk/src/modules/AverageFilter/AverageFilter.cpp
===================================================================
--- /issm/trunk/src/modules/AverageFilter/AverageFilter.cpp	(revision 13394)
+++ /issm/trunk/src/modules/AverageFilter/AverageFilter.cpp	(revision 13395)
@@ -10,10 +10,16 @@
 */
 
-
 #include "./AverageFilter.h"
 
-void mexFunction( int nlhs, mxArray* plhs[],
-				  int nrhs, const mxArray* prhs[])
-{
+void AverageFilterUsage(void){/*{{{*/
+	_printLine_("   AverageFilter usage:");
+	_printLine_("   [image_out]=AverageFilter(image_in,pixels);\n");
+	_printLine_("   where:");
+	_printLine_("      image_in in double format");
+	_printLine_("      pixels: characteristic size of smoothing");
+	_printLine_("      image_out in double format");
+	_printLine_("");
+}/*}}}*/
+WRAPPER(AverageFilter){
 
 	int i,j;
@@ -49,14 +55,2 @@
 	MODULEEND();
 }
-
-
-void AverageFilterUsage(void)
-{
-	_printLine_("   AverageFilter usage:");
-	_printLine_("   [image_out]=AverageFilter(image_in,pixels);\n");
-	_printLine_("   where:");
-	_printLine_("      image_in in double format");
-	_printLine_("      pixels: characteristic size of smoothing");
-	_printLine_("      image_out in double format");
-	_printLine_("");
-}
Index: /issm/trunk/src/modules/AverageFilter/AverageFilter.h
===================================================================
--- /issm/trunk/src/modules/AverageFilter/AverageFilter.h	(revision 13394)
+++ /issm/trunk/src/modules/AverageFilter/AverageFilter.h	(revision 13395)
@@ -1,13 +1,19 @@
-
 /*
 	AverageFilter.h
 */
 
-
 #ifndef _AVERAGEFILTER_H
 #define _AVERAGEFILTER_H
 
-/* local prototypes: */
-void AverageFilterUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -20,11 +26,19 @@
 #define __FUNCT__  "AverageFilter"
 
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
 #define IMAGEIN prhs[0]
-#define SMOOTH prhs[1]
+#define SMOOTH  prhs[1]
+/* serial output macros: */
+#define IMAGEOUT (mxArray**)&plhs[0]
+#endif
 
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define IMAGEIN PyTuple_GetItem(args,0)
+#define SMOOTH  PyTuple_GetItem(args,1)
 /* serial output macros: */
-#define IMAGEOUT &plhs[0]
+#define IMAGEOUT output,0
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/BamgConvertMesh/BamgConvertMesh.cpp
===================================================================
--- /issm/trunk/src/modules/BamgConvertMesh/BamgConvertMesh.cpp	(revision 13394)
+++ /issm/trunk/src/modules/BamgConvertMesh/BamgConvertMesh.cpp	(revision 13395)
@@ -4,5 +4,14 @@
 #include "./BamgConvertMesh.h"
 
-void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+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_("");
+}/*}}}*/
+WRAPPER(BamgConvertMesh){
 
 	/*input: */
@@ -13,8 +22,6 @@
 
 	/*Output*/
-	BamgMesh *bamgmesh     = NULL;
-	BamgGeom *bamggeom     = NULL;
-	mxArray  *bamgmesh_mat = NULL;
-	mxArray  *bamggeom_mat = NULL;
+	BamgMesh *bamgmesh = NULL;
+	BamgGeom *bamggeom = NULL;
 
 	/*Boot module: */
@@ -22,5 +29,5 @@
 
 	/*checks on arguments on the matlab side: */
-	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&BamgConvertMeshUsage);
+	CHECKARGUMENTS(NLHS,NRHS,&BamgConvertMeshUsage);
 
 	/*Initialize Bamg outputs*/
@@ -34,8 +41,8 @@
 
 	/*Check inputs*/
-	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");
+	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(test1!=3) _error_("index should have 3 columns");
+	if(test2!=nods) _error_("x and y do not have the same length");
 
 	/* Run core computations: */
@@ -53,12 +60,2 @@
 	MODULEEND();
 }
-
-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/trunk/src/modules/BamgConvertMesh/BamgConvertMesh.h
===================================================================
--- /issm/trunk/src/modules/BamgConvertMesh/BamgConvertMesh.h	(revision 13394)
+++ /issm/trunk/src/modules/BamgConvertMesh/BamgConvertMesh.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _BAMGCONVERTMESH_H
 
-/* local prototypes: */
-void BamgConvertMeshUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -14,17 +22,28 @@
 #include "../../c/shared/shared.h"
 #include "../../c/issm-binding.h"
+#include "../../c/io/io.h"
 
 #undef __FUNCT__ 
 #define __FUNCT__  "BamgConvertMesh"
 
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
 #define INDEXHANDLE prhs[0]
-#define XHANDLE prhs[1]
-#define YHANDLE prhs[2]
-
+#define XHANDLE     prhs[1]
+#define YHANDLE     prhs[2]
 /* serial output macros: */
 #define BAMGMESHOUT    (mxArray**)&plhs[0]
 #define BAMGGEOMOUT    (mxArray**)&plhs[1]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define INDEXHANDLE PyTuple_GetItem(args,0)
+#define XHANDLE     PyTuple_GetItem(args,1)
+#define YHANDLE     PyTuple_GetItem(args,2)
+/* serial output macros: */
+#define BAMGMESHOUT    output,0
+#define BAMGGEOMOUT    output,1
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/BamgMesher/BamgMesher.cpp
===================================================================
--- /issm/trunk/src/modules/BamgMesher/BamgMesher.cpp	(revision 13394)
+++ /issm/trunk/src/modules/BamgMesher/BamgMesher.cpp	(revision 13395)
@@ -4,11 +4,12 @@
 #include "./BamgMesher.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void BamgMesherUsage(void){/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("   usage: [bamgmesh,bamggeom]=" << __FUNCT__ << "(bamgmesh,bamggeom,bamgoptions);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(BamgMesher){
 
-	/*Outputs*/
-	mxArray* bamgmesh_mat=NULL;
-	mxArray* bamggeom_mat=NULL;
-
-	/*diverse: */
+	/*Intermediary*/
 	BamgOpts *bamgopts=NULL;
 	BamgMesh *bamgmesh_in=NULL;
@@ -17,9 +18,9 @@
 	BamgGeom *bamggeom_out=NULL;
 
-	/*Boot module: */
+	/*Boot module*/
 	MODULEBOOT();
 
 	/*checks on arguments on the matlab side: */
-	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&BamgMesherUsage);
+	CHECKARGUMENTS(NLHS,NRHS,&BamgMesherUsage);
 
 	/*Initialize outputs*/
@@ -49,8 +50,2 @@
 	MODULEEND();
 }
-
-void BamgMesherUsage(void){
-	_pprintLine_("");
-	_pprintLine_("   usage: [bamgmesh,bamggeom]=" << __FUNCT__ << "(bamgmesh,bamggeom,bamgoptions);");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/BamgMesher/BamgMesher.h
===================================================================
--- /issm/trunk/src/modules/BamgMesher/BamgMesher.h	(revision 13394)
+++ /issm/trunk/src/modules/BamgMesher/BamgMesher.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _BAMG_MESHER_H_
 
-/* local prototypes: */
-void BamgMesherUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -17,13 +25,24 @@
 #undef __FUNCT__ 
 #define __FUNCT__  "BamgMesher"
-    
+
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define BAMGMESHIN  (mxArray*)prhs[0]
-#define BAMGGEOMIN  (mxArray*)prhs[1]
-#define BAMGOPTIONS (mxArray*)prhs[2]
+#define BAMGMESHIN  prhs[0]
+#define BAMGGEOMIN  prhs[1]
+#define BAMGOPTIONS prhs[2]
+/* serial output macros: */
+#define BAMGMESHOUT (mxArray**)&plhs[0]
+#define BAMGGEOMOUT (mxArray**)&plhs[1]
+#endif
 
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define BAMGMESHIN  PyTuple_GetItem(args,0)
+#define BAMGGEOMIN  PyTuple_GetItem(args,1)
+#define BAMGOPTIONS PyTuple_GetItem(args,2)
 /* serial output macros: */
-#define BAMGMESHOUT    (mxArray**)&plhs[0]
-#define BAMGGEOMOUT    (mxArray**)&plhs[1]
+#define BAMGMESHOUT output,0
+#define BAMGGEOMOUT output,1
+#endif
 
 /* serial arg counts: */
@@ -34,3 +53,2 @@
 
 #endif  /* _BAMG_MESHER_H_ */
-
Index: /issm/trunk/src/modules/BamgTriangulate/BamgTriangulate.cpp
===================================================================
--- /issm/trunk/src/modules/BamgTriangulate/BamgTriangulate.cpp	(revision 13394)
+++ /issm/trunk/src/modules/BamgTriangulate/BamgTriangulate.cpp	(revision 13395)
@@ -4,5 +4,14 @@
 #include "./BamgTriangulate.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void BamgTriangulateUsage(void){/*{{{*/
+	_pprintString_("BAMGTRIANGULATE - Delaunay Triangulation of a list of points");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      index=BamgTriangulate(x,y);");
+	_pprintLine_("      index: index of the triangulation");
+	_pprintLine_("      x,y: coordinates of the nodes");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(BamgTriangulate){
 
 	/*input: */
@@ -32,7 +41,7 @@
 
 	/*Check inputs*/
-	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");
+	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");
 
 	/* Run core computations: */
@@ -46,13 +55,2 @@
 	MODULEEND();
 }
-
-void BamgTriangulateUsage(void)
-{
-	_pprintString_("BAMGTRIANGULATE - Delaunay Triangulation of a list of points");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      index=BamgTriangulate(x,y);");
-	_pprintLine_("      index: index of the triangulation");
-	_pprintLine_("      x,y: coordinates of the nodes");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/BamgTriangulate/BamgTriangulate.h
===================================================================
--- /issm/trunk/src/modules/BamgTriangulate/BamgTriangulate.h	(revision 13394)
+++ /issm/trunk/src/modules/BamgTriangulate/BamgTriangulate.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _BAMGTRIANGULATE_H
 
-/* local prototypes: */
-void BamgTriangulateUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -18,5 +26,5 @@
 #define __FUNCT__  "BamgTriangulate"
 
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
 #define XHANDLE prhs[0]
@@ -25,4 +33,14 @@
 /* serial output macros: */
 #define INDEX (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define XHANDLE PyTuple_GetItem(args,0)
+#define YHANDLE PyTuple_GetItem(args,1)
+
+/* serial output macros: */
+#define INDEX output,0
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/Chaco/Chaco.cpp
===================================================================
--- /issm/trunk/src/modules/Chaco/Chaco.cpp	(revision 13394)
+++ /issm/trunk/src/modules/Chaco/Chaco.cpp	(revision 13395)
@@ -9,8 +9,12 @@
 #endif
 
-
 #include "./Chaco.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void ChacoUsage(void){/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("Usage: [assgn] = Chaco(A,vwgts,ewgts,x,y,z,options,nparts,goal);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(Chaco){
    
 	int i;
@@ -42,5 +46,5 @@
 
 	#ifndef _HAVE_CHACO_ //only works if dakota library has been compiled in.
-	_error2_("Chaco not available! Cannot carry out Chaco partitioning!");
+	_error_("Chaco not available! Cannot carry out Chaco partitioning!");
 	#endif
 
@@ -54,14 +58,14 @@
 	nvtxs = mxGetN(A_IN);
 	mwstart = mxGetJc(A_IN);
-	start=(int*)xmalloc((nvtxs+1)*sizeof(int));
+	start=xNew<int>((nvtxs+1));
 	for (i=0; i<nvtxs+1;i++)start[i]=(int)mwstart[i];
 
 	mwadjacency = mxGetIr(A_IN);
-	adjacency = (int*)xmalloc(mxGetNzmax(A_IN)*sizeof(int));
+	adjacency = xNew<int>(mxGetNzmax(A_IN));
 	for (i=0; i<mxGetNzmax(A_IN); i++) adjacency[i]= (int)mwadjacency[i];
 
 	nedges = start[nvtxs];
 	if(!mxIsEmpty(EWGTS_IN)){
-		ewgts = (float*)xcalloc(nedges, sizeof(float));
+		ewgts = xNewZeroInit<float>(nedges);
 		doublepointer=mxGetPr(A_IN);
 		for (i = 0; i < nedges; i++)ewgts[i] = (float)doublepointer[i];
@@ -77,5 +81,5 @@
 	for (i=0;i<(nterms<10?nterms:10);i++) options[i]=in_options[i]; //copy in_options into default options
 	FetchData(&npart,NPARTS_IN); 
-	nparts=(int*)xmalloc(sizeof(int)); nparts[0]=npart; //weird Chacox interface ain't it?
+	nparts=xNew<int>(1); nparts[0]=npart; //weird Chacox interface ain't it?
 	FetchData(&goal,&nterms,GOAL_IN); 
 	
@@ -104,5 +108,5 @@
 	
 	/*Allocate output: */
-	assignment = (short*)xcalloc(nvtxs, sizeof(short));
+	assignment = xNewZeroInit<short>(nvtxs);
 	
     /*Call core: */
@@ -110,28 +114,22 @@
 
     /*Output data: */
-	doubleassignment=(double*)xmalloc(nvtxs*sizeof(double));
+	doubleassignment=xNew<double>(nvtxs);
 	for(i=0;i<nvtxs;i++) doubleassignment[i]=(double)assignment[i];
 	WriteData(ASSGN_OUT,doubleassignment,nvtxs);
 
 	/*Free ressources:*/
-	xfree((void**)&assignment); 
-	xfree((void**)&goal);
-	xfree((void**)&nparts);
-	xfree((void**)&z);
-	xfree((void**)&y);
-	xfree((void**)&x);
-	xfree((void**)&ewgts);
-	xfree((void**)&vwgts);
-	xfree((void**)&adjacency);
-	xfree((void**)&start);
-	xfree((void**)&doubleassignment);
+	xDelete<short>(assignment); 
+	xDelete<double>(goal);
+	xDelete<int>(nparts);
+	xDelete<float>(z);
+	xDelete<float>(y);
+	xDelete<float>(x);
+	xDelete<float>(ewgts);
+	xDelete<int>(vwgts);
+	xDelete<int>(adjacency);
+	xDelete<int>(start);
+	xDelete<double>(doubleassignment);
 
 	/*end module: */
 	MODULEEND();
 }
-
-void ChacoUsage(void){
-	_pprintLine_("");
-	_pprintLine_("Usage: [assgn] = Chaco(A,vwgts,ewgts,x,y,z,options,nparts,goal);");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/Chaco/Chaco.h
===================================================================
--- /issm/trunk/src/modules/Chaco/Chaco.h	(revision 13394)
+++ /issm/trunk/src/modules/Chaco/Chaco.h	(revision 13395)
@@ -6,11 +6,19 @@
 #define _CHACO_H
 
-/* local prototypes: */
-void ChacoUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
 
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*headers*/
 #include <stdio.h>
 #include <string.h>    /*  strcasecmp  */
 #include <time.h>      /*  clock,time,difftime  */
-
 #include "../../c/include/globals.h"
 #include "../../c/modules/modules.h"
@@ -18,18 +26,37 @@
 #include "../../c/shared/shared.h"
 #include "../../c/issm-binding.h"
-    
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Chaco"
+
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define A_IN (mxArray*)prhs[0]
-#define VWGTS_IN (mxArray*)prhs[1]
-#define EWGTS_IN (mxArray*)prhs[2]
-#define X_IN (mxArray*)prhs[3]
-#define Y_IN (mxArray*)prhs[4]
-#define Z_IN (mxArray*)prhs[5]
-#define OPTNS_IN (mxArray*)prhs[6]
-#define NPARTS_IN (mxArray*)prhs[7]
-#define GOAL_IN (mxArray*)prhs[8]
-
+#define A_IN      prhs[0]
+#define VWGTS_IN  prhs[1]
+#define EWGTS_IN  prhs[2]
+#define X_IN      prhs[3]
+#define Y_IN      prhs[4]
+#define Z_IN      prhs[5]
+#define OPTNS_IN  prhs[6]
+#define NPARTS_IN prhs[7]
+#define GOAL_IN   prhs[8]
 /* serial output macros: */
 #define ASSGN_OUT (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define A_IN      PyTuple_GetItem(args,0)
+#define VWGTS_IN  PyTuple_GetItem(args,1)
+#define EWGTS_IN  PyTuple_GetItem(args,2)
+#define X_IN      PyTuple_GetItem(args,3)
+#define Y_IN      PyTuple_GetItem(args,4)
+#define Z_IN      PyTuple_GetItem(args,5)
+#define OPTNS_IN  PyTuple_GetItem(args,6)
+#define NPARTS_IN PyTuple_GetItem(args,7)
+#define GOAL_IN   PyTuple_GetItem(args,8)
+/* serial output macros: */
+#define ASSGN_OUT output,0
+#endif
 
 /* serial arg counts: */
@@ -39,6 +66,3 @@
 #define NRHS  9
 
-#undef __FUNCT__ 
-#define __FUNCT__  "Chaco"
-
 #endif  /* _CHACO_H */
Index: /issm/trunk/src/modules/ContourToMesh/ContourToMesh.cpp
===================================================================
--- /issm/trunk/src/modules/ContourToMesh/ContourToMesh.cpp	(revision 13394)
+++ /issm/trunk/src/modules/ContourToMesh/ContourToMesh.cpp	(revision 13395)
@@ -2,93 +2,9 @@
     \brief: takes an  contour file, and figures out which nodes or elements from the mesh  
     are inside this contour. 
-	usage:
-	[in_nod,in_elem]=ContourToMesh(index,x,y,contours,interptype,edgevalue);
-	
-	input:
-
-		index,x,y: delaunay triangulation.
-		contours: structure holding sets of vertices making open contours. 
-		interptype: string definining type of interpolation ('element', or 'node', or 'element and node');
-		edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons
-
-	output:
-		in_nod: vector of flags (0 or 1), of size nods if interptype is set to 'node' or 'element and node', 
-				or of size 0 otherwise.
-		in_elem: vector of flags (0 or 1), of size nel if interptype is set to 'element' or 'element and node', 
-				or of size 0 otherwise.
 */
 	
 #include "./ContourToMesh.h"
 
-WRAPPER(ContourToMesh){
-
-	int i,j;
-
-	/* required input: */
-	int     edgevalue;
-	double *index      = NULL;
-	int     nel;
-	double *x          = NULL;
-	int     nods;
-	double *y          = NULL;
-	char   *interptype = NULL;
-	char* contourname  = NULL;
-	DataSet* contours  = NULL;
-
-	/* output: */
-	Vector *in_nod  = NULL;
-	Vector *in_elem = NULL;
-
-	/*Boot module: */
-	MODULEBOOT();
-
-	/*checks on output arguments on the matlab side: */
-	#ifdef _HAVE_MATLAB_MODULES_
-	if(nlhs!=1 && nlhs!=2){
-		ContourToMeshUsage();
-		_error2_("usage. See above");
-	}
-	#endif
-	/*check on input arguments: */
-	if(nrhs!=NRHS){
-		ContourToMeshUsage();
-		_error2_("usage. See above");
-	}
-
-
-	/*Fetch inputs: */
-	FetchData(&index,&nel,NULL,INDEX);
-	FetchData(&x,&nods,NULL,X);
-	FetchData(&y,NULL,NULL,Y);
-	FetchData(&edgevalue,EDGEVALUE);
-	FetchData(&contourname,CONTOURNAME);
-	contours=DomainOutlineRead(contourname);
-
-	/*Fetch  interptype: */
-	FetchData(&interptype,INTERPTYPE);
-
-	/*Run interpolation routine: */
-	ContourToMeshx( &in_nod,&in_elem,index,x,y,contours,interptype,nel,nods,edgevalue);
-
-	/* output: */
-	if (strcmp(interptype,"node")==0){
-		WriteData(PLHS0,in_nod);
-	}
-	else if (strcmp(interptype,"element")==0){
-		WriteData(PLHS0,in_elem);
-	}
-	else if (strcmp(interptype,"element and node")==0){
-		WriteData(PLHS0,in_nod);
-		WriteData(PLHS1,in_elem);
-	}
-	else _error2_("wrong interpolation type");
-
-	/*end module: */
-	MODULEEND();
-	
-}
-
-void ContourToMeshUsage(void)//{{{1
-{
+void ContourToMeshUsage(void){/*{{{*/
 	_printLine_("CONTOURTOMESH - Flag the elements or nodes inside a contour");
 	_printLine_("");
@@ -110,4 +26,62 @@
 	_printLine_("         [in_nodes,in_elements]=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','element and node',0)");
 	_printLine_("");
+}/*}}}*/
+WRAPPER(ContourToMesh){
+
+	/* required input: */
+	int      edgevalue;
+	double  *index       = NULL;
+	int      nel;
+	double  *x           = NULL;
+	int      nods;
+	double  *y           = NULL;
+	char    *interptype  = NULL;
+	DataSet *contours    = NULL;
+
+	/* output: */
+	SeqVec<double> *in_nod  = NULL;
+	SeqVec<double> *in_elem = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on output arguments on the matlab side: */
+	#ifdef _HAVE_MATLAB_MODULES_
+	if(nlhs!=1 && nlhs!=2){
+		ContourToMeshUsage();
+		_error_("usage. See above");
+	}
+	#endif
+	/*check on input arguments: */
+	if(nrhs!=NRHS){
+		ContourToMeshUsage();
+		_error_("usage. See above");
+	}
+
+	/*Fetch inputs: */
+	FetchData(&index,&nel,NULL,INDEX);
+	FetchData(&x,&nods,NULL,X);
+	FetchData(&y,NULL,NULL,Y);
+	FetchData(&edgevalue,EDGEVALUE);
+	FetchData(&contours,CONTOUR);
+	FetchData(&interptype,INTERPTYPE);
+
+	/*Run interpolation routine: */
+	ContourToMeshx( &in_nod,&in_elem,index,x,y,contours,interptype,nel,nods,edgevalue);
+
+	/* output: */
+	if (strcmp(interptype,"node")==0){
+		WriteData(PLHS0,in_nod);
+	}
+	else if (strcmp(interptype,"element")==0){
+		WriteData(PLHS0,in_elem);
+	}
+	else if (strcmp(interptype,"element and node")==0){
+		WriteData(PLHS0,in_nod);
+		WriteData(PLHS1,in_elem);
+	}
+	else _error_("wrong interpolation type");
+
+	/*end module: */
+	MODULEEND();
 }
-//}}}
Index: /issm/trunk/src/modules/ContourToMesh/ContourToMesh.h
===================================================================
--- /issm/trunk/src/modules/ContourToMesh/ContourToMesh.h	(revision 13394)
+++ /issm/trunk/src/modules/ContourToMesh/ContourToMesh.h	(revision 13395)
@@ -1,19 +1,16 @@
-
 /*
 	ContourToMesh.h
 */
 
-
 #ifndef _CONTOURTOMESH_H
 #define _CONTOURTOMESH_H
-
 
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
 #else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif
 
-/*Very important definition in case we are compiling a python module!: needs to come before header files inclusion*/
+/*For python modules: needs to come before header files inclusion*/
 #ifdef _HAVE_PYTHON_
 #define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
@@ -31,12 +28,15 @@
 #include "../../c/EnumDefinitions/EnumDefinitions.h"
 
+#undef __FUNCT__
+#define __FUNCT__ "ContourToMesh"
+
 #ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define INDEX (mxArray *)prhs[0]
-#define X (mxArray *)prhs[1]
-#define Y (mxArray *)prhs[2]
-#define CONTOURNAME (mxArray *)prhs[3]
-#define INTERPTYPE (mxArray *)prhs[4]
-#define EDGEVALUE (mxArray *)prhs[5]
+#define INDEX       prhs[0]
+#define X           prhs[1]
+#define Y           prhs[2]
+#define CONTOUR     prhs[3]
+#define INTERPTYPE  prhs[4]
+#define EDGEVALUE   prhs[5]
 /* serial output macros: */
 #define PLHS0 (mxArray**)&plhs[0]
@@ -46,17 +46,14 @@
 #ifdef _HAVE_PYTHON_MODULES_
 /* serial input macros: */
-#define INDEX PyTuple_GetItem(args,0)
-#define X PyTuple_GetItem(args,1)
-#define Y PyTuple_GetItem(args,2)
-#define CONTOURNAME PyTuple_GetItem(args,3)
-#define INTERPTYPE PyTuple_GetItem(args,4)
-#define EDGEVALUE PyTuple_GetItem(args,5)
+#define INDEX       PyTuple_GetItem(args,0)
+#define X           PyTuple_GetItem(args,1)
+#define Y           PyTuple_GetItem(args,2)
+#define CONTOUR     PyTuple_GetItem(args,3)
+#define INTERPTYPE  PyTuple_GetItem(args,4)
+#define EDGEVALUE   PyTuple_GetItem(args,5)
 /* serial output macros: */
 #define PLHS0 output,0
 #define PLHS1 output,1
 #endif
-
-#undef __FUNCT__
-#define __FUNCT__ "ContourToMesh"
 
 /* serial arg counts: */
@@ -66,7 +63,4 @@
 #define NRHS 6
 
-/* local prototypes: */
-void ContourToMeshUsage(void);
-
 #endif  /* _CONTOURTOMESH_H */
 
Index: /issm/trunk/src/modules/ContourToNodes/ContourToNodes.cpp
===================================================================
--- /issm/trunk/src/modules/ContourToNodes/ContourToNodes.cpp	(revision 13394)
+++ /issm/trunk/src/modules/ContourToNodes/ContourToNodes.cpp	(revision 13395)
@@ -1,46 +1,29 @@
 /*! \file  ContourtoNodes
     \brief: takes a  contour file, and figures out which nodes  (x,y list)
-    are inside this contour. 
-
-	usage:
-	[flags]=ContourToNodes(x,y,contours,interptype,edgevalue);
-	
-	where:
-
-	input:
-
-		x,y: node cooredinates
-		
-		contours: structure holding sets of vertices making open contours. 
-		
-		interptype: string definining type of interpolation ('element', or 'node', or 'element and node');
-
-		edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons
-
-	output:
-		flags: vector of flags (0 or 1), of size nods 
 */
 	
 #include "./ContourToNodes.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+void ContourToNodesUsage(void){/*{{{*/
+	_printLine_("   usage:");
+	_printLine_("   [flags]=ContourToNodes(x,y,contourname,edgevalue);\n");
+	_printLine_("   where:");
+	_printLine_("      x,y: list of nodes.");
+	_printLine_("      contourname: name of .exp file containing the contours, or resulting structure from call to expread.");
+	_printLine_("      edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons.");
+	_printLine_("      flags: vector of flags (0 or 1), of size nods.");
+	_printLine_("");
+}/*}}}*/
+WRAPPER(ContourToNodes){
 
-	int i,j;
-
-	/* required input: */
-	double* x=NULL;
-	double* y=NULL;
-	int     edgevalue;
-	char*   interptype=NULL;
+	/* input: */
+	int      edgevalue,nods;
+	double  *x           = NULL;
+	double  *y           = NULL;
+	char    *contourname = NULL;
+	DataSet *contours    = NULL;
 
 	/* output: */
-	Vector*  flags=NULL;
-	int  nods;
-
-	//contours
-	mxArray*  matlabstructure=NULL;
-	int numcontours;
-	Contour** contours=NULL;
-	Contour*  contouri=NULL;
+	SeqVec<double> *flags = NULL;
 
 	/*Boot module: */
@@ -48,49 +31,14 @@
 
 	/*checks on arguments on the matlab side: */
-	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ContourToNodesUsage);
-
+	CHECKARGUMENTS(NLHS,NRHS,&ContourToNodesUsage);
 	
 	/*Fetch inputs: */
 	FetchData(&x,&nods,NULL,XHANDLE);
 	FetchData(&y,NULL,NULL,YHANDLE);
-	FetchData(&edgevalue,EDGEVALUEHANDLE);
+	FetchData(&edgevalue,EDGEVALUE);
+	FetchData(&contours,CONTOUR);
 
-	//Fetch contours
-
-	if(mxIsChar(FILENAME)){
-		/*Call expread on filename to build a contour array in the matlab workspace: */
-		mexCallMATLAB( 1, &matlabstructure, 1, (mxArray**)&FILENAME, "expread");
-	}
-	else{
-		/*FILENAME is actually a structure, coming directly from expread: */
-		matlabstructure=(mxArray*)FILENAME;
-	}
-
-	numcontours=mxGetNumberOfElements(matlabstructure);
-	contours=(Contour**)xmalloc(numcontours*sizeof(Contour*));
-	for(i=0;i<numcontours;i++){
-		//allocate
-		contouri=(Contour*)xmalloc(sizeof(Contour));
-		//retrieve dimension of this contour.
-		contouri->nods=(int)mxGetScalar(mxGetField(matlabstructure,i,"nods"));
-		//set pointers.
-		contouri->x=mxGetPr(mxGetField(matlabstructure,i,"x"));
-		contouri->y=mxGetPr(mxGetField(matlabstructure,i,"y"));
-		*(contours+i)=contouri;
-	}
-
-	/* Debugging of contours :{{{1*/
-	/*for(i=0;i<numcontours;i++){
-		_printLine_("\nContour echo: contour number  " << i+1 << " / " << numcontours);
-		contouri=*(contours+i);
-		_printLine_("   Number of nodes " << contouri->nods);
-		for (j=0;j<contouri->nods;j++){
-			_printLine_("   " << *(contouri->x+j) << "f " << *(contouri->y+j) << "f");
-		}
-	}*/
-	/*}}}*/
-
-	/*Run interpolation routine: */
-	ContourToNodesx(&flags,x,y,nods,contours,numcontours,edgevalue);
+	/*Run x layer */
+	ContourToNodesx(&flags,x,y,nods,contours,edgevalue);
 
 	/* output: */
@@ -99,16 +47,3 @@
 	/*end module: */
 	MODULEEND();
-
 }
-
-void ContourToNodesUsage(void){
-	_printLine_("   usage:");
-	_printLine_("   [flags]=ContourToNodes(x,y,contourname,edgevalue);\n");
-	_printLine_("   where:");
-	_printLine_("      x,y: list of nodes.");
-	_printLine_("      contourname: name of .exp file containing the contours, or resulting structure from call to expread.");
-	_printLine_("      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/trunk/src/modules/ContourToNodes/ContourToNodes.h
===================================================================
--- /issm/trunk/src/modules/ContourToNodes/ContourToNodes.h	(revision 13394)
+++ /issm/trunk/src/modules/ContourToNodes/ContourToNodes.h	(revision 13395)
@@ -1,13 +1,19 @@
-
 /*
 	ContourToNodes.h
 */
 
-
 #ifndef _CONTOURTONODES_H
 #define _CONTOURTONODES_H
 
-/* local prototypes: */
-void ContourToNodesUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -20,17 +26,25 @@
 #define __FUNCT__ "ContourToNodes"
 
-
-#ifndef ALL
-#define ALL 0
-#endif
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* input macros: */
-#define XHANDLE prhs[0]
-#define YHANDLE prhs[1]
-#define FILENAME prhs[2]
-#define EDGEVALUEHANDLE prhs[3]
+#define XHANDLE   prhs[0]
+#define YHANDLE   prhs[1]
+#define CONTOUR   prhs[2]
+#define EDGEVALUE prhs[3]
 
 /* serial output macros: */
 #define FLAGS (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* input macros: */
+#define XHANDLE   PyTuple_GetItem(args,0)
+#define YHANDLE   PyTuple_GetItem(args,1)
+#define CONTOUR   PyTuple_GetItem(args,2)
+#define EDGEVALUE PyTuple_GetItem(args,3)
+
+/* serial output macros: */
+#define FLAGS output,0
+#endif
 
 /* serial arg counts: */
@@ -40,5 +54,4 @@
 #define NRHS 4
 
-
 #endif  /* _CONTOURTONODES_H */
 
Index: /issm/trunk/src/modules/ElementConnectivity/ElementConnectivity.cpp
===================================================================
--- /issm/trunk/src/modules/ElementConnectivity/ElementConnectivity.cpp	(revision 13394)
+++ /issm/trunk/src/modules/ElementConnectivity/ElementConnectivity.cpp	(revision 13395)
@@ -5,4 +5,9 @@
 #include "./ElementConnectivity.h"
 
+void ElementConnectivityUsage(void) {/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("   usage: elementconnectivity = " << __FUNCT__ << "(elements, nodeconnectivity);");
+	_pprintLine_("");
+}/*}}}*/
 WRAPPER(ElementConnectivity){
 
@@ -35,8 +40,2 @@
 	MODULEEND();
 }
-
-void ElementConnectivityUsage(void) {
-	_pprintLine_("");
-	_pprintLine_("   usage: elementconnectivity = " << __FUNCT__ << "(elements, nodeconnectivity);");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/ElementConnectivity/ElementConnectivity.h
===================================================================
--- /issm/trunk/src/modules/ElementConnectivity/ElementConnectivity.h	(revision 13394)
+++ /issm/trunk/src/modules/ElementConnectivity/ElementConnectivity.h	(revision 13395)
@@ -9,8 +9,8 @@
 	#include <config.h>
 #else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif
 
-/*Very important definition in case we are compiling a python module!: needs to come before header files inclusion*/
+/*For python modules: needs to come before header files inclusion*/
 #ifdef _HAVE_PYTHON_
 #define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
@@ -28,9 +28,11 @@
 #include "../../c/EnumDefinitions/EnumDefinitions.h"
 
+#undef __FUNCT__ 
+#define __FUNCT__  "ElementConnectivity"
+
 #ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-/* serial input macros: */
-#define ELEMENTS (mxArray*)prhs[0]
-#define NODECONNECTIVITY (mxArray*)prhs[1]
+#define ELEMENTS         prhs[0]
+#define NODECONNECTIVITY prhs[1]
 /* serial output macros: */
 #define ELEMENTCONNECTIVITY (mxArray**)&plhs[0]
@@ -39,13 +41,9 @@
 #ifdef _HAVE_PYTHON_MODULES_
 /* serial input macros: */
-/* serial input macros: */
-#define ELEMENTS PyTuple_GetItem(args,0)
+#define ELEMENTS         PyTuple_GetItem(args,0)
 #define NODECONNECTIVITY PyTuple_GetItem(args,1)
 /* serial output macros: */
 #define ELEMENTCONNECTIVITY output,0
 #endif
-
-#undef __FUNCT__ 
-#define __FUNCT__  "ElementConnectivity"
 
 /* serial arg counts: */
@@ -55,6 +53,3 @@
 #define NRHS  2
 
-/* local prototypes: */
-void ElementConnectivityUsage(void);
-
 #endif  /* _ELEMENTCONNECTIVITY_H */
Index: /issm/trunk/src/modules/EnumToString/EnumToString.cpp
===================================================================
--- /issm/trunk/src/modules/EnumToString/EnumToString.cpp	(revision 13394)
+++ /issm/trunk/src/modules/EnumToString/EnumToString.cpp	(revision 13395)
@@ -5,13 +5,19 @@
 #include "./EnumToString.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void EnumToStringUsage(void){/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("   usage: " << __FUNCT__ << "string = EnumToString(enum);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(EnumToString){
 
 	char    *name    = NULL;
 	int      enum_in;
 
-	/*checks on arguments on the matlab side: */
-	if(nrhs!=NRHS){
-		EnumToStringUsage(); _error2_("usage. See above");
-	}
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&EnumToStringUsage);
 
 	/*Fetch inputs: */
@@ -23,10 +29,6 @@
 	/* output: */
 	WriteData(NAME,name);
+
+	/*end module: */
+	MODULEEND();
 }
-
-void EnumToStringUsage(void)
-{
-	_pprintLine_("");
-	_pprintLine_("   usage: " << __FUNCT__ << "string = EnumToString(enum);");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/EnumToString/EnumToString.h
===================================================================
--- /issm/trunk/src/modules/EnumToString/EnumToString.h	(revision 13394)
+++ /issm/trunk/src/modules/EnumToString/EnumToString.h	(revision 13395)
@@ -6,7 +6,16 @@
 #define _ENUMTOSTRING_H
 
-/* local prototypes: */
-void EnumToStringUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
 
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*Header files: */
 #include "../../c/include/globals.h"
 #include "../../c/modules/modules.h"
@@ -14,10 +23,21 @@
 #include "../../c/shared/shared.h"
 #include "../../c/issm-binding.h"
-    
+
+#undef __FUNCT__ 
+#define __FUNCT__  "EnumToString"
+ 
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
 #define ENUMIN (mxArray*)prhs[0]
-
 /* serial output macros: */
 #define NAME (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define ENUMIN PyTuple_GetItem(args,0)
+/* serial output macros: */
+#define NAME output,0
+#endif
 
 /* serial arg counts: */
@@ -27,6 +47,3 @@
 #define NRHS  1
 
-#undef __FUNCT__ 
-#define __FUNCT__  "EnumToString"
-
 #endif  /* _TEST_H */
Index: /issm/trunk/src/modules/Exp2Kml/Exp2Kml.cpp
===================================================================
--- /issm/trunk/src/modules/Exp2Kml/Exp2Kml.cpp	(revision 13394)
+++ /issm/trunk/src/modules/Exp2Kml/Exp2Kml.cpp	(revision 13395)
@@ -4,73 +4,5 @@
 #include "./Exp2Kml.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
-
-	int i,verbose=1;
-
-	/*input: */
-	char    *filexp=NULL,*filkml=NULL;
-	int     sgn;
-
-	Options* options=NULL;
-	char     *choles=NULL;
-	bool     holes=false;
-	double   cm=0.,sp=0.;
-
-	/* output: */
-	int     iret=0;
-
-	/*Boot module: */
-	MODULEBOOT();
-
-	/*checks on arguments on the matlab side: */
-	if (nlhs > NLHS) {
-		Exp2KmlUsage(); _error2_("Exp2Kml usage error");
-	}
-	if (nrhs < NRHS) {
-		Exp2KmlUsage(); _error2_("Exp2Kml usage error");
-	}
-
-	/*Input datasets: */
-	FetchData(&filexp,EXP_IN);
-	FetchData(&filkml,KML_IN);
-	FetchData(&sgn,SGN_IN);
-	FetchData(&options,NRHS,nrhs,prhs);
-
-	options->Get(&choles,"holes","no");
-	if (!strncmp(choles,"y",1) || !strncmp(choles,"on",2)) holes=true;
-
-	/*  defaults are in Xy2lldef, so don't duplicate them here, and only use user values if both have been specified  */
-	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
-		options->Get(&cm,"central_meridian");
-		if (verbose) _printLine_("  cm=" << cm);
-		options->Get(&sp,"standard_parallel");
-		if (verbose) _printLine_("  sp=" << sp);
-	}
-
-	/*some checks*/
-	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: */
-	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
-		iret=Exp2Kmlx(filexp,filkml,sgn,cm,sp,holes);
-	else
-		iret=Exp2Kmlx(filexp,filkml,sgn,holes);
-
-	/*Write data: */
-	WriteData(RET_OUT,iret);
-
-	/*Clean-up*/
-	xfree((void**)&choles);
-	delete options;
-	xfree((void**)&filkml);
-	xfree((void**)&filexp);
-
-	/*end module: */
-	MODULEEND();
-}
-
-void Exp2KmlUsage(void){
+void Exp2KmlUsage(void){/*{{{*/
 	_pprintLine_("Exp2Kml - exp to kml file conversion module:");
 	_pprintLine_("");
@@ -95,4 +27,70 @@
 	_pprintLine_("      [ret]=Exp2Kml('file.exp','file.kml',-1,'central_meridian', 0,'standard_parallel',71,'holes','yes');");
 	_pprintLine_("");
+}/*}}}*/
+WRAPPER(Exp2Kml){
+
+	int i,verbose=1;
+
+	/*input: */
+	char    *filexp=NULL,*filkml=NULL;
+	int     sgn;
+
+	Options* options=NULL;
+	char     *choles=NULL;
+	bool     holes=false;
+	double   cm=0.,sp=0.;
+
+	/* output: */
+	int     iret=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if (nlhs > NLHS) {
+		Exp2KmlUsage(); _error_("Exp2Kml usage error");
+	}
+	if (nrhs < NRHS) {
+		Exp2KmlUsage(); _error_("Exp2Kml usage error");
+	}
+
+	/*Input datasets: */
+	FetchData(&filexp,EXP_IN);
+	FetchData(&filkml,KML_IN);
+	FetchData(&sgn,SGN_IN);
+	FetchData(&options,NRHS,nrhs,prhs);
+
+	options->Get(&choles,"holes",(char*)"no");
+	if (!strncmp(choles,"y",1) || !strncmp(choles,"on",2)) holes=true;
+
+	/*  defaults are in Xy2lldef, so don't duplicate them here, and only use user values if both have been specified  */
+	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
+		options->Get(&cm,"central_meridian");
+		if (verbose) _printLine_("  cm=" << cm);
+		options->Get(&sp,"standard_parallel");
+		if (verbose) _printLine_("  sp=" << sp);
+	}
+
+	/*some checks*/
+	if (sgn !=+1 && sgn !=-1) _error_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
+
+	/* Run core computations: */
+	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
+		iret=Exp2Kmlx(filexp,filkml,sgn,cm,sp,holes);
+	else
+		iret=Exp2Kmlx(filexp,filkml,sgn,holes);
+
+	/*Write data: */
+	WriteData(RET_OUT,iret);
+
+	/*Clean-up*/
+	xDelete<char>(choles);
+	xDelete<char>(filkml);
+	xDelete<char>(filexp);
+	delete options;
+
+	/*end module: */
+	MODULEEND();
 }
-
Index: /issm/trunk/src/modules/Exp2Kml/Exp2Kml.h
===================================================================
--- /issm/trunk/src/modules/Exp2Kml/Exp2Kml.h	(revision 13394)
+++ /issm/trunk/src/modules/Exp2Kml/Exp2Kml.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _EXP2KML_H
 
-/* local prototypes: */
-void Exp2KmlUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -18,12 +26,21 @@
 #define __FUNCT__  "Exp2Kml"
 
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define EXP_IN    prhs[0]
-#define KML_IN    prhs[1]
-#define SGN_IN    prhs[2]
-
+#define EXP_IN prhs[0]
+#define KML_IN prhs[1]
+#define SGN_IN prhs[2]
 /* serial output macros: */
 #define RET_OUT    (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define EXP_IN PyTuple_GetItem(args,0)
+#define KML_IN PyTuple_GetItem(args,1)
+#define SGN_IN PyTuple_GetItem(args,2)
+/* serial output macros: */
+#define RET_OUT    output,0
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/HoleFiller/HoleFiller.cpp
===================================================================
--- /issm/trunk/src/modules/HoleFiller/HoleFiller.cpp	(revision 13394)
+++ /issm/trunk/src/modules/HoleFiller/HoleFiller.cpp	(revision 13395)
@@ -10,10 +10,16 @@
 */
 
-
 #include "./HoleFiller.h"
 
-void mexFunction( int nlhs, mxArray* plhs[],
-				  int nrhs, const mxArray* prhs[])
-{
+void HoleFillerUsage(void){/*{{{*/
+	_printLine_("   HoleFiller usage:");
+	_printLine_("   [image_out]=HoleFiller(image_in,smooth);\n");
+	_printLine_("   where:");
+	_printLine_("      image_in in double format");
+	_printLine_("      smooth: 1 to smooth with a box filer, 0 to leave data raw");
+	_printLine_("      image_out in double format");
+	_printLine_("");
+}/*}}}*/
+WRAPPER(HoleFiller){
 
 	int i,j;
@@ -56,14 +62,2 @@
 	MODULEEND();
 }
-
-
-void HoleFillerUsage(void)
-{
-	_printLine_("   HoleFiller usage:");
-	_printLine_("   [image_out]=HoleFiller(image_in,smooth);\n");
-	_printLine_("   where:");
-	_printLine_("      image_in in double format");
-	_printLine_("      smooth: 1 to smooth with a box filer, 0 to leave data raw");
-	_printLine_("      image_out in double format");
-	_printLine_("");
-}
Index: /issm/trunk/src/modules/HoleFiller/HoleFiller.h
===================================================================
--- /issm/trunk/src/modules/HoleFiller/HoleFiller.h	(revision 13394)
+++ /issm/trunk/src/modules/HoleFiller/HoleFiller.h	(revision 13395)
@@ -1,13 +1,19 @@
-
 /*
 	HoleFiller.h
 */
 
-
 #ifndef _HOLEFILLER_H
 #define _HOLEFILLER_H
 
-/* local prototypes: */
-void HoleFillerUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -20,11 +26,19 @@
 #define __FUNCT__  "HoleFiller"
 
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
 #define IMAGEIN prhs[0]
-#define SMOOTH prhs[1]
+#define SMOOTH  prhs[1]
+/* serial output macros: */
+#define IMAGEOUT (mxArray**)&plhs[0]
+#endif
 
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define IMAGEIN PyTuple_GetItem(args,0)
+#define SMOOTH  PyTuple_GetItem(args,1)
 /* serial output macros: */
-#define IMAGEOUT &plhs[0]
+#define IMAGEOUT output,0
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/InternalFront/InternalFront.cpp
===================================================================
--- /issm/trunk/src/modules/InternalFront/InternalFront.cpp	(revision 13394)
+++ /issm/trunk/src/modules/InternalFront/InternalFront.cpp	(revision 13395)
@@ -5,5 +5,10 @@
 #include "./InternalFront.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void InternalFrontUsage(void) {/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("   usage: icefront = " << __FUNCT__ << "(md);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(InternalFront){
 
 	bool*   elementonwater=NULL;
@@ -26,15 +31,15 @@
 	/*Fetch required fields*/
 	FetchData(&numberofelements,mxGetAssignedField(MODEL,0,"numberofelements"));
-	if(numberofelements<=0) _error2_("No elements found in the model");
+	if(numberofelements<=0) _error_("No elements found in the model");
 	FetchData(&elements,&M,&N,mxGetAssignedField(MODEL,0,"elements"));
-	if(M!=numberofelements || N!=3) _error2_("Field 'elements' should be of size [md.numberofelements 3]");
+	if(M!=numberofelements || N!=3) _error_("Field 'elements' should be of size [md.numberofelements 3]");
 	FetchData(&elementonwater,&M,&N,mxGetAssignedField(MODEL,0,"elementonwater"));
-	if(M!=numberofelements || N!=1) _error2_("Field 'elementonwater' should be of size [md.numberofelements 1]");
+	if(M!=numberofelements || N!=1) _error_("Field 'elementonwater' should be of size [md.numberofelements 1]");
 	FetchData(&elementconnectivity,&M,&N,mxGetAssignedField(MODEL,0,"elementconnectivity"));
-	if(M!=numberofelements || N!=3) _error2_("Field 'elementconnectivity' should be of size [md.numberofelements 3]");
+	if(M!=numberofelements || N!=3) _error_("Field 'elementconnectivity' should be of size [md.numberofelements 3]");
 
 	/*Allocate and initialize all variables*/
 	numberofsegments=0;
-	front=(int*)xmalloc(3*numberofelements*4*sizeof(int));
+	front=xNew<int>(3*numberofelements*4);
 
 	/*Loop over all elements on water*/
@@ -81,8 +86,8 @@
 	/*Now that we know how many segments there is we can allocate the final matrix*/
 	if(numberofsegments){
-		front2=(double*)xmalloc(4*numberofsegments*sizeof(double));
+		front2=xNew<double>(4*numberofsegments);
 		for(i=0;i<4*numberofsegments;i++) front2[i]=(double)front[i];
 	}
-	xfree((void**)&front);
+	xDelete<int>(front);
 
 	/*write output datasets: */
@@ -92,8 +97,2 @@
 	MODULEEND();
 }
-
-void InternalFrontUsage(void) {
-	_pprintLine_("");
-	_pprintLine_("   usage: icefront = " << __FUNCT__ << "(md);");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/InternalFront/InternalFront.h
===================================================================
--- /issm/trunk/src/modules/InternalFront/InternalFront.h	(revision 13394)
+++ /issm/trunk/src/modules/InternalFront/InternalFront.h	(revision 13395)
@@ -1,13 +1,19 @@
-
 /*
 	InternalFront.h
 */
 
-
 #ifndef _INTERNALFRONT_H
 #define _INTERNALFRONT_H
 
-/* local prototypes: */
-void InternalFrontUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -19,9 +25,17 @@
 #define __FUNCT__  "InternalFront"
 
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define MODEL (mxArray*)prhs[0]
-
+#define MODEL prhs[0]
 /* serial output macros: */
 #define FRONT (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define MODEL PyTuple_GetItem(args,0)
+/* serial output macros: */
+#define FRONT output,0]
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/InterpFromGridToMesh/InterpFromGridToMesh.cpp
===================================================================
--- /issm/trunk/src/modules/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 13394)
+++ /issm/trunk/src/modules/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 13395)
@@ -1,35 +1,40 @@
 /*!\file InterpFromGridToMesh.c
  * \brief: data interpolation from a list of (x,y,values) into mesh vertices
- 
-	InterpFromGridToMesh.c
-
-	usage:
-	data_mesh=InterpFromGridToMesh(x,y,data,x_mesh,y_mesh);
-	
-	where:
-
-		input:
-		x,y: coordinates of matrix data
-		data - matrix holding the data to be interpolated onto the mesh.
-		x_mesh,y_mesh: coordinates of the mesh vertices onto which we interpolate.
-		
-		output: 
-		data_mesh:  vector of mesh interpolated data.
 */
 	
 #include "./InterpFromGridToMesh.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+void InterpFromGridToMeshUsage(void){/*{{{*/
+	_pprintLine_("INTERPFROMGRIDTOMESH - interpolation from a grid onto a list of points");
+	_pprintLine_("");
+	_pprintLine_("   This function is a multi-threaded mex file that interpolates a field");
+	_pprintLine_("   defined on a grid onto a list of points");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      data_mesh=InterpFromGridToMesh(x,y,data,x_mesh,y_mesh,default_value);");
+	_pprintLine_("");
+	_pprintLine_("      data: matrix holding the data to be interpolated onto the mesh.");
+	_pprintLine_("      x,y: coordinates of matrix data. (x and y must be in increasing order)");
+	_pprintLine_("      x_mesh,y_mesh: coordinates of the points onto which we interpolate.");
+	_pprintLine_("      default_value: default value if no data is found (holes).");
+	_pprintLine_("      data_mesh: vector of mesh interpolated data.");
+	_pprintLine_("");
+	_pprintLine_("   Example:");
+	_pprintLine_("      load('velocities.mat');");
+	_pprintLine_("      md.inversion.vx_obs=InterpFromGridToMesh(x_n,y_m,vx,md.mesh.x,md.mesh.y,0);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(InterpFromGridToMesh){
 
 	int i,j;
 
 	/*input: */
-	double* x=NULL;
-	double* y=NULL;
+	double *x = NULL;
+	double *y = NULL;
 	int     x_rows,y_rows;
-	double* data=NULL; 
+	double *data  = NULL;
 	int     data_rows,data_cols;
-	double* x_mesh=NULL;
-	double* y_mesh=NULL;
+	double *x_mesh = NULL;
+	double *y_mesh = NULL;
 	int     x_mesh_rows,y_mesh_rows;
 	double  default_value;
@@ -37,5 +42,5 @@
 
 	/* output: */
-	Vector*  data_mesh=NULL;
+	SeqVec<double>*  data_mesh=NULL;
 
 	/*Boot module: */
@@ -43,8 +48,7 @@
 
 	/*checks on arguments on the matlab side: */
-	//CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InterpFromGridToMeshUsage);
 	if((nlhs!=NLHS) || (nrhs!=6 && nrhs!=7)){
 		InterpFromGridToMeshUsage();
-		_error2_("usage. See above");
+		_error_("usage. See above");
 	}
 
@@ -72,24 +76,2 @@
 	MODULEEND();
 }
-
-void InterpFromGridToMeshUsage(void)
-{
-	_pprintLine_("INTERPFROMGRIDTOMESH - interpolation from a grid onto a list of points");
-	_pprintLine_("");
-	_pprintLine_("   This function is a multi-threaded mex file that interpolates a field");
-	_pprintLine_("   defined on a grid onto a list of points");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      data_mesh=InterpFromGridToMesh(x,y,data,x_mesh,y_mesh,default_value);");
-	_pprintLine_("");
-	_pprintLine_("      data: matrix holding the data to be interpolated onto the mesh.");
-	_pprintLine_("      x,y: coordinates of matrix data. (x and y must be in increasing order)");
-	_pprintLine_("      x_mesh,y_mesh: coordinates of the points onto which we interpolate.");
-	_pprintLine_("      default_value: default value if no data is found (holes).");
-	_pprintLine_("      data_mesh: vector of mesh interpolated data.");
-	_pprintLine_("");
-	_pprintLine_("   Example:");
-	_pprintLine_("      load('velocities.mat');");
-	_pprintLine_("      md.inversion.vx_obs=InterpFromGridToMesh(x_n,y_m,vx,md.mesh.x,md.mesh.y,0);");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/InterpFromGridToMesh/InterpFromGridToMesh.h
===================================================================
--- /issm/trunk/src/modules/InterpFromGridToMesh/InterpFromGridToMesh.h	(revision 13394)
+++ /issm/trunk/src/modules/InterpFromGridToMesh/InterpFromGridToMesh.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _InterpFromGridToMesh_H
 
-/* local prototypes: */
-void InterpFromGridToMeshUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -18,19 +26,29 @@
 #define __FUNCT__  "InterpFromGridToMesh"
 
-#undef CLEANUP
-#define CLEANUP InterpFromGridToMeshLocalCleanup();
-
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define XHANDLE prhs[0]
-#define YHANDLE prhs[1]
-#define DATAHANDLE prhs[2]
-#define XMESHHANDLE prhs[3]
-#define YMESHHANDLE prhs[4]
+#define XHANDLE       prhs[0]
+#define YHANDLE       prhs[1]
+#define DATAHANDLE    prhs[2]
+#define XMESHHANDLE   prhs[3]
+#define YMESHHANDLE   prhs[4]
 #define DEFAULTHANDLE prhs[5]
-#define INTERPENUM prhs[6]
-
+#define INTERPENUM    prhs[6]
 /* serial output macros: */
 #define DATAMESH (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define XHANDLE       PyTuple_GetItem(args,0)
+#define YHANDLE       PyTuple_GetItem(args,1)
+#define DATAHANDLE    PyTuple_GetItem(args,2)
+#define XMESHHANDLE   PyTuple_GetItem(args,3)
+#define YMESHHANDLE   PyTuple_GetItem(args,4)
+#define DEFAULTHANDLE PyTuple_GetItem(args,5)
+#define INTERPENUM    PyTuple_GetItem(args,6)
+/* serial output macros: */
+#define DATAMESH output,0
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/InterpFromMesh2d/InterpFromMesh2d.cpp
===================================================================
--- /issm/trunk/src/modules/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 13394)
+++ /issm/trunk/src/modules/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 13395)
@@ -1,25 +1,24 @@
 /*!\file InterpFromMesh2d.c
  * \brief: data interpolation from a list of (x,y,values) into mesh vertices
- 
-	InterpFromMesh2d.c
-
-	usage:
-	data_mesh=InterpFromMesh2d(index,x,y,data,x_mesh,y_mesh);
-	
-	where:
-
-		input:
-		x,y: coordinates of matrix data
-		data - matrix holding the data to be interpolated onto the mesh.
-		x_mesh,y_mesh: coordinates of the mesh vertices onto which we interpolate.
-		
-		output: 
-		data_mesh:  vector of mesh interpolated data.
-
 */
 	
 #include "./InterpFromMesh2d.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+void InterpFromMesh2dUsage(void){/*{{{*/
+	_pprintLine_("   usage:");
+	_pprintLine_("         data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime);\n");
+	_pprintLine_("      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value);\n");
+	_pprintLine_("      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value,contourname);\n");
+	_pprintLine_("   where:");
+	_pprintLine_("      x,y: coordinates of the nodes where data is defined");
+	_pprintLine_("      index: index of the mesh where data is defined");
+	_pprintLine_("      data - vector holding the data to be interpolated onto the points.");
+	_pprintLine_("      x_prime,y_prime: coordinates of the mesh vertices onto which we interpolate.");
+	_pprintLine_("      default_value: a scalar or vector of size length(x_prime).");
+	_pprintLine_("      contourname: linear interpolation will happen on all x_interp,y_interp inside the contour, default value will be adopted on the rest of the mesh.");
+	_pprintLine_("      data_prime:  vector of prime interpolated data.");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(InterpFromMesh2d){
 
 	/*input: */
@@ -48,10 +47,10 @@
 	int     num_default_values=0;
 
-	//contours
-	mxArray*  matlabstructure=NULL;
-	Contour** contours=NULL;
-	int       numcontours;
-	Contour*  contouri=NULL;
-	int       i;
+	/*contours*/
+	int i;
+	mxArray *matlabstructure = NULL;
+	Contour<double> **contours=NULL;
+	int numcontours;
+	Contour<double> *contouri=NULL;
 
 	/*Intermediary*/
@@ -61,5 +60,5 @@
 
 	/* output: */
-	Vector*  data_prime=NULL;
+	SeqVec<double> *data_prime = NULL;
 
 	/*Boot module: */
@@ -69,9 +68,9 @@
 	if(nlhs!=NLHS){
 		InterpFromMesh2dUsage();
-		_error2_("InterpFromMeshToMesh2dUsage usage error");
+		_error_("InterpFromMeshToMesh2dUsage usage error");
 	}
 	if((nrhs!=6) && (nrhs!=7) && (nrhs!=8)){
 		InterpFromMesh2dUsage();
-		_error2_("InterpFromMeshToMesh2dUsage usage error");
+		_error_("InterpFromMeshToMesh2dUsage usage error");
 	}
 
@@ -100,8 +99,8 @@
 		/*contours: */
 		numcontours=mxGetNumberOfElements(matlabstructure);
-		contours=(Contour**)xmalloc(numcontours*sizeof(Contour*));
+		contours=xNew<Contour<double> *>(numcontours);
 		for(i=0;i<numcontours;i++){
 			//allocate
-			contouri=(Contour*)xmalloc(sizeof(Contour));
+			contouri=xNew<Contour<double> >(1);
 			//retrieve dimension of this contour.
 			contouri->nods=(int)mxGetScalar(mxGetField(matlabstructure,i,"nods"));
@@ -131,8 +130,8 @@
 	/*some checks*/
 	if (x_data_rows!=y_data_rows){
-		_error2_("vectors x and y should have the same length!");
+		_error_("vectors x and y should have the same length!");
 	}
 	if (x_prime_rows!=y_prime_rows){
-		_error2_("vectors x_prime and y_prime should have the same length!");
+		_error_("vectors x_prime and y_prime should have the same length!");
 	}
 	
@@ -151,19 +150,2 @@
 	MODULEEND();
 }
-
-void InterpFromMesh2dUsage(void)
-{
-	_pprintLine_("   usage:");
-	_pprintLine_("         data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime);\n");
-	_pprintLine_("      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value);\n");
-	_pprintLine_("      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value,contourname);\n");
-	_pprintLine_("   where:");
-	_pprintLine_("      x,y: coordinates of the nodes where data is defined");
-	_pprintLine_("      index: index of the mesh where data is defined");
-	_pprintLine_("      data - vector holding the data to be interpolated onto the points.");
-	_pprintLine_("      x_prime,y_prime: coordinates of the mesh vertices onto which we interpolate.");
-	_pprintLine_("      default_value: a scalar or vector of size length(x_prime).");
-	_pprintLine_("      contourname: linear interpolation will happen on all x_interp,y_interp inside the contour, default value will be adopted on the rest of the mesh.");
-	_pprintLine_("      data_prime:  vector of prime interpolated data.");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/InterpFromMesh2d/InterpFromMesh2d.h
===================================================================
--- /issm/trunk/src/modules/InterpFromMesh2d/InterpFromMesh2d.h	(revision 13394)
+++ /issm/trunk/src/modules/InterpFromMesh2d/InterpFromMesh2d.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _INTERPFROMMESH2D_H
 
-/* local prototypes: */
-void InterpFromMesh2dUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -18,19 +26,31 @@
 #define __FUNCT__  "InterpFromMesh2d"
 
-#undef CLEANUP
-#define CLEANUP InterpFromMesh2dLocalCleanup();
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define INDEXHANDLE prhs[0]
-#define XHANDLE prhs[1]
-#define YHANDLE prhs[2]
-#define DATAHANDLE prhs[3]
-#define XPRIMEHANDLE prhs[4]
-#define YPRIMEHANDLE prhs[5]
+#define INDEXHANDLE   prhs[0]
+#define XHANDLE       prhs[1]
+#define YHANDLE       prhs[2]
+#define DATAHANDLE    prhs[3]
+#define XPRIMEHANDLE  prhs[4]
+#define YPRIMEHANDLE  prhs[5]
 #define DEFAULTHANDLE prhs[6]
-#define FILENAME prhs[7]
-
+#define FILENAME      prhs[7]
 /* serial output macros: */
 #define DATAPRIME (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define INDEXHANDLE   PyTuple_GetItem(args,0)
+#define XHANDLE       PyTuple_GetItem(args,1)
+#define YHANDLE       PyTuple_GetItem(args,2)
+#define DATAHANDLE    PyTuple_GetItem(args,3)
+#define XPRIMEHANDLE  PyTuple_GetItem(args,4)
+#define YPRIMEHANDLE  PyTuple_GetItem(args,5)
+#define DEFAULTHANDLE PyTuple_GetItem(args,6)
+#define FILENAME      PyTuple_GetItem(args,7)
+/* serial output macros: */
+#define DATAPRIME output,0
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp
===================================================================
--- /issm/trunk/src/modules/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 13394)
+++ /issm/trunk/src/modules/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 13395)
@@ -5,5 +5,20 @@
 #include "./InterpFromMeshToGrid.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void InterpFromMeshToGridUsage(void){/*{{{*/
+	_pprintLine_("INTERPFROMMESHTOGRID - interpolation of a data defined on a mesh onto a grid");
+	_pprintLine_("");
+	_pprintLine_("   This function is a multi-threaded mex file that interpolates a field");
+	_pprintLine_("   defined on a triangular mesh onto a regular grid");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      [x_m,y_m,griddata]=InterpFromMeshToGrid(index,x,y,data,xmin,ymax,xposting,yposting,nlines,ncols,default_value)");
+	_pprintLine_("");
+	_pprintLine_("      index,x,y: delaunay triangulation defining the mesh.");
+	_pprintLine_("      meshdata: vertex values of data to be interpolated.");
+	_pprintLine_("      xmin,ymax,posting,nlines,ncols: parameters that define the grid");
+	_pprintLine_("      default_value: value of points located out of the mesh.");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(InterpFromMeshToGrid){
 
 	/*input datasets: */
@@ -61,19 +76,2 @@
 	MODULEEND();
 }
-
-void InterpFromMeshToGridUsage(void)
-{
-	_pprintLine_("INTERPFROMMESHTOGRID - interpolation of a data defined on a mesh onto a grid");
-	_pprintLine_("");
-	_pprintLine_("   This function is a multi-threaded mex file that interpolates a field");
-	_pprintLine_("   defined on a triangular mesh onto a regular grid");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      [x_m,y_m,griddata]=InterpFromMeshToGrid(index,x,y,data,xmin,ymax,xposting,yposting,nlines,ncols,default_value)");
-	_pprintLine_("");
-	_pprintLine_("      index,x,y: delaunay triangulation defining the mesh.");
-	_pprintLine_("      meshdata: vertex values of data to be interpolated.");
-	_pprintLine_("      xmin,ymax,posting,nlines,ncols: parameters that define the grid");
-	_pprintLine_("      default_value: value of points located out of the mesh.");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/InterpFromMeshToGrid/InterpFromMeshToGrid.h
===================================================================
--- /issm/trunk/src/modules/InterpFromMeshToGrid/InterpFromMeshToGrid.h	(revision 13394)
+++ /issm/trunk/src/modules/InterpFromMeshToGrid/InterpFromMeshToGrid.h	(revision 13395)
@@ -1,13 +1,19 @@
-
 /*
 	InterpFromMeshToGrid.h
 */
 
-
 #ifndef _INTERPFROMMESHTOGRID_H
 #define _INTERPFROMMESHTOGRID_H
 
-/* local prototypes: */
-void InterpFromMeshToGridUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -20,21 +26,41 @@
 #define __FUNCT__  "InterpFromMeshToGrid"
 
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define INDEX (mxArray*)prhs[0]
-#define X (mxArray*)prhs[1]
-#define Y (mxArray*)prhs[2]
-#define MESHDATA (mxArray*)prhs[3]
-#define XMIN (mxArray*)prhs[4]
-#define YMAX (mxArray*)prhs[5]
-#define XPOSTING (mxArray*)prhs[6]
-#define YPOSTING (mxArray*)prhs[7]
-#define NLINES (mxArray*)prhs[8]
-#define NCOLS (mxArray*)prhs[9]
-#define DEFAULTVALUE (mxArray*)prhs[10]
-
+#define INDEX        prhs[0]
+#define X            prhs[1]
+#define Y            prhs[2]
+#define MESHDATA     prhs[3]
+#define XMIN         prhs[4]
+#define YMAX         prhs[5]
+#define XPOSTING     prhs[6]
+#define YPOSTING     prhs[7]
+#define NLINES       prhs[8]
+#define NCOLS        prhs[9]
+#define DEFAULTVALUE prhs[10]
 /* serial output macros: */
 #define XM (mxArray**)&plhs[0]
 #define YM (mxArray**)&plhs[1]
 #define GRIDDATA (mxArray**)&plhs[2]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define INDEX        PyTuple_GetItem(args,0)
+#define X            PyTuple_GetItem(args,1)
+#define Y            PyTuple_GetItem(args,2)
+#define MESHDATA     PyTuple_GetItem(args,3)
+#define XMIN         PyTuple_GetItem(args,4)
+#define YMAX         PyTuple_GetItem(args,5)
+#define XPOSTING     PyTuple_GetItem(args,6)
+#define YPOSTING     PyTuple_GetItem(args,7)
+#define NLINES       PyTuple_GetItem(args,8)
+#define NCOLS        PyTuple_GetItem(args,9)
+#define DEFAULTVALUE PyTuple_GetItem(args,10)
+/* serial output macros: */
+#define XM output,0
+#define YM output,1
+#define GRIDDATA output,2
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp
===================================================================
--- /issm/trunk/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 13394)
+++ /issm/trunk/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 13395)
@@ -4,5 +4,28 @@
 #include "./InterpFromMeshToMesh2d.h"
 
-
+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_("");
+}/*}}}*/
 WRAPPER(InterpFromMeshToMesh2d){
 
@@ -28,5 +51,5 @@
 	if(nlhs!=NLHS){
 		InterpFromMeshToMesh2dUsage();
-		_error2_("InterpFromMeshToMesh2dUsage usage error");
+		_error_("InterpFromMeshToMesh2dUsage usage error");
 	}
 	#endif
@@ -34,15 +57,15 @@
 	if(nrhs<NRHS){
 		InterpFromMeshToMesh2dUsage();
-		_error2_("InterpFromMeshToMesh2dUsage usage error");
+		_error_("InterpFromMeshToMesh2dUsage usage error");
 	}
 
 	/*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,prhs);
+	FetchData(&index,&nels_data,&test,INDEX); if(test!=3) _error_("index should have 3 columns");
+	FetchData(&x_data,&nods_data,X);          if(nods_data<3) _error_("there should be at least three points");
+	FetchData(&y_data,&test,Y);               if(test!=nods_data) _error_("vectors x and y should have the same length");
+	FetchData(&data,&M_data,&N_data,DATA);    if(M_data*N_data<1) _error_("data is empty");
+	FetchData(&x_interp,&N_interp,XINTERP);   if(N_interp<1) _error_("no interpolation requested");
+	FetchData(&y_interp,&test,YINTERP);       if(test!=N_interp) _error_("vectors x_interp and y_interp should have the same length");
+	FetchData(&options,NRHS,nrhs,ARGUMENTS);
 
 	/*Run core computations*/
@@ -55,28 +78,2 @@
 	MODULEEND();
 }
-
-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/trunk/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
===================================================================
--- /issm/trunk/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h	(revision 13394)
+++ /issm/trunk/src/modules/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h	(revision 13395)
@@ -9,11 +9,8 @@
 	#include <config.h>
 #else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif
 
-/* local prototypes: */
-void InterpFromMeshToMesh2dUsage(void);
-
-/*If python: this macro needs to come before header files inclusion*/
+/*For python modules: needs to come before header files inclusion*/
 #ifdef _HAVE_PYTHON_
 #define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
@@ -36,11 +33,11 @@
 #ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define INDEX prhs[0]
-#define X prhs[1]
-#define Y prhs[2]
-#define DATA prhs[3]
-#define XINTERP prhs[4]
-#define YINTERP prhs[5]
-
+#define INDEX     prhs[0]
+#define X         prhs[1]
+#define Y         prhs[2]
+#define DATA      prhs[3]
+#define XINTERP   prhs[4]
+#define YINTERP   prhs[5]
+#define ARGUMENTS prhs 
 /* serial output macros: */
 #define DATAINTERP (mxArray**)&plhs[0]
@@ -49,11 +46,11 @@
 #ifdef _HAVE_PYTHON_MODULES_
 /* serial input macros: */
-#define INDEX PyTuple_GetItem(args,0)
-#define X PyTuple_GetItem(args,1)
-#define Y PyTuple_GetItem(args,2)
-#define DATA PyTuple_GetItem(args,3)
-#define XINTERP PyTuple_GetItem(args,4)
-#define YINTERP PyTuple_GetItem(args,5)
-
+#define INDEX          PyTuple_GetItem(args,0)
+#define X              PyTuple_GetItem(args,1)
+#define Y              PyTuple_GetItem(args,2)
+#define DATA           PyTuple_GetItem(args,3)
+#define XINTERP        PyTuple_GetItem(args,4)
+#define YINTERP        PyTuple_GetItem(args,5)
+#define ARGUMENTS args
 /* serial output macros: */
 #define DATAINTERP output,0
Index: /issm/trunk/src/modules/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp
===================================================================
--- /issm/trunk/src/modules/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 13394)
+++ /issm/trunk/src/modules/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 13395)
@@ -1,25 +1,30 @@
 /*!\file InterpFromMeshToMesh3d.c
  * \brief: data interpolation from a list of (x,y,values) into mesh vertices
- 
-	InterpFromMeshToMesh3d.c
-
-	usage:
-	data_mesh=InterpFromMeshToMesh3d(index,x,y,z,data,x_mesh,y_mesh,z_mesh);
-	
-	where:
-
-		input:
-		x,y,z: coordinates of matrix data
-		data - matrix holding the data to be interpolated onto the mesh.
-		x_mesh,y_mesh,z_mesh: coordinates of the mesh vertices onto which we interpolate.
-		
-		output: 
-		data_mesh:  vector of mesh interpolated data.
-
 */
 	
 #include "./InterpFromMeshToMesh3d.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+void InterpFromMeshToMesh3dUsage(void){/*{{{*/
+	_pprintLine_("INTERPFROMMESHTOMESH3D - interpolation from a 3d hexahedron mesh onto a list of point");
+	_pprintLine_("");
+	_pprintLine_("   This function is a multi-threaded mex file that interpolates a field");
+	_pprintLine_("   defined on a triangular mesh onto a list of point");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      data_prime=InterpFromMeshToMesh3d(index,x,y,z,data,x_prime,y_prime,z_prime,default_value);");
+	_pprintLine_("");
+	_pprintLine_("      index: index of the mesh where data is defined");
+	_pprintLine_("      x,y,z: coordinates of the nodes where data is defined");
+	_pprintLine_("      data: matrix holding the data to be interpolated onto the mesh.");
+	_pprintLine_("      x_prime,y_prime,z_prime: coordinates of the points onto which we interpolate.");
+	_pprintLine_("      default_value: default value if no data is found (holes).");
+	_pprintLine_("      data_prime: vector of mesh interpolated data.");
+	_pprintLine_("");
+	_pprintLine_("   Example:");
+	_pprintLine_("      load('temperature.mat');");
+	_pprintLine_("      md.initialization.temperature=InterpFromMeshToMesh3d(index,x,y,z,temperature,md.mesh.x,md.mesh.y,md.mesh.z,253);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(InterpFromMeshToMesh3d){
 
 	/*input: */
@@ -55,5 +60,5 @@
 
 	/* output: */
-	Vector*  data_prime=NULL;
+	SeqVec<double>*  data_prime=NULL;
 
 	/*Boot module: */
@@ -76,8 +81,8 @@
 	/*some checks*/
 	if (x_data_rows!=y_data_rows || x_data_rows!=z_data_rows){
-		_error2_("vectors x, y and z should have the same length!");
+		_error_("vectors x, y and z should have the same length!");
 	}
 	if (x_prime_rows!=y_prime_rows || x_prime_rows!=z_prime_rows){
-		_error2_("vectors x_prime, y_prime and z_prime should have the same length!");
+		_error_("vectors x_prime, y_prime and z_prime should have the same length!");
 	}
 	/*get number of elements and number of nodes in the data*/
@@ -95,25 +100,2 @@
 	MODULEEND();
 }
-
-void InterpFromMeshToMesh3dUsage(void)
-{
-	_pprintLine_("INTERPFROMMESHTOMESH3D - interpolation from a 3d hexahedron mesh onto a list of point");
-	_pprintLine_("");
-	_pprintLine_("   This function is a multi-threaded mex file that interpolates a field");
-	_pprintLine_("   defined on a triangular mesh onto a list of point");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      data_prime=InterpFromMeshToMesh3d(index,x,y,z,data,x_prime,y_prime,z_prime,default_value);");
-	_pprintLine_("");
-	_pprintLine_("      index: index of the mesh where data is defined");
-	_pprintLine_("      x,y,z: coordinates of the nodes where data is defined");
-	_pprintLine_("      data: matrix holding the data to be interpolated onto the mesh.");
-	_pprintLine_("      x_prime,y_prime,z_prime: coordinates of the points onto which we interpolate.");
-	_pprintLine_("      default_value: default value if no data is found (holes).");
-	_pprintLine_("      data_prime: vector of mesh interpolated data.");
-	_pprintLine_("");
-	_pprintLine_("   Example:");
-	_pprintLine_("      load('temperature.mat');");
-	_pprintLine_("      md.initialization.temperature=InterpFromMeshToMesh3d(index,x,y,z,temperature,md.mesh.x,md.mesh.y,md.mesh.z,253);");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
===================================================================
--- /issm/trunk/src/modules/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h	(revision 13394)
+++ /issm/trunk/src/modules/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _INTERPFROMMESH3D_H
 
-/* local prototypes: */
-void InterpFromMeshToMesh3dUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -18,21 +26,33 @@
 #define __FUNCT__  "InterpFromMeshToMesh3d"
 
-#undef CLEANUP
-#define CLEANUP InterpFromMeshToMesh3dLocalCleanup();
-
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define INDEXHANDLE prhs[0]
-#define XHANDLE prhs[1]
-#define YHANDLE prhs[2]
-#define ZHANDLE prhs[3]
-#define DATAHANDLE prhs[4]
-#define XPRIMEHANDLE prhs[5]
-#define YPRIMEHANDLE prhs[6]
-#define ZPRIMEHANDLE prhs[7]
+#define INDEXHANDLE   prhs[0]
+#define XHANDLE       prhs[1]
+#define YHANDLE       prhs[2]
+#define ZHANDLE       prhs[3]
+#define DATAHANDLE    prhs[4]
+#define XPRIMEHANDLE  prhs[5]
+#define YPRIMEHANDLE  prhs[6]
+#define ZPRIMEHANDLE  prhs[7]
 #define DEFAULTHANDLE prhs[8]
-
 /* serial output macros: */
 #define DATAPRIME (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define INDEXHANDLE   PyTuple_GetItem(args,0)
+#define XHANDLE       PyTuple_GetItem(args,1)
+#define YHANDLE       PyTuple_GetItem(args,2)
+#define ZHANDLE       PyTuple_GetItem(args,3)
+#define DATAHANDLE    PyTuple_GetItem(args,4)
+#define XPRIMEHANDLE  PyTuple_GetItem(args,5)
+#define YPRIMEHANDLE  PyTuple_GetItem(args,6)
+#define ZPRIMEHANDLE  PyTuple_GetItem(args,7)
+#define DEFAULTHANDLE PyTuple_GetItem(args,8)
+/* serial output macros: */
+#define DATAPRIME output,0
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/KMLFileRead/KMLFileRead.cpp
===================================================================
--- /issm/trunk/src/modules/KMLFileRead/KMLFileRead.cpp	(revision 13394)
+++ /issm/trunk/src/modules/KMLFileRead/KMLFileRead.cpp	(revision 13395)
@@ -4,5 +4,26 @@
 #include "./KMLFileRead.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void KMLFileReadUsage(void){/*{{{*/
+	_pprintLine_("KMLFileRead - KML file reader module:");
+	_pprintLine_("");
+	_pprintLine_("   This module reads a KML file.");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      [ierror]=KMLFileRead(kmlfile,'param name',param,...);");
+	_pprintLine_("");
+	_pprintLine_("      kmlfile      file name of kml file to be read (char)");
+	_pprintLine_("");
+	_pprintLine_("      echo         echo command (char, optional, 'off'/'on')");
+	_pprintLine_("      deepecho     deep echo command (char, optional, 'off'/'on')");
+	_pprintLine_("      write        write command (char, optional, 'off'/'stdout'/kmlfile)");
+	_pprintLine_("");
+	_pprintLine_("      ierror       return code (non-zero for error)");
+	_pprintLine_("");
+	_pprintLine_("   Examples:");
+	_pprintLine_("      [ierror]=KMLFileRead('file.kml','deepecho','on');");
+	_pprintLine_("      [ierror]=KMLFileRead('filin.kml','echo','on','write','filout.kml');");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(KMLFileRead){
 
 	int i,j,nnodes=0,verbose=1;
@@ -45,8 +66,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		KMLFileReadUsage(); _error2_("KMLFileRead usage error");
+		KMLFileReadUsage(); _error_("KMLFileRead usage error");
 	}
 	if (nrhs < NRHS) {
-		KMLFileReadUsage(); _error2_("KMLFileRead usage error");
+		KMLFileReadUsage(); _error_("KMLFileRead usage error");
 	}
 
@@ -56,7 +77,7 @@
 	FetchData(&options,NRHS,nrhs,prhs);
 
-	options->Get(&echo    ,"echo"    ,"off");
-	options->Get(&deepecho,"deepecho","off");
-	options->Get(&write   ,"write"   ,"off");
+	options->Get(&echo    ,"echo"    ,(char*)"off");
+	options->Get(&deepecho,"deepecho",(char*)"off");
+	options->Get(&write   ,"write"   ,(char*)"off");
 
 	/*some checks*/
@@ -97,7 +118,7 @@
 
 	/*Clean-up*/
-	xfree((void**)&write);
-	xfree((void**)&deepecho);
-	xfree((void**)&echo);
+	xDelete<char>(write);
+	xDelete<char>(deepecho);
+	xDelete<char>(echo);
 	delete options;
 
@@ -105,25 +126,2 @@
 	MODULEEND();
 }
-
-void KMLFileReadUsage(void){
-	_pprintLine_("KMLFileRead - KML file reader module:");
-	_pprintLine_("");
-	_pprintLine_("   This module reads a KML file.");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      [ierror]=KMLFileRead(kmlfile,'param name',param,...);");
-	_pprintLine_("");
-	_pprintLine_("      kmlfile      file name of kml file to be read (char)");
-	_pprintLine_("");
-	_pprintLine_("      echo         echo command (char, optional, 'off'/'on')");
-	_pprintLine_("      deepecho     deep echo command (char, optional, 'off'/'on')");
-	_pprintLine_("      write        write command (char, optional, 'off'/'stdout'/kmlfile)");
-	_pprintLine_("");
-	_pprintLine_("      ierror       return code (non-zero for error)");
-	_pprintLine_("");
-	_pprintLine_("   Examples:");
-	_pprintLine_("      [ierror]=KMLFileRead('file.kml','deepecho','on');");
-	_pprintLine_("      [ierror]=KMLFileRead('filin.kml','echo','on','write','filout.kml');");
-	_pprintLine_("");
-}
-
Index: /issm/trunk/src/modules/KMLFileRead/KMLFileRead.h
===================================================================
--- /issm/trunk/src/modules/KMLFileRead/KMLFileRead.h	(revision 13394)
+++ /issm/trunk/src/modules/KMLFileRead/KMLFileRead.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _KMLFILEREAD_H
 
-/* local prototypes: */
-void KMLFileReadUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -18,10 +26,17 @@
 #define __FUNCT__  "KMLFileRead"
 
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define FILENAME      prhs[0]
-
+#define FILENAME prhs[0]
 /* serial output macros: */
 #define ERRORFLAG (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define FILENAME PyTuple_GetItem(args,0)
+/* serial output macros: */
+#define ERRORFLAG output,0
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/KMLMeshWrite/KMLMeshWrite.cpp
===================================================================
--- /issm/trunk/src/modules/KMLMeshWrite/KMLMeshWrite.cpp	(revision 13394)
+++ /issm/trunk/src/modules/KMLMeshWrite/KMLMeshWrite.cpp	(revision 13395)
@@ -4,5 +4,30 @@
 #include "./KMLMeshWrite.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void KMLMeshWriteUsage(void){/*{{{*/
+	_pprintLine_("KMLMeshWrite - KML mesh writer module:");
+	_pprintLine_("");
+	_pprintLine_("   This module writes the mesh of a model as KML polygons into the specified KML file.");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      ierror=KMLMeshWrite(name,notes,elem,nodecon,lat,long,part,data,cmap,kmlfile);");
+	_pprintLine_("");
+	_pprintLine_("      name       model name (string, may be empty)");
+	_pprintLine_("      notes      model notes (string or cell array of strings, may be empty)");
+	_pprintLine_("      elem       elements (double array)");
+	_pprintLine_("      nodecon    nodal connectivity array (double array, may be empty)");
+	_pprintLine_("      lat        nodal latititudes (double vector)");
+	_pprintLine_("      long       nodal longitudes (double vector)");
+	_pprintLine_("      part       nodal partitions (double vector, may be empty)");
+	_pprintLine_("      data       nodal or element data (double vector, may be empty)");
+	_pprintLine_("      cmap       color map (double nx3 array, may be empty)");
+	_pprintLine_("      kmlfile    KML file name (string)");
+	_pprintLine_("");
+	_pprintLine_("      ierror     error flag (double, non-zero for error)");
+	_pprintLine_("");
+	_pprintLine_("   Example:");
+	_pprintLine_("      KMLMeshWrite(md.name,md.notes,md.elements,md.nodeconnectivity,md.lat,md.long,md.part,md.fm_criterion,options.cmap,filekml);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(KMLMeshWrite){
 
 	int i,j,nnodes=0,verbose=1;
@@ -11,4 +36,5 @@
 	char*   name=NULL;
 	char*   notes=NULL;
+	char*   notes2=NULL;
 	const mxArray* notesi;
 	mwIndex        nindex;
@@ -40,8 +66,8 @@
 	/*checks on arguments on the matlab side: */
 	if (nlhs > NLHS) {
-		KMLMeshWriteUsage(); _error2_("KMLMeshWrite usage error");
+		KMLMeshWriteUsage(); _error_("KMLMeshWrite usage error");
 	}
 	if (nrhs < NRHS) {
-		KMLMeshWriteUsage(); _error2_("KMLMeshWrite usage error");
+		KMLMeshWriteUsage(); _error_("KMLMeshWrite usage error");
 	}
 
@@ -55,10 +81,15 @@
 			if (notesi && mxIsChar(notesi) && mxGetNumberOfElements(notesi)) {
 				if (!notes) {
-					notes=(char *) xmalloc((mxGetNumberOfElements(notesi)+1)*sizeof(char));
+					notes=xNew<char>(mxGetNumberOfElements(notesi)+1);
 					mxGetString(notesi,notes,mxGetNumberOfElements(notesi)+1);
 				}
 				else {
 /*  note that strlen does not include trailing null  */
-					notes=(char*)xrealloc(notes,(strlen(notes)+1+mxGetNumberOfElements(notesi)+1)*sizeof(char));
+					notes2=xNew<char>(strlen(notes)+1+mxGetNumberOfElements(notesi)+1);
+					memcpy(notes2,notes,(strlen(notes)+1)*sizeof(char));
+					xDelete<char>(notes);
+					notes=notes2;
+					notes2=NULL;
+//					notes=(char*)xrealloc(notes,(strlen(notes)+1+mxGetNumberOfElements(notesi)+1)*sizeof(char));
 					strcat(notes,"\n");
 					mxGetString(notesi,&notes[strlen(notes)],mxGetNumberOfElements(notesi)+1);
@@ -87,15 +118,15 @@
 
 	if (nodecon && (mncon != nnodes))
-	  {_error2_("Nodal connectivity table, if supplied, must be supplied for all nodes.");}
+	  {_error_("Nodal connectivity table, if supplied, must be supplied for all nodes.");}
 	else if (!nodecon)
 		mncon=nnodes;
 	if ((llat != nnodes) || (llng != nnodes) || (llat != llng))
-		_error2_("Latitude and longitude vectors must be supplied for all nodes.");
+		_error_("Latitude and longitude vectors must be supplied for all nodes.");
 	if (part && (lprt != nnodes))
-		_error2_("Partitioning vector, if supplied, must be supplied for all nodes.");
+		_error_("Partitioning vector, if supplied, must be supplied for all nodes.");
 	if (data && !((mdata == nnodes) || (mdata == melem)))
-		_error2_("Data matrix, if supplied, must be supplied for all nodes or all elements.");
+		_error_("Data matrix, if supplied, must be supplied for all nodes or all elements.");
 	if (cmap && (ncmap != 3))
-		_error2_("Colormap matrix, if supplied, must have three columns for rgb.");
+		_error_("Colormap matrix, if supplied, must have three columns for rgb.");
 	if (!strlen(filnam))
 		strcpy(filnam,"stdout");
@@ -111,33 +142,7 @@
 	/*Clean-up*/
 	delete options;
-	if (mxIsCell(NOTES) && notes) xfree((void**)&notes);
+	if (mxIsCell(NOTES) && notes) xDelete<char>(notes);
 
 	/*end module: */
 	MODULEEND();
 }
-
-void KMLMeshWriteUsage(void){
-	_pprintLine_("KMLMeshWrite - KML mesh writer module:");
-	_pprintLine_("");
-	_pprintLine_("   This module writes the mesh of a model as KML polygons into the specified KML file.");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      ierror=KMLMeshWrite(name,notes,elem,nodecon,lat,long,part,data,cmap,kmlfile);");
-	_pprintLine_("");
-	_pprintLine_("      name       model name (string, may be empty)");
-	_pprintLine_("      notes      model notes (string or cell array of strings, may be empty)");
-	_pprintLine_("      elem       elements (double array)");
-	_pprintLine_("      nodecon    nodal connectivity array (double array, may be empty)");
-	_pprintLine_("      lat        nodal latititudes (double vector)");
-	_pprintLine_("      long       nodal longitudes (double vector)");
-	_pprintLine_("      part       nodal partitions (double vector, may be empty)");
-	_pprintLine_("      data       nodal or element data (double vector, may be empty)");
-	_pprintLine_("      cmap       color map (double nx3 array, may be empty)");
-	_pprintLine_("      kmlfile    KML file name (string)");
-	_pprintLine_("");
-	_pprintLine_("      ierror     error flag (double, non-zero for error)");
-	_pprintLine_("");
-	_pprintLine_("   Example:");
-	_pprintLine_("      KMLMeshWrite(md.name,md.notes,md.elements,md.nodeconnectivity,md.lat,md.long,md.part,md.fm_criterion,options.cmap,filekml);");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/KMLMeshWrite/KMLMeshWrite.h
===================================================================
--- /issm/trunk/src/modules/KMLMeshWrite/KMLMeshWrite.h	(revision 13394)
+++ /issm/trunk/src/modules/KMLMeshWrite/KMLMeshWrite.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _KMLMESHWRITE_H
 
-/* local prototypes: */
-void KMLMeshWriteUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -18,5 +26,5 @@
 #define __FUNCT__  "KMLMeshWrite"
 
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
 #define NAME          prhs[0]
@@ -30,7 +38,23 @@
 #define CMAPHANDLE    prhs[8]
 #define FILENAME      prhs[9]
-
 /* serial output macros: */
 #define ERRORFLAG (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define NAME          PyTuple_GetItem(args,0)
+#define NOTES         PyTuple_GetItem(args,1)
+#define ELEMHANDLE    PyTuple_GetItem(args,2)
+#define NODECONHANDLE PyTuple_GetItem(args,3)
+#define LATHANDLE     PyTuple_GetItem(args,4)
+#define LNGHANDLE     PyTuple_GetItem(args,5)
+#define PARTHANDLE    PyTuple_GetItem(args,6)
+#define DATAHANDLE    PyTuple_GetItem(args,7)
+#define CMAPHANDLE    PyTuple_GetItem(args,8)
+#define FILENAME      PyTuple_GetItem(args,9)
+/* serial output macros: */
+#define ERRORFLAG output,0
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/KMLOverlay/KMLOverlay.cpp
===================================================================
--- /issm/trunk/src/modules/KMLOverlay/KMLOverlay.cpp	(revision 13394)
+++ /issm/trunk/src/modules/KMLOverlay/KMLOverlay.cpp	(revision 13395)
@@ -4,5 +4,26 @@
 #include "./KMLOverlay.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void KMLOverlayUsage(void){/*{{{*/
+	_pprintLine_("KMLOverlay - KML file overlay module:");
+	_pprintLine_("");
+	_pprintLine_("   This module reads a list of image files and writes a KML or KMZ overlay file.");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      ierror=KMLOverlay(kmlfile,'param name',param,...);");
+	_pprintLine_("");
+	_pprintLine_("      kmlfile     KML or KMZ file name (string)");
+	_pprintLine_("");
+	_pprintLine_("      lataxis     latitude axis (double vector [south north], required)");
+	_pprintLine_("      longaxis    longitude axis (double vector [west east], required)");
+	_pprintLine_("      images      relative or http image file names (string or array of strings or cell array of strings, required)");
+	_pprintLine_("      zip         flag to zip the doc.kml and image files into kmzfile (double, non-zero for kmz)");
+	_pprintLine_("");
+	_pprintLine_("      ierror     error flag (double, non-zero for error)");
+	_pprintLine_("");
+	_pprintLine_("   Example:");
+	_pprintLine_("      KMLOverlay(kmlfile,'lataxis',[south north],'longaxis',[west east],'images',{'file1.png','http://issm/file2.png'},'zip',1);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(KMLOverlay){
 
 	int i,verbose=1;
@@ -31,8 +52,8 @@
 	/*checks on arguments on the matlab side: */
 	if(nlhs>NLHS){
-		KMLOverlayUsage(); _error2_("KMLOverlay usage error");
+		KMLOverlayUsage(); _error_("KMLOverlay usage error");
 	}
 	if(nrhs<NRHS){
-		KMLOverlayUsage(); _error2_("KMLOverlay usage error");
+		KMLOverlayUsage(); _error_("KMLOverlay usage error");
 	}
 
@@ -41,17 +62,17 @@
 	FetchData(&options,NRHS,nrhs,prhs);
 
-	options->Get(&lataxis ,&nlat ,"lataxis" );
+	options->Get(&lataxis ,&nlat ,(char*)"lataxis");
 	if (verbose && lataxis) for (i=0; i<nlat; i++) _printLine_("  lataxis [" << i << "]=" << lataxis[i]);
-	options->Get(&longaxis,&nlong,"longaxis");
+	options->Get(&longaxis,&nlong,(char*)"longaxis");
 	if (verbose && longaxis) for (i=0; i<nlong; i++) _printLine_("  longaxis[" << i << "]=" << longaxis[i]);
-	options->Get(&pimages,&nimages,"images");
+	options->Get(&pimages,&nimages,(char*)"images");
 	if (verbose && pimages) for (i=0; i<nimages; i++) _printLine_("  pimages[" << i << "]=\"" << pimages[i] << "\"");
-	options->Get(&dzip,"zip",0.);
+	options->Get(&dzip,(char*)"zip",0.);
 	if (verbose) _printLine_("  dzip=" << dzip);
 
 	/*some checks*/
-	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 (nlat !=2) _error_("Latitudinal axes \"lataxis\" require two double values, not " << nlat << ".");
+	if (nlong!=2) _error_("Longitudinal axes \"longaxis\" require two double values, not " << nlong << ".");
+	if (!nimages) _error_("No image files provided.");
 
 	if ((int)dzip){
@@ -90,7 +111,7 @@
 		if (verbose) _printLine_(czip);
 
-		if (mexEvalString(czip)) _error2_("Error zipping file \"" << filkmz << "\".");
-		xfree((void**)&czip);
-		xfree((void**)&filkmz);
+		if (mexEvalString(czip)) _error_("Error zipping file \"" << filkmz << "\".");
+		xDelete<char>(czip);
+		xDelete<char>(filkmz);
 	}
 
@@ -100,35 +121,13 @@
 	/*Clean-up*/
 	if (pimages) {
-		for (i=nimages; i>0; i--) xfree((void**)&(pimages[i-1]));
-		xfree((void**)&pimages);
+		for (i=nimages; i>0; i--) xDelete<char>(pimages[i-1]);
+		xDelete<char*>(pimages);
 	}
-	xfree((void**)&longaxis);
-	xfree((void**)&lataxis);
+	xDelete<double>(longaxis);
+	xDelete<double>(lataxis);
+	xDelete<char>(filkml);
 	delete options;
-	xfree((void**)&filkml);
 
 	/*end module: */
 	MODULEEND();
 }
-
-void KMLOverlayUsage(void){
-	_pprintLine_("KMLOverlay - KML file overlay module:");
-	_pprintLine_("");
-	_pprintLine_("   This module reads a list of image files and writes a KML or KMZ overlay file.");
-	_pprintLine_("");
-	_pprintLine_("   Usage:");
-	_pprintLine_("      ierror=KMLOverlay(kmlfile,'param name',param,...);");
-	_pprintLine_("");
-	_pprintLine_("      kmlfile     KML or KMZ file name (string)");
-	_pprintLine_("");
-	_pprintLine_("      lataxis     latitude axis (double vector [south north], required)");
-	_pprintLine_("      longaxis    longitude axis (double vector [west east], required)");
-	_pprintLine_("      images      relative or http image file names (string or array of strings or cell array of strings, required)");
-	_pprintLine_("      zip         flag to zip the doc.kml and image files into kmzfile (double, non-zero for kmz)");
-	_pprintLine_("");
-	_pprintLine_("      ierror     error flag (double, non-zero for error)");
-	_pprintLine_("");
-	_pprintLine_("   Example:");
-	_pprintLine_("      KMLOverlay(kmlfile,'lataxis',[south north],'longaxis',[west east],'images',{'file1.png','http://issm/file2.png'},'zip',1);");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/KMLOverlay/KMLOverlay.h
===================================================================
--- /issm/trunk/src/modules/KMLOverlay/KMLOverlay.h	(revision 13394)
+++ /issm/trunk/src/modules/KMLOverlay/KMLOverlay.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _KMLOVERLAY_H
 
-/* local prototypes: */
-void KMLOverlayUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -18,10 +26,17 @@
 #define __FUNCT__  "KMLOverlay"
 
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define FILENAME      prhs[0]
-
+#define FILENAME  prhs[0]
 /* serial output macros: */
 #define ERRORFLAG (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define FILENAME  PyTuple_GetItem(args,0)
+/* serial output macros: */
+#define ERRORFLAG output,0
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/Kml2Exp/Kml2Exp.cpp
===================================================================
--- /issm/trunk/src/modules/Kml2Exp/Kml2Exp.cpp	(revision 13394)
+++ /issm/trunk/src/modules/Kml2Exp/Kml2Exp.cpp	(revision 13395)
@@ -4,66 +4,5 @@
 #include "./Kml2Exp.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
-
-	int i,verbose=1;
-
-	/*input: */
-	char    *filkml=NULL,*filexp=NULL;
-	int     sgn;
-	Options* options=NULL;
-	double   cm=0.,sp=0.;
-
-	/* output: */
-	int     iret=0;
-
-	/*Boot module: */
-	MODULEBOOT();
-
-	/*checks on arguments on the matlab side: */
-	if (nlhs > NLHS) {
-		Kml2ExpUsage(); _error2_("Kml2Exp usage error");
-	}
-	if (nrhs < NRHS) {
-		Kml2ExpUsage(); _error2_("Kml2Exp usage error");
-	}
-
-	/*Input datasets: */
-	FetchData(&filkml,KML_IN);
-	FetchData(&filexp,EXP_IN);
-	FetchData(&sgn,SGN_IN);
-	FetchData(&options,NRHS,nrhs,prhs);
-
-	/*  defaults are in Ll2xydef, so don't duplicate them here, and only use user values if both have been specified  */
-	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
-		options->Get(&cm,"central_meridian");
-		if (verbose) _printLine_("  cm=" << cm);
-		options->Get(&sp,"standard_parallel");
-		if (verbose) _printLine_("  sp=" << sp);
-	}
-
-	/*some checks*/
-	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: */
-	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
-		iret=Kml2Expx(filkml,filexp,sgn,cm,sp);
-	else
-		iret=Kml2Expx(filkml,filexp,sgn);
-
-	/*Write data: */
-	WriteData(RET_OUT,iret);
-
-	/*Clean-up*/
-	delete options;
-	xfree((void**)&filexp);
-	xfree((void**)&filkml);
-
-	/*end module: */
-	MODULEEND();
-}
-
-void Kml2ExpUsage(void){
+void Kml2ExpUsage(void){/*{{{*/
 	_pprintLine_("Kml2Exp - kml to exp file conversion module:");
 	_pprintLine_("");
@@ -87,4 +26,63 @@
 	_pprintLine_("      [ret]=Kml2Exp('file.kml','file.exp',-1,'central_meridian', 0,'standard_parallel',71);");
 	_pprintLine_("");
+}/*}}}*/
+WRAPPER(Kml2Exp){
+
+	int i,verbose=1;
+
+	/*input: */
+	char    *filkml=NULL,*filexp=NULL;
+	int     sgn;
+	Options* options=NULL;
+	double   cm=0.,sp=0.;
+
+	/* output: */
+	int     iret=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if (nlhs > NLHS) {
+		Kml2ExpUsage(); _error_("Kml2Exp usage error");
+	}
+	if (nrhs < NRHS) {
+		Kml2ExpUsage(); _error_("Kml2Exp usage error");
+	}
+
+	/*Input datasets: */
+	FetchData(&filkml,KML_IN);
+	FetchData(&filexp,EXP_IN);
+	FetchData(&sgn,SGN_IN);
+	FetchData(&options,NRHS,nrhs,prhs);
+
+	/*  defaults are in Ll2xydef, so don't duplicate them here, and only use user values if both have been specified  */
+	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
+		options->Get(&cm,"central_meridian");
+		if (verbose) _printLine_("  cm=" << cm);
+		options->Get(&sp,"standard_parallel");
+		if (verbose) _printLine_("  sp=" << sp);
+	}
+
+	/*some checks*/
+	if (sgn !=+1 && sgn!= -1) _error_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
+
+	/* Run core computations: */
+	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
+		iret=Kml2Expx(filkml,filexp,sgn,cm,sp);
+	else
+		iret=Kml2Expx(filkml,filexp,sgn);
+
+	/*Write data: */
+	WriteData(RET_OUT,iret);
+
+	/*Clean-up*/
+	xDelete<char>(filexp);
+	xDelete<char>(filkml);
+	delete options;
+
+	/*end module: */
+	MODULEEND();
 }
-
Index: /issm/trunk/src/modules/Kml2Exp/Kml2Exp.h
===================================================================
--- /issm/trunk/src/modules/Kml2Exp/Kml2Exp.h	(revision 13394)
+++ /issm/trunk/src/modules/Kml2Exp/Kml2Exp.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _KML2EXP_H
 
-/* local prototypes: */
-void Kml2ExpUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -18,12 +26,21 @@
 #define __FUNCT__  "Kml2Exp"
 
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define KML_IN    prhs[0]
-#define EXP_IN    prhs[1]
-#define SGN_IN    prhs[2]
-
+#define KML_IN prhs[0]
+#define EXP_IN prhs[1]
+#define SGN_IN prhs[2]
 /* serial output macros: */
 #define RET_OUT    (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define KML_IN PyTuple_GetItem(args,0)
+#define EXP_IN PyTuple_GetItem(args,1)
+#define SGN_IN PyTuple_GetItem(args,2)
+/* serial output macros: */
+#define RET_OUT    output,0
+#endif
 
 /* serial arg counts: */
@@ -34,3 +51,2 @@
 
 #endif
-
Index: /issm/trunk/src/modules/Kriging/Kriging.cpp
===================================================================
--- /issm/trunk/src/modules/Kriging/Kriging.cpp	(revision 13394)
+++ /issm/trunk/src/modules/Kriging/Kriging.cpp	(revision 13395)
@@ -4,5 +4,24 @@
 #include "./Kriging.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void KrigingUsage(void){/*{{{*/
+	_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_("");
+}/*}}}*/
+WRAPPER(Kriging){
 
 	/*Outputs*/
@@ -22,13 +41,13 @@
 	/*checks on arguments on the matlab side: */
 	if (nrhs<NRHS || nlhs>NLHS){
-		KrigingUsage(); _error2_("Kriging usage error");
+		KrigingUsage(); _error_("Kriging usage error");
 	}
 
 	/*Fetch inputs: */
 	FetchData(&x,&n_obs,X);
-	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(&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(&x_interp,&M_interp,&N_interp,XINTERP);
-	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(&y_interp,&M,&N,YINTERP);       if(N!=N_interp || M!=M_interp) _error_("x_interp and y_interp should have the same size");
 	FetchData(&options,NRHS,nrhs,prhs);
 
@@ -41,33 +60,14 @@
 
 	/*Free ressources: */
-	xfree((void**)&x);
-	xfree((void**)&y);
-	xfree((void**)&observations);
-	xfree((void**)&x_interp);
-	xfree((void**)&y_interp);
-	xfree((void**)&predictions);
-	xfree((void**)&error);
+	xDelete<double>(x);
+	xDelete<double>(y);
+	xDelete<double>(observations);
+	xDelete<double>(x_interp);
+	xDelete<double>(y_interp);
+	xDelete<double>(predictions);
+	xDelete<double>(error);
+	delete options;
 
 	/*end module: */
 	MODULEEND();
 }
-
-void KrigingUsage(void){
-	_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/trunk/src/modules/Kriging/Kriging.h
===================================================================
--- /issm/trunk/src/modules/Kriging/Kriging.h	(revision 13394)
+++ /issm/trunk/src/modules/Kriging/Kriging.h	(revision 13395)
@@ -1,4 +1,4 @@
 /*
-	KrigingUsage.h
+	Kriging.h
 */
 
@@ -6,6 +6,14 @@
 #define _KRIGING_H_
 
-/* local prototypes: */
-void KrigingUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -16,15 +24,30 @@
 #undef __FUNCT__ 
 #define __FUNCT__  "Kriging"
-    
+
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define X            (mxArray *)prhs[0]
-#define Y            (mxArray *)prhs[1]
-#define OBSERVATIONS (mxArray *)prhs[2]
-#define XINTERP      (mxArray *)prhs[3]
-#define YINTERP      (mxArray *)prhs[4]
+#define X            prhs[0]
+#define Y            prhs[1]
+#define OBSERVATIONS prhs[2]
+#define XINTERP      prhs[3]
+#define YINTERP      prhs[4]
 
 /* serial output macros: */
 #define PREDICTIONS (mxArray**)&plhs[0]
 #define ERROR       (mxArray**)&plhs[1]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define X            PyTuple_GetItem(args,0)
+#define Y            PyTuple_GetItem(args,1)
+#define OBSERVATIONS PyTuple_GetItem(args,2)
+#define XINTERP      PyTuple_GetItem(args,3)
+#define YINTERP      PyTuple_GetItem(args,4)
+
+/* serial output macros: */
+#define PREDICTIONS output,0
+#define ERROR       output,1
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/Ll2xy/Ll2xy.cpp
===================================================================
--- /issm/trunk/src/modules/Ll2xy/Ll2xy.cpp	(revision 13394)
+++ /issm/trunk/src/modules/Ll2xy/Ll2xy.cpp	(revision 13395)
@@ -4,74 +4,5 @@
 #include "./Ll2xy.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
-
-	int i,verbose=1;
-
-	/*input: */
-	double  *lat=NULL,*lon=NULL;
-	int     nlat,nlon,ncoord;
-	int     sgn;
-
-	Options* options=NULL;
-	double   cm=0.,sp=0.;
-
-	/* output: */
-	double  *x=NULL,*y=NULL;
-	int     iret=0;
-
-	/*Boot module: */
-	MODULEBOOT();
-
-	/*checks on arguments on the matlab side: */
-	if (nlhs > NLHS) {
-		Ll2xyUsage(); _error2_("Ll2xy usage error");
-	}
-	if (nrhs < NRHS) {
-		Ll2xyUsage(); _error2_("Ll2xy usage error");
-	}
-
-	/*Input datasets: */
-	FetchData(&lat,&nlat,LAT_IN);
-	FetchData(&lon,&nlon,LON_IN);
-	FetchData(&sgn,SGN_IN);
-	FetchData(&options,NRHS,nrhs,prhs);
-
-	/*  defaults are in Ll2xydef, so don't duplicate them here, and only use user values if both have been specified  */
-	if(options->GetOption("central_meridian") || options->GetOption("standard_parallel")){
-		options->Get(&cm,"central_meridian");
-		if (verbose) _printLine_("  cm=" << cm);
-		options->Get(&sp,"standard_parallel");
-		if (verbose) _printLine_("  sp=" << sp);
-	}
-
-	/*some checks*/
-	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) _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));
-	y=(double*)mxMalloc(ncoord*sizeof(double));
-
-	/* Run core computations: */
-	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
-		iret=Ll2xyx(x,y,lat,lon,ncoord,sgn,cm,sp);
-	else
-		iret=Ll2xyx(x,y,lat,lon,ncoord,sgn);
-
-	/*Write data: */
-	WriteData(X_OUT,x,ncoord);
-	WriteData(Y_OUT,y,ncoord);
-
-	/*Clean-up*/
-	delete options;
-
-	/*end module: */
-	MODULEEND();
-}
-
-void Ll2xyUsage(void){
+void Ll2xyUsage(void){/*{{{*/
 	_pprintLine_("Ll2xy - lat/long to x/y coordinate transformation module:");
 	_pprintLine_("");
@@ -96,3 +27,71 @@
 	_pprintLine_("      [x,y]=Ll2xy(lat,lon,-1,'central_meridian', 0,'standard_parallel',71);");
 	_pprintLine_("");
+}/*}}}*/
+WRAPPER(Ll2xy){
+
+	int i,verbose=1;
+
+	/*input: */
+	double  *lat=NULL,*lon=NULL;
+	int     nlat,nlon,ncoord;
+	int     sgn;
+
+	Options* options=NULL;
+	double   cm=0.,sp=0.;
+
+	/* output: */
+	double  *x=NULL,*y=NULL;
+	int     iret=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if (nlhs > NLHS) {
+		Ll2xyUsage(); _error_("Ll2xy usage error");
+	}
+	if (nrhs < NRHS) {
+		Ll2xyUsage(); _error_("Ll2xy usage error");
+	}
+
+	/*Input datasets: */
+	FetchData(&lat,&nlat,LAT_IN);
+	FetchData(&lon,&nlon,LON_IN);
+	FetchData(&sgn,SGN_IN);
+	FetchData(&options,NRHS,nrhs,prhs);
+
+	/*  defaults are in Ll2xydef, so don't duplicate them here, and only use user values if both have been specified  */
+	if(options->GetOption("central_meridian") || options->GetOption("standard_parallel")){
+		options->Get(&cm,"central_meridian");
+		if (verbose) _printLine_("  cm=" << cm);
+		options->Get(&sp,"standard_parallel");
+		if (verbose) _printLine_("  sp=" << sp);
+	}
+
+	/*some checks*/
+	if (verbose) _printLine_("Checking inputs:");
+	if (nlat != nlon){_error_("Must have same number of lat[" << nlat << "] and lon[" << nlon << "] coordinates.");}
+	else                ncoord=nlat;
+	if (sgn != +1 && sgn != -1) _error_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
+
+	x=(double*)mxMalloc(ncoord*sizeof(double));
+	y=(double*)mxMalloc(ncoord*sizeof(double));
+
+	/* Run core computations: */
+	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
+		iret=Ll2xyx(x,y,lat,lon,ncoord,sgn,cm,sp);
+	else
+		iret=Ll2xyx(x,y,lat,lon,ncoord,sgn);
+
+	/*Write data: */
+	WriteData(X_OUT,x,ncoord);
+	WriteData(Y_OUT,y,ncoord);
+
+	/*Clean-up*/
+	delete options;
+
+	/*end module: */
+	MODULEEND();
 }
Index: /issm/trunk/src/modules/Ll2xy/Ll2xy.h
===================================================================
--- /issm/trunk/src/modules/Ll2xy/Ll2xy.h	(revision 13394)
+++ /issm/trunk/src/modules/Ll2xy/Ll2xy.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _LL2XY_H
 
-/* local prototypes: */
-void Ll2xyUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -18,13 +26,23 @@
 #define __FUNCT__  "Ll2xy"
 
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define LAT_IN prhs[0]
+#define LON_IN prhs[1]
+#define SGN_IN prhs[2]
+/* serial output macros: */
+#define X_OUT (mxArray**)&plhs[0]
+#define Y_OUT (mxArray**)&plhs[1]
+#endif
 
+#ifdef _HAVE_PYTHON_MODULES_
 /* serial input macros: */
-#define LAT_IN    prhs[0]
-#define LON_IN    prhs[1]
-#define SGN_IN    prhs[2]
-
+#define LAT_IN PyTuple_GetItem(args,0)
+#define LON_IN PyTuple_GetItem(args,1)
+#define SGN_IN PyTuple_GetItem(args,2)
 /* serial output macros: */
-#define X_OUT    (mxArray**)&plhs[0]
-#define Y_OUT    (mxArray**)&plhs[1]
+#define X_OUT output,0
+#define Y_OUT output,1
+#endif
 
 /* serial arg counts: */
@@ -35,3 +53,2 @@
 
 #endif
-
Index: /issm/trunk/src/modules/MeshPartition/MeshPartition.cpp
===================================================================
--- /issm/trunk/src/modules/MeshPartition/MeshPartition.cpp	(revision 13394)
+++ /issm/trunk/src/modules/MeshPartition/MeshPartition.cpp	(revision 13395)
@@ -1,28 +1,17 @@
 /*!\file:  MeshPartition.cpp
  * \brief: partition mesh according to number of areas, using Metis library.
-
-	usage:
-	[element_partitioning,node_partitioning]=MeshPartition(model,numareas)
-	
-	%Info needed from model are the following: 
-	%mesh info: 
-	numberofelements,numberofvertices,elements,elements_width
-	%Non-extruded 2d mesh info
-	nel2d,nods2d,elements2d,
-	%Extruded 2d mesh info
-	nel2d_ext,nods2d_ext,elements2d_ext,
-	%Diverse
-	numberoflayers,dim)
-
-	output:
-	vector of partitioning area numbers, for every element.
-	vector of partitioning area numbers, for every node.
 */
 	
 #include "./MeshPartition.h"
 
-
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
-
+void MeshPartitionUsage(void){/*{{{*/
+	_printLine_("   usage:");
+	_printString_("   [element_partitioning,node_partitioning]=MeshPartition(md.mesh,numpartitions)");
+	_printLine_("   where:");
+	_printLine_("      element_partitioning is a vector of partitioning area numbers, for every element.");
+	_printLine_("      node_partitioning is a vector of partitioning area numbers, for every node.");
+	_printLine_("");
+}/*}}}*/
+WRAPPER(MeshPartition){
 
 	/*Indexing: */
@@ -74,10 +63,10 @@
 
 	/*Post process node_partitioning and element_partitioning to be in double format. Metis needed them in int* format: */
-	element_partitioning=(double*)xmalloc(numberofelements*sizeof(double));
+	element_partitioning=xNew<double>(numberofelements);
 	for (i=0;i<numberofelements;i++){
 		element_partitioning[i]=(double)int_element_partitioning[i]+1; //Metis indexing from 0, matlab from 1.
 	}
 	
-	node_partitioning=(double*)xmalloc(numberofvertices*sizeof(double));
+	node_partitioning=xNew<double>(numberofvertices);
 	for (i=0;i<numberofvertices;i++){
 		node_partitioning[i]=(double)int_node_partitioning[i]+1; //Metis indexing from 0, matlab from 1.
@@ -94,11 +83,2 @@
 	MODULEEND();
 }
-
-void MeshPartitionUsage(void){
-	_printLine_("   usage:");
-	_printString_("   [element_partitioning,node_partitioning]=MeshPartition(md.mesh,numpartitions)");
-	_printLine_("   where:");
-	_printLine_("      element_partitioning is a vector of partitioning area numbers, for every element.");
-	_printLine_("      node_partitioning is a vector of partitioning area numbers, for every node.");
-	_printLine_("");
-}
Index: /issm/trunk/src/modules/MeshPartition/MeshPartition.h
===================================================================
--- /issm/trunk/src/modules/MeshPartition/MeshPartition.h	(revision 13394)
+++ /issm/trunk/src/modules/MeshPartition/MeshPartition.h	(revision 13395)
@@ -1,13 +1,19 @@
-
 /*
 	MeshPartition.h
 */
 
-
 #ifndef _MESHPARTITION_H
 #define _MESHPARTITION_H
 
-/* local prototypes: */
-void MeshPartitionUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -17,17 +23,24 @@
 #include "../../c/issm-binding.h"
 
-#undef CLEANUP
-#define CLEANUP MeshPartitionLocalCleanup();
-
 #undef __FUNCT__ 
 #define __FUNCT__  "MeshPartition"
 
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define MODEL (mxArray*)prhs[0]
-#define NUMAREAS (mxArray*)prhs[1]
-
+#define MODEL    prhs[0]
+#define NUMAREAS prhs[1]
 /* serial output macros: */
 #define ELEMENTPARTITIONING (mxArray**)&plhs[0]
 #define NODEPARTITIONING (mxArray**)&plhs[1]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define MODEL    PyTuple_GetItem(args,0)
+#define NUMAREAS PyTuple_GetItem(args,1)
+/* serial output macros: */
+#define ELEMENTPARTITIONING output,0
+#define NODEPARTITIONING output,1
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/MeshProfileIntersection/MeshProfileIntersection.cpp
===================================================================
--- /issm/trunk/src/modules/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 13394)
+++ /issm/trunk/src/modules/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 13395)
@@ -18,5 +18,17 @@
 #include "./MeshProfileIntersection.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+void MeshProfileIntersectionUsage(void){/*{{{*/
+	_printLine_("   usage:");
+	_printLine_("   [segments]=MeshProfileIntersection(index,x,y,filename);");
+	_printLine_("   where:");
+	_printLine_("   input:");
+	_printLine_("        index,x,y is a triangulation");
+	_printLine_("        filename: name of Argus style .exp file containing the segments (can be groups of disconnected segments)");
+	_printLine_("   output:");
+	_printLine_("        segments: array made of x1,y1,x2,y2,element_id lines (x1,y1) and (x2,y2) are segment 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.");
+}/*}}}*/
+WRAPPER(MeshProfileIntersection){
 
 	int i,j;
@@ -34,7 +46,7 @@
 	//contours
 	mxArray*  matlabstructure=NULL;
-	Contour** contours=NULL;
+	Contour<double>** contours=NULL;
 	int       numcontours;
-	Contour*  contouri=NULL;
+	Contour<double>*  contouri=NULL;
 
 	/* output: */
@@ -54,6 +66,6 @@
 	//index
 	FetchData(&double_index,&nel,&dummy,INDEX);
-	if(dummy!=3 && dummy!=6)_error2_("element triangulation should be of 3 or 6 column width!");
-	index=(int*)xmalloc(nel*3*sizeof(int));
+	if(dummy!=3 && dummy!=6)_error_("element triangulation should be of 3 or 6 column width!");
+	index=xNew<int>(nel*3);
 	for(i=0;i<nel;i++){
 		for(j=0;j<3;j++){
@@ -67,8 +79,8 @@
 	//contours
 	numcontours=mxGetNumberOfElements(matlabstructure);
-	contours=(Contour**)xmalloc(numcontours*sizeof(Contour*));
+	contours=xNew<Contour<double>*>(numcontours);
 	for(i=0;i<numcontours;i++){
 		//allocate
-		contouri=(Contour*)xmalloc(sizeof(Contour));
+		contouri=xNew<Contour<double> >(1);
 		//retrieve dimension of this contour.
 		contouri->nods=(int)mxGetScalar(mxGetField(matlabstructure,i,"nods"));
@@ -100,15 +112,2 @@
 
 }
-
-void MeshProfileIntersectionUsage(void){
-	_printLine_("   usage:");
-	_printLine_("   [segments]=MeshProfileIntersection(index,x,y,filename);");
-	_printLine_("   where:");
-	_printLine_("   input:");
-	_printLine_("        index,x,y is a triangulation");
-	_printLine_("        filename: name of Argus style .exp file containing the segments (can be groups of disconnected segments)");
-	_printLine_("   output:");
-	_printLine_("        segments: array made of x1,y1,x2,y2,element_id lines (x1,y1) and (x2,y2) are segment 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/trunk/src/modules/MeshProfileIntersection/MeshProfileIntersection.h
===================================================================
--- /issm/trunk/src/modules/MeshProfileIntersection/MeshProfileIntersection.h	(revision 13394)
+++ /issm/trunk/src/modules/MeshProfileIntersection/MeshProfileIntersection.h	(revision 13395)
@@ -1,13 +1,19 @@
-
 /*
 	MeshProfileIntersection.h
 */
 
-
 #ifndef _MESHPROFILEINTERSECTION_H
 #define _MESHPROFILEINTERSECTION_H
 
-/* local prototypes: */
-void MeshProfileIntersectionUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -20,12 +26,23 @@
 #define __FUNCT__ "MeshProfileIntersection"
 
+#ifdef _HAVE_MATLAB_MODULES_
 /* input macros: */
-#define INDEX prhs[0]
-#define X prhs[1]
-#define Y prhs[2]
+#define INDEX    prhs[0]
+#define X        prhs[1]
+#define Y        prhs[2]
 #define FILENAME prhs[3]
-
 /* serial output macros: */
 #define SEGMENTS (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* input macros: */
+#define INDEX    PyTuple_GetItem(args,0)
+#define X        PyTuple_GetItem(args,1)
+#define Y        PyTuple_GetItem(args,2)
+#define FILENAME PyTuple_GetItem(args,3)
+/* serial output macros: */
+#define SEGMENTS output,0
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/NodeConnectivity/NodeConnectivity.cpp
===================================================================
--- /issm/trunk/src/modules/NodeConnectivity/NodeConnectivity.cpp	(revision 13394)
+++ /issm/trunk/src/modules/NodeConnectivity/NodeConnectivity.cpp	(revision 13395)
@@ -5,4 +5,9 @@
 #include "./NodeConnectivity.h"
 
+void NodeConnectivityUsage(void){/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("   usage: connectivity = " << __FUNCT__ << "(elements, numnodes);");
+	_pprintLine_("");
+}/*}}}*/
 WRAPPER(NodeConnectivity){
 
@@ -35,8 +40,2 @@
 	MODULEEND();
 }
-
-void NodeConnectivityUsage(void) {
-	_pprintLine_("");
-	_pprintLine_("   usage: connectivity = " << __FUNCT__ << "(elements, numnodes);");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/NodeConnectivity/NodeConnectivity.h
===================================================================
--- /issm/trunk/src/modules/NodeConnectivity/NodeConnectivity.h	(revision 13394)
+++ /issm/trunk/src/modules/NodeConnectivity/NodeConnectivity.h	(revision 13395)
@@ -9,11 +9,14 @@
 	#include <config.h>
 #else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif
 
-/*Very important definition in case we are compiling a python module!: needs to come before header files inclusion*/
+/*For python modules: needs to come before header files inclusion*/
 #ifdef _HAVE_PYTHON_
 #define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
 #endif
+
+#undef __FUNCT__ 
+#define __FUNCT__  "NodeConnectivity"
 
 /*Header files: */
@@ -30,6 +33,6 @@
 #ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define ELEMENTS (mxArray*)prhs[0]
-#define NUMNODES (mxArray*)prhs[1]
+#define ELEMENTS prhs[0]
+#define NUMNODES prhs[1]
 /* serial output macros: */
 #define CONNECTIVITY (mxArray**)&plhs[0]
@@ -44,7 +47,4 @@
 #endif
 
-#undef __FUNCT__ 
-#define __FUNCT__  "NodeConnectivity"
-
 /* serial arg counts: */
 #undef NLHS
@@ -53,6 +53,3 @@
 #define NRHS  2
 
-/* local prototypes: */
-void NodeConnectivityUsage(void);
-
 #endif  /* _NODECONNECTIVITY_H */
Index: /issm/trunk/src/modules/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp
===================================================================
--- /issm/trunk/src/modules/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp	(revision 13394)
+++ /issm/trunk/src/modules/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp	(revision 13395)
@@ -5,11 +5,21 @@
 #include "./PointCloudFindNeighbors.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
+void PointCloudFindNeighborsUsage(void){/*{{{*/
+	_printLine_("   usage:");
+	_printLine_("   [flags]=PointCloudFindNeighbors(x,y,mindistance,multithread);\n");
+	_printLine_("   where:");
+	_printLine_("      x,y: list of points.");
+	_printLine_("      mindistance: minimum distance that should exist between points in the cloud.");
+	_printLine_("      multithread: run multithreaded or not. with multithreads, flags can get 1 and 2 values in duplicates.");
+	_printLine_("      flags: array of flags (flag==1 means point is within mindistance of another point)");
+	_printLine_("");
+}/*}}}*/
+WRAPPER(PointCloudFindNeighbors){
 
 	int i,j;
 
 	/* required input: */
-	double* x=NULL;
-	double* y=NULL;
+	double *x = NULL;
+	double *y = NULL;
 	int     nods;
 	double  mindistance;
@@ -17,5 +27,5 @@
 
 	/* output: */
-	Vector*  flags=NULL;
+	SeqVec<double> *flags = NULL;
 
 	/*Boot module: */
@@ -40,13 +50,2 @@
 	MODULEEND();
 }
-
-void PointCloudFindNeighborsUsage(void){
-	_printLine_("   usage:");
-	_printLine_("   [flags]=PointCloudFindNeighbors(x,y,mindistance,multithread);\n");
-	_printLine_("   where:");
-	_printLine_("      x,y: list of points.");
-	_printLine_("      mindistance: minimum distance that should exist between points in the cloud.");
-	_printLine_("      multithread: run multithreaded or not. with multithreads, flags can get 1 and 2 values in duplicates.");
-	_printLine_("      flags: array of flags (flag==1 means point is within mindistance of another point)");
-	_printLine_("");
-}
Index: /issm/trunk/src/modules/PointCloudFindNeighbors/PointCloudFindNeighbors.h
===================================================================
--- /issm/trunk/src/modules/PointCloudFindNeighbors/PointCloudFindNeighbors.h	(revision 13394)
+++ /issm/trunk/src/modules/PointCloudFindNeighbors/PointCloudFindNeighbors.h	(revision 13395)
@@ -1,13 +1,19 @@
-
 /*
 	PointCloudFindNeighbors.h
 */
 
-
 #ifndef _POINTCLOUDFINDNEIGHBORS_H
 #define _POINTCLOUDFINDNEIGHBORS_H
 
-/* local prototypes: */
-void PointCloudFindNeighborsUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -20,17 +26,23 @@
 #define __FUNCT__ "PointCloudFindNeighbors"
 
-
-#ifndef ALL
-#define ALL 0
+#ifdef _HAVE_MATLAB_MODULES_
+/* input macros: */
+#define XHANDLE     prhs[0]
+#define YHANDLE     prhs[1]
+#define MINDISTANCE prhs[2]
+#define MULTITHREAD prhs[3]
+/* serial output macros: */
+#define FLAGS (mxArray**)&plhs[0]
 #endif
 
+#ifdef _HAVE_PYTHON_MODULES_
 /* input macros: */
-#define XHANDLE prhs[0]
-#define YHANDLE prhs[1]
-#define MINDISTANCE prhs[2]
-#define MULTITHREAD prhs[3]
-
+#define XHANDLE     PyTuple_GetItem(args,0)
+#define YHANDLE     PyTuple_GetItem(args,1)
+#define MINDISTANCE PyTuple_GetItem(args,2)
+#define MULTITHREAD PyTuple_GetItem(args,3)
 /* serial output macros: */
-#define FLAGS (mxArray**)&plhs[0]
+#define FLAGS output,0
+#endif
 
 /* serial arg counts: */
@@ -40,5 +52,3 @@
 #define NRHS 4
 
-
 #endif  /* _POINTCLOUDFINDNEIGHBORS_H */
-
Index: /issm/trunk/src/modules/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp
===================================================================
--- /issm/trunk/src/modules/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp	(revision 13394)
+++ /issm/trunk/src/modules/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp	(revision 13395)
@@ -5,5 +5,10 @@
 #include "./PropagateFlagsFromConnectivity.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void PropagateFlagsFromConnectivityUsage(void) {/*{{{*/
+	_printLine_("");
+	_printLine_("   usage: [pool] = " << __FUNCT__ << "(connectivity,pool,index,flags);");;
+	_printLine_("");
+}/*}}}*/
+WRAPPER(PropagateFlagsFromConnectivity){
 
 	/*input/output datasets: */
@@ -34,14 +39,8 @@
 
 	/*Free ressources: */
-	xfree((void**)&connectivity);
-	xfree((void**)&flags);
+	xDelete<double>(connectivity);
+	xDelete<double>(flags);
 
 	/*end module: */
 	MODULEEND();
 }
-
-void PropagateFlagsFromConnectivityUsage(void) {
-	_printLine_("");
-	_printLine_("   usage: [pool] = " << __FUNCT__ << "(connectivity,pool,index,flags);");;
-	_printLine_("");
-}
Index: /issm/trunk/src/modules/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
===================================================================
--- /issm/trunk/src/modules/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h	(revision 13394)
+++ /issm/trunk/src/modules/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h	(revision 13395)
@@ -1,13 +1,19 @@
-
 /*
 	PropagateFlagsFromConnectivity.h
 */
 
-
 #ifndef _PROPAGATEFLAGSFROMCONNECTIVITY_H
 #define _PROPAGATEFLAGSFROMCONNECTIVITY_H
 
-/* local prototypes: */
-void PropagateFlagsFromConnectivityUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -20,12 +26,23 @@
 #define __FUNCT__  "PropagateFlagsFromConnectivity"
 
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define CONNECTIVITY (mxArray*)prhs[0]
-#define POOL (mxArray*)prhs[1]
-#define INDEX (mxArray*)prhs[2]
-#define FLAGS (mxArray*)prhs[3]
-
+#define CONNECTIVITY prhs[0]
+#define POOL         prhs[1]
+#define INDEX        prhs[2]
+#define FLAGS        prhs[3]
 /* serial output macros: */
 #define POOLOUT (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define CONNECTIVITY PyTuple_GetItem(args,0)
+#define POOL         PyTuple_GetItem(args,1)
+#define INDEX        PyTuple_GetItem(args,2)
+#define FLAGS        PyTuple_GetItem(args,3)
+/* serial output macros: */
+#define POOLOUT output,0
+#endif
 
 /* serial arg counts: */
@@ -35,6 +52,3 @@
 #define NRHS  4
 
-
 #endif  /* _PROPAGATEFLAGSFROMCONNECTIVITY_H */
-
-
Index: /issm/trunk/src/modules/Scotch/Scotch.cpp
===================================================================
--- /issm/trunk/src/modules/Scotch/Scotch.cpp	(revision 13394)
+++ /issm/trunk/src/modules/Scotch/Scotch.cpp	(revision 13395)
@@ -8,22 +8,16 @@
 #error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif
-
-
 #include "./Scotch.h"
 
-/******************************/
-/*                            */
-/* This is the main function. */
-/*                            */
-/******************************/
-
-void mexFunction( int nlhs,
-				  mxArray *plhs[],
-				  int nrhs,
-				  const mxArray *prhs[] )
-{
-
-#ifndef _HAVE_SCOTCH_ //only works if scotch library has been compiled in.
-	_error2_("Scotch not available! Cannot carry out Scotch partitioning!");
+void GmapUsage(void){/*{{{*/
+	mexPrintf("\n");
+	mexPrintf("Usage: [maptab]=Scotch(adjmat,vertlb,vertwt,edgewt,archtyp,archpar,\n");
+	mexPrintf("                         Scotch-specific parameters);\n");
+	mexPrintf("\n");
+}/*}}}*/
+void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
+
+	#ifndef _HAVE_SCOTCH_ //only works if scotch library has been compiled in.
+	_error_("Scotch not available! Cannot carry out Scotch partitioning!");
 	#else
 
@@ -42,5 +36,5 @@
 	/* Check for proper number of arguments */
    
-	if      (nrhs == 0 && nlhs == 0) {
+	if (nrhs == 0 && nlhs == 0) {
 		GmapUsage();
 		return;
@@ -254,14 +248,2 @@
 #endif //#ifndef _HAVE_SCOTCH_
 }
-
-void GmapUsage( void )
-{
-
-    mexPrintf("\n");
-    mexPrintf("Usage: [maptab]=Scotch(adjmat,vertlb,vertwt,edgewt,archtyp,archpar,\n");
-    mexPrintf("                         Scotch-specific parameters);\n");
-    mexPrintf("\n");
-
-    return;
-}
-
Index: /issm/trunk/src/modules/Scotch/Scotch.h
===================================================================
--- /issm/trunk/src/modules/Scotch/Scotch.h	(revision 13394)
+++ /issm/trunk/src/modules/Scotch/Scotch.h	(revision 13395)
@@ -6,11 +6,7 @@
 #define _SCOTCH_H
 
-/* local prototypes: */
-void GmapUsage(void);
-
 #include <stdio.h>
 #include <string.h>    /*  strcasecmp  */
 #include <time.h>      /*  clock,time,difftime  */
-
 #include "../../c/include/globals.h"
 #include "../../c/modules/modules.h"
@@ -24,17 +20,16 @@
 /*  Scotch structures and prototypes  */
 #ifdef MATLAB
-		#include "mat.h"
-		#include "mex.h"
-		#include "matrix.h"
+#include "mat.h"
+#include "mex.h"
+#include "matrix.h"
 
-		#define printf mexPrintf
-		#define fprintf(file,...) (file == stdout || file == stderr ? mexPrintf(__VA_ARGS__) : fprintf(file,__VA_ARGS__))
-		#define malloc mxMalloc
-		#define calloc mxCalloc
-		#define realloc mxRealloc
-		#define free mxFree
-		#define exit(status) mexErrMsgTxt("exit=" #status)
+#define printf mexPrintf
+#define fprintf(file,...) (file == stdout || file == stderr ? mexPrintf(__VA_ARGS__) : fprintf(file,__VA_ARGS__))
+#define malloc mxMalloc
+#define calloc mxCalloc
+#define realloc mxRealloc
+#define free mxFree
+#define exit(status) mexErrMsgTxt("exit=" #status)
 #endif
 
-
 #endif  /* _SCOTCH_H */
Index: /issm/trunk/src/modules/Shp2Kml/Shp2Kml.cpp
===================================================================
--- /issm/trunk/src/modules/Shp2Kml/Shp2Kml.cpp	(revision 13394)
+++ /issm/trunk/src/modules/Shp2Kml/Shp2Kml.cpp	(revision 13395)
@@ -11,70 +11,5 @@
 #include "./Shp2Kml.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
-
-	int i,verbose=1;
-
-	/*input: */
-	char    *filshp=NULL,*filkml=NULL;
-	int     sgn;
-	Options* options=NULL;
-	double   cm=0.,sp=0.;
-
-	/* output: */
-	int     iret=0;
-
-	#ifndef _HAVE_SHAPELIB_ //only works if shapelib library has been compiled in.
-	_error2_("Shapelib not available! Cannot carry out shp file translation!");
-	#endif
-
-	/*Boot module: */
-	MODULEBOOT();
-
-	/*checks on arguments on the matlab side: */
-	if (nlhs > NLHS) {
-		Shp2KmlUsage(); _error2_("Shp2Kml usage error");
-	}
-	if (nrhs < NRHS) {
-		Shp2KmlUsage(); _error2_("Shp2Kml usage error");
-	}
-
-	/*Input datasets: */
-	FetchData(&filshp,SHP_IN);
-	FetchData(&filkml,KML_IN);
-	FetchData(&sgn,SGN_IN);
-	FetchData(&options,NRHS,nrhs,prhs);
-
-	/*  defaults are in Xy2lldef, so don't duplicate them here, and only use user values if both have been specified  */
-	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
-		options->Get(&cm,"central_meridian");
-		if (verbose) _printLine_("  cm=" << cm);
-		options->Get(&sp,"standard_parallel");
-		if (verbose) _printLine_("  sp=" << sp);
-	}
-
-	/*some checks*/
-	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: */
-	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
-		iret=Shp2Kmlx(filshp,filkml,sgn,cm,sp);
-	else
-		iret=Shp2Kmlx(filshp,filkml,sgn);
-
-	/*Write data: */
-	WriteData(RET_OUT,iret);
-
-	/*Clean-up*/
-	delete options;
-	xfree((void**)&filkml);
-	xfree((void**)&filshp);
-
-	/*end module: */
-	MODULEEND();
-}
-
-void Shp2KmlUsage(void){
+void Shp2KmlUsage(void){/*{{{*/
 	_pprintLine_("Shp2Kml - shp to kml file conversion module:");
 	_pprintLine_("");
@@ -98,3 +33,67 @@
 	_pprintLine_("      [ret]=Shp2Kml('file.shp','file.kml',-1,'central_meridian', 0,'standard_parallel',71);");
 	_pprintLine_("");
+}/*}}}*/
+WRAPPER(Shp2Kml){
+
+	int i,verbose=1;
+
+	/*input: */
+	char    *filshp=NULL,*filkml=NULL;
+	int     sgn;
+	Options* options=NULL;
+	double   cm=0.,sp=0.;
+
+	/* output: */
+	int     iret=0;
+
+	#ifndef _HAVE_SHAPELIB_ //only works if shapelib library has been compiled in.
+	_error_("Shapelib not available! Cannot carry out shp file translation!");
+	#endif
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if (nlhs > NLHS) {
+		Shp2KmlUsage(); _error_("Shp2Kml usage error");
+	}
+	if (nrhs < NRHS) {
+		Shp2KmlUsage(); _error_("Shp2Kml usage error");
+	}
+
+	/*Input datasets: */
+	FetchData(&filshp,SHP_IN);
+	FetchData(&filkml,KML_IN);
+	FetchData(&sgn,SGN_IN);
+	FetchData(&options,NRHS,nrhs,prhs);
+
+	/*  defaults are in Xy2lldef, so don't duplicate them here, and only use user values if both have been specified  */
+	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
+		options->Get(&cm,"central_meridian");
+		if (verbose) _printLine_("  cm=" << cm);
+		options->Get(&sp,"standard_parallel");
+		if (verbose) _printLine_("  sp=" << sp);
+	}
+
+	/*some checks*/
+	if (sgn < -1 || sgn > +1) _error_("Hemisphere sgn=" << sgn << " must be +1 (north), -1 (south), or 0 (no translation).");
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
+
+	/* Run core computations: */
+	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
+		iret=Shp2Kmlx(filshp,filkml,sgn,cm,sp);
+	else
+		iret=Shp2Kmlx(filshp,filkml,sgn);
+
+	/*Write data: */
+	WriteData(RET_OUT,iret);
+
+	/*Clean-up*/
+	delete options;
+	xDelete<char>(filkml);
+	xDelete<char>(filshp);
+
+	/*end module: */
+	MODULEEND();
 }
Index: /issm/trunk/src/modules/Shp2Kml/Shp2Kml.h
===================================================================
--- /issm/trunk/src/modules/Shp2Kml/Shp2Kml.h	(revision 13394)
+++ /issm/trunk/src/modules/Shp2Kml/Shp2Kml.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _SHP2KML_H
 
-/* local prototypes: */
-void Shp2KmlUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -18,12 +26,21 @@
 #define __FUNCT__  "Shp2Kml"
 
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define SHP_IN  prhs[0]
+#define KML_IN  prhs[1]
+#define SGN_IN  prhs[2]
+/* serial output macros: */
+#define RET_OUT (mxArray**)&plhs[0]
+#endif
 
+#ifdef _HAVE_PYTHON_MODULES_
 /* serial input macros: */
-#define SHP_IN    prhs[0]
-#define KML_IN    prhs[1]
-#define SGN_IN    prhs[2]
-
+#define SHP_IN PyTuple_GetItem(args,0)
+#define KML_IN PyTuple_GetItem(args,1)
+#define SGN_IN PyTuple_GetItem(args,2)
 /* serial output macros: */
-#define RET_OUT    (mxArray**)&plhs[0]
+#define RET_OUT output,0
+#endif
 
 /* serial arg counts: */
Index: /issm/trunk/src/modules/StringToEnum/StringToEnum.cpp
===================================================================
--- /issm/trunk/src/modules/StringToEnum/StringToEnum.cpp	(revision 13394)
+++ /issm/trunk/src/modules/StringToEnum/StringToEnum.cpp	(revision 13395)
@@ -5,13 +5,19 @@
 #include "./StringToEnum.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+void StringToEnumUsage(void){/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("   usage: " << __FUNCT__ << "enum = StringToEnum(string);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(StringToEnum){
 
 	char    *name    = NULL;
 	int      enum_out;
 
-	/*checks on arguments on the matlab side: */
-	if(nrhs!=NRHS){
-		StringToEnumUsage(); _error2_("usage. See above");
-	}
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&StringToEnumUsage);
 
 	/*Fetch inputs: */
@@ -23,10 +29,6 @@
 	/* output: */
 	WriteData(ENUMOUT,enum_out);
+
+	/*end module: */
+	MODULEEND();
 }
-
-void StringToEnumUsage(void)
-{
-	_pprintLine_("");
-	_pprintLine_("   usage: " << __FUNCT__ << "enum = StringToEnum(string);");
-	_pprintLine_("");
-}
Index: /issm/trunk/src/modules/StringToEnum/StringToEnum.h
===================================================================
--- /issm/trunk/src/modules/StringToEnum/StringToEnum.h	(revision 13394)
+++ /issm/trunk/src/modules/StringToEnum/StringToEnum.h	(revision 13395)
@@ -6,7 +6,16 @@
 #define _STRINGTOENUM_H
 
-/* local prototypes: */
-void StringToEnumUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
 
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*Header files: */
 #include "../../c/include/globals.h"
 #include "../../c/modules/modules.h"
@@ -14,10 +23,21 @@
 #include "../../c/shared/shared.h"
 #include "../../c/issm-binding.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "StringToEnum"
     
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
 #define NAME (mxArray*)prhs[0]
-
 /* serial output macros: */
 #define ENUMOUT (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define NAME PyTuple_GetItem(args,0)
+/* serial output macros: */
+#define ENUMOUT output,0
+#endif
 
 /* serial arg counts: */
@@ -27,6 +47,3 @@
 #define NRHS  1
 
-#undef __FUNCT__ 
-#define __FUNCT__  "StringToEnum"
-
 #endif  /* _TEST_H */
Index: /issm/trunk/src/modules/TriMesh/TriMesh.cpp
===================================================================
--- /issm/trunk/src/modules/TriMesh/TriMesh.cpp	(revision 13394)
+++ /issm/trunk/src/modules/TriMesh/TriMesh.cpp	(revision 13395)
@@ -5,21 +5,26 @@
 #include "./TriMesh.h"
 
+void TriMeshUsage(void){/*{{{*/
+	_printLine_("");
+	_printLine_("   usage: [index,x,y,segments,segmentmarkers]=TriMesh(domainoutlinefilename,rifts,area) ");
+	_printLine_("      where: index,x,y defines a triangulation, segments is an array made ");
+	_printLine_("      of exterior segments to the mesh domain outline, segmentmarkers is an array flagging each segment, ");
+	_printLine_("      outlinefilename an Argus domain outline file, ");
+	_printLine_("      area is the maximum area desired for any element of the resulting mesh, ");
+	_printLine_("");
+}/*}}}*/
 WRAPPER(TriMesh){
 	
-	/* input: */
-	char   *domainname = NULL;
-	char   *riftsname  = NULL;
+	/*intermediary: */
 	double  area;
-
-	/*intermediary: */
 	DataSet *domain = NULL;
 	DataSet *rifts  = NULL;
 
 	/* output: */
-	Matrix *index             = NULL;
-	Vector *x                 = NULL;
-	Vector *y                 = NULL;
-	Matrix *segments          = NULL;
-	Vector *segmentmarkerlist = NULL;
+	SeqMat<double> *index             = NULL;
+	SeqVec<double> *x                 = NULL;
+	SeqVec<double> *y                 = NULL;
+	SeqMat<double> *segments          = NULL;
+	SeqVec<double> *segmentmarkerlist = NULL;
 
 	/*Boot module: */
@@ -30,11 +35,7 @@
 	
 	/*Fetch data needed for meshing: */
-	FetchData(&domainname,DOMAINOUTLINE);
-	FetchData(&riftsname,RIFTSOUTLINE);
+	FetchData(&domain,DOMAINOUTLINE);
+	FetchData(&rifts,RIFTSOUTLINE);
 	FetchData(&area,AREA);
-
-	/*Read domain outline: */
-	domain = DomainOutlineRead(domainname);
-	rifts  = DomainOutlineRead(riftsname);
 
 	/*call x core: */
@@ -51,23 +52,11 @@
 	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: */
 	MODULEEND();
 }
-
-void TriMeshUsage(void) //{{{1
-{
-	_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/trunk/src/modules/TriMesh/TriMesh.h
===================================================================
--- /issm/trunk/src/modules/TriMesh/TriMesh.h	(revision 13394)
+++ /issm/trunk/src/modules/TriMesh/TriMesh.h	(revision 13395)
@@ -9,8 +9,8 @@
 	#include <config.h>
 #else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif
 
-/*Very important definition in case we are compiling a python module!: needs to come before header files inclusion*/
+/*For python modules: needs to come before header files inclusion*/
 #ifdef _HAVE_PYTHON_
 #define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
@@ -28,9 +28,12 @@
 #include "../../c/EnumDefinitions/EnumDefinitions.h"
 
+#undef __FUNCT__ 
+#define __FUNCT__  "TriMesh"
+
 #ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
-#define DOMAINOUTLINE  (mxArray *)prhs[0]
-#define RIFTSOUTLINE   (mxArray *)prhs[1]
-#define AREA           (mxArray *)prhs[2]
+#define DOMAINOUTLINE  prhs[0]
+#define RIFTSOUTLINE   prhs[1]
+#define AREA           prhs[2]
 /* serial output macros: */
 #define INDEX             (mxArray**)&plhs[0]
@@ -54,7 +57,4 @@
 #endif
 
-#undef __FUNCT__ 
-#define __FUNCT__  "TriMesh"
-
 /* serial arg counts: */
 #undef NLHS
@@ -63,6 +63,3 @@
 #define NRHS  3
 
-/* local prototypes: */
-void TriMeshUsage(void);
-
 #endif  /* _TRIMESH_H */
Index: /issm/trunk/src/modules/TriMeshProcessRifts/TriMeshProcessRifts.cpp
===================================================================
--- /issm/trunk/src/modules/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 13394)
+++ /issm/trunk/src/modules/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 13395)
@@ -5,23 +5,27 @@
 #include "./TriMeshProcessRifts.h"
 
-void mexFunction(	int nlhs, mxArray* plhs[],
-					int nrhs, const mxArray* prhs[] ) {
-
+void TriMeshProcessRiftsUsage(void){/*{{{*/
+	_printLine_("");
+	_printLine_("   usage: [index2,x2,y2,segments2,segmentmarkers2,rifts2]=TriMeshProcessrifts(index1,x1,y1,segments1,segmentmarkers1) ");
+	_printLine_("      where: (index1,x1,y1,segments1,segmentmarkers1) is an initial triangulation.");
+	_printLine_("      index2,x2,y2,segments2,segmentmarkers2,rifts2 is the resulting triangulation where rifts have been processed.");
+}/*}}}*/
+WRAPPER(TriMeshProcessRifts){
 
 	/*Matlab arrays: */
-	mxArray* pmxa_array=NULL;
-	mxArray* pmxa_array2=NULL;
-	mxArray* pmxa_array3=NULL;
+	mxArray *pmxa_array  = NULL;
+	mxArray *pmxa_array2 = NULL;
+	mxArray *pmxa_array3 = NULL;
 	int i,j,k,counter;
 	
 	/* returned quantities: */
 	int      out_numrifts;
-	int*     out_riftsnumsegments=NULL;
-	double** out_riftssegments=NULL; 
-	int*     out_riftsnumpairs=NULL;
-	double** out_riftspairs=NULL;
-	double*  out_riftstips=NULL;
-	double** out_riftspenaltypairs=NULL;
-	int*     out_riftsnumpenaltypairs=NULL;
+	int     *out_riftsnumsegments     = NULL;
+	double **out_riftssegments        = NULL;
+	int     *out_riftsnumpairs        = NULL;
+	double **out_riftspairs           = NULL;
+	double  *out_riftstips            = NULL;
+	double **out_riftspenaltypairs    = NULL;
+	int     *out_riftsnumpenaltypairs = NULL;
 
 	/*empty rifts structure: */
@@ -34,20 +38,19 @@
 	
 	/* input: */
-	double* tindex_in=NULL;
-	double* index_in=NULL;
+	double *tindex_in = NULL;
+	double *index_in  = NULL;
 	int     nel;
-	double* x_inm=NULL; //matlab vector
-	double* x_in=NULL; //copy of matlab vector
+	double *x_inm = NULL; //matlab vector
+	double *x_in  = NULL; //copy of matlab vector
 	int     nods;
-	double* y_inm=NULL;//matlab vector
-	double* y_in=NULL;//copy of matlab vector
-	double* tsegments_in=NULL;
-	double* segments_in=NULL;
-	double* tsegmentmarkers_in=NULL;
-	double* segmentmarkers_in=NULL;
+	double *y_inm              = NULL; //matlab vector
+	double *y_in               = NULL; //copy of matlab vector
+	double *tsegments_in       = NULL;
+	double *segments_in        = NULL;
+	double *tsegmentmarkers_in = NULL;
+	double *segmentmarkers_in  = NULL;
 
 	/* state: */
-	double* state=NULL;
-
+	double *state = NULL;
 	int     num_seg;
 
@@ -57,5 +60,5 @@
 
 	/* verify correct usage: */
-	if (nlhs==0 && nrhs==0) {
+	if (nlhs==0 && nrhs==0){
 		/* special case: */
 		TriMeshProcessRiftsUsage();
@@ -73,5 +76,5 @@
 		nel=mxGetM(prhs[0]);
 		tindex_in=mxGetPr(prhs[0]);
-		index_in=(double*)xmalloc(nel*3*sizeof(double));
+		index_in=xNew<double>(nel*3);
 		for (i=0;i<nel;i++){
 			for (j=0;j<3;j++){
@@ -88,5 +91,5 @@
 		nods=mxGetM(prhs[1]);
 		x_inm=mxGetPr(prhs[1]);
-		x_in=(double*)xmalloc(nods*sizeof(double));
+		x_in=xNew<double>(nods);
 		for (i=0;i<nods;i++){
 			x_in[i]=x_inm[i];
@@ -100,5 +103,5 @@
 	if(mxIsDouble(prhs[2])){
 		y_inm=mxGetPr(prhs[2]);
-		y_in=(double*)xmalloc(nods*sizeof(double));
+		y_in=xNew<double>(nods);
 		for (i=0;i<nods;i++){
 			y_in[i]=y_inm[i];
@@ -113,5 +116,5 @@
 		num_seg=mxGetM(prhs[3]);
 		tsegments_in=mxGetPr(prhs[3]);
-		segments_in=(double*)xmalloc(num_seg*3*sizeof(double));
+		segments_in=xNew<double>(num_seg*3);
 		for (i=0;i<num_seg;i++){
 			for (j=0;j<3;j++){
@@ -127,5 +130,5 @@
 	if(mxIsDouble(prhs[4])){
 		tsegmentmarkers_in=mxGetPr(prhs[4]);
-		segmentmarkers_in=(double*)xmalloc(num_seg*sizeof(double));
+		segmentmarkers_in=xNew<double>(num_seg);
 		for (i=0;i<num_seg;i++){
 			segmentmarkers_in[i]=tsegmentmarkers_in[i];
@@ -169,41 +172,11 @@
 	/*Output : */
 	WriteData(&plhs[0],index_in,nel,3);
-	//pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
-	//mxSetM(pmxa_array,3);
-	//mxSetN(pmxa_array,nel);
-	//mxSetPr(pmxa_array,index_in);
-	//mexCallMATLAB( 1, &plhs[0], 1, &pmxa_array, "transpose");
-
 	WriteData(&plhs[1],x_in,nods,1);
-	//pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
-	//mxSetM(pmxa_array,1);
-	//mxSetN(pmxa_array,nods);
-	//mxSetPr(pmxa_array,x_in);
-	//mexCallMATLAB( 1, &plhs[1], 1, &pmxa_array, "transpose");
-
 	WriteData(&plhs[2],y_in,nods,1);
-	//pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
-	//mxSetM(pmxa_array,1);
-	//mxSetN(pmxa_array,nods);
-	//mxSetPr(pmxa_array,y_in);
-	//mexCallMATLAB( 1, &plhs[2], 1, &pmxa_array, "transpose");
-
 	WriteData(&plhs[3],segments_in,num_seg,3);
-//pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
-//mxSetM(pmxa_array,3);
-//mxSetN(pmxa_array,num_seg);
-//mxSetPr(pmxa_array,segments_in);
-//mexCallMATLAB( 1, &plhs[3], 1, &pmxa_array, "transpose");
-
 	WriteData(&plhs[4],segmentmarkers_in,num_seg,1);
-	//pmxa_array= mxCreateDoubleMatrix(0,0,mxREAL);
-	//mxSetM(pmxa_array,1);
-	//mxSetN(pmxa_array,num_seg);
-	//mxSetPr(pmxa_array,segmentmarkers_in);
-	//mexCallMATLAB( 1, &plhs[4], 1, &pmxa_array, "transpose");
 
 	if(riftflag){
 		/*Create a structure rifts where if i is a rift number, we have the following fields rifts(i).segments and rifts(i).numsegs: */
-
 		fnames[0] = "numsegs";
 		fnames[1] = "segments";
@@ -225,9 +198,4 @@
 			/*Segments: */
 			WriteData(&pmxa_array3,out_riftssegments[i],out_riftsnumsegments[i],3);
-			//pmxa_array2= mxCreateDoubleMatrix(0,0,mxREAL);
-			//mxSetM(pmxa_array2,3);
-			//mxSetN(pmxa_array2,out_riftsnumsegments[i]);
-			//mxSetPr(pmxa_array2,out_riftssegments[i]);
-			//mexCallMATLAB( 1, &pmxa_array3, 1, &pmxa_array2, "transpose");
 			mxSetField(pmxa_array,i,"segments",pmxa_array3);
 			mxSetField(pmxa_array,i,"numsegs",mxCreateDoubleScalar((double)out_riftsnumsegments[i]));
@@ -235,9 +203,4 @@
 			/*Element pairs: */
 			WriteData(&pmxa_array3,out_riftspairs[i],out_riftsnumpairs[i],2);
-			//pmxa_array2= mxCreateDoubleMatrix(0,0,mxREAL);
-			//mxSetM(pmxa_array2,2);
-			//mxSetN(pmxa_array2,out_riftsnumpairs[i]);
-			//mxSetPr(pmxa_array2,out_riftspairs[i]);
-			//mexCallMATLAB( 1, &pmxa_array3, 1, &pmxa_array2, "transpose");
 			mxSetField(pmxa_array,i,"pairs",pmxa_array3);
 
@@ -254,9 +217,4 @@
 			/*Penalty pairs: */
 			WriteData(&pmxa_array3,out_riftspenaltypairs[i],out_riftsnumpenaltypairs[i],7);
-			//pmxa_array2= mxCreateDoubleMatrix(0,0,mxREAL);
-			//mxSetM(pmxa_array2,7);
-			//mxSetN(pmxa_array2,out_riftsnumpenaltypairs[i]);
-			//mxSetPr(pmxa_array2,out_riftspenaltypairs[i]);
-			//mexCallMATLAB( 1, &pmxa_array3, 1, &pmxa_array2, "transpose");
 			mxSetField(pmxa_array,i,"penaltypairs",pmxa_array3);
 
@@ -293,11 +251,2 @@
 	return;
 }
-
-
-void TriMeshProcessRiftsUsage(void)
-{
-	_printLine_("");
-	_printLine_("   usage: [index2,x2,y2,segments2,segmentmarkers2,rifts2]=TriMeshProcessrifts(index1,x1,y1,segments1,segmentmarkers1) ");
-	_printLine_("      where: (index1,x1,y1,segments1,segmentmarkers1) is an initial triangulation.");
-	_printLine_("      index2,x2,y2,segments2,segmentmarkers2,rifts2 is the resulting triangulation where rifts have been processed.");
-}
Index: /issm/trunk/src/modules/TriMeshProcessRifts/TriMeshProcessRifts.h
===================================================================
--- /issm/trunk/src/modules/TriMeshProcessRifts/TriMeshProcessRifts.h	(revision 13394)
+++ /issm/trunk/src/modules/TriMeshProcessRifts/TriMeshProcessRifts.h	(revision 13395)
@@ -9,5 +9,4 @@
 #include "triangle.h"
 #include "string.h"
-
 #include "../../c/include/globals.h"
 #include "../../c/modules/modules.h"
@@ -17,5 +16,4 @@
 #include "../../c/EnumDefinitions/EnumDefinitions.h"
 
-void TriMeshProcessRiftsUsage(void);
 #undef __FUNCT__ 
 #define __FUNCT__ "TriMeshProcessRifts"
Index: /issm/trunk/src/modules/TriaSearch/TriaSearch.cpp
===================================================================
--- /issm/trunk/src/modules/TriaSearch/TriaSearch.cpp	(revision 13394)
+++ /issm/trunk/src/modules/TriaSearch/TriaSearch.cpp	(revision 13395)
@@ -4,5 +4,15 @@
 #include "./TriaSearch.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
+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_("");
+}/*}}}*/
+WRAPPER(TriaSearch){
 
 	int i;
@@ -49,13 +59,2 @@
 	MODULEEND();
 }
-
-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/trunk/src/modules/TriaSearch/TriaSearch.h
===================================================================
--- /issm/trunk/src/modules/TriaSearch/TriaSearch.h	(revision 13394)
+++ /issm/trunk/src/modules/TriaSearch/TriaSearch.h	(revision 13395)
@@ -5,6 +5,14 @@
 #define _TRIASEARCH_H
 
-/* local prototypes: */
-void TriaSearchUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -17,19 +25,31 @@
 #define __FUNCT__  "TriaSearch"
 
-
+#ifdef _HAVE_MATLAB_MODULES_
 /* serial input macros: */
 #define INDEXHANDLE prhs[0]
-#define XHANDLE prhs[1]
-#define YHANDLE prhs[2]
-#define X0HANDLE prhs[3]
-#define Y0HANDLE prhs[4]
+#define XHANDLE     prhs[1]
+#define YHANDLE     prhs[2]
+#define X0HANDLE    prhs[3]
+#define Y0HANDLE    prhs[4]
 
 /* serial output macros: */
 #define TRIA (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define INDEXHANDLE PyTuple _GetItem(args,0)
+#define XHANDLE     PyTuple _GetItem(args,1)
+#define YHANDLE     PyTuple _GetItem(args,2)
+#define X0HANDLE    PyTuple _GetItem(args,3)
+#define Y0HANDLE    PyTuple _GetItem(args,4)
+
+/* serial output macros: */
+#define TRIA output,0
+#endif
 
 /* serial arg counts: */
 #undef NLHS
 #define NLHS  1
-
 #undef NRHS
 #define NRHS  5
Index: /issm/trunk/src/modules/Xy2ll/Xy2ll.cpp
===================================================================
--- /issm/trunk/src/modules/Xy2ll/Xy2ll.cpp	(revision 13394)
+++ /issm/trunk/src/modules/Xy2ll/Xy2ll.cpp	(revision 13395)
@@ -4,73 +4,5 @@
 #include "./Xy2ll.h"
 
-void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
-
-	int i,verbose=1;
-
-	/*input: */
-	double  *x=NULL,*y=NULL;
-	int     nx,ny,ncoord;
-	int     sgn;
-	Options* options=NULL;
-	double   cm=0.,sp=0.;
-
-	/* output: */
-	double  *lat=NULL,*lon=NULL;
-	int     iret=0;
-
-	/*Boot module: */
-	MODULEBOOT();
-
-	/*checks on arguments on the matlab side: */
-	if (nlhs > NLHS) {
-		Xy2llUsage(); _error2_("Xy2ll usage error");
-	}
-	if (nrhs < NRHS) {
-		Xy2llUsage(); _error2_("Xy2ll usage error");
-	}
-
-	/*Input datasets: */
-	FetchData(&x,&nx,X_IN);
-	FetchData(&y,&ny,Y_IN);
-	FetchData(&sgn,SGN_IN);
-	FetchData(&options,NRHS,nrhs,prhs);
-
-	/*  defaults are in Xy2lldef, so don't duplicate them here, and only use user values if both have been specified  */
-	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
-		options->Get(&cm,"central_meridian");
-		if (verbose) _printLine_("  cm=" << cm);
-		options->Get(&sp,"standard_parallel");
-		if (verbose) _printLine_("  sp=" << sp);
-	}
-
-	/*some checks*/
-	if   (nx != ny){_error2_("Must have same number of x[" << nx << "] and y[" << ny << "] coordinates.");}
-	else            ncoord=nx;
-	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));
-	lon=(double*)mxMalloc(ncoord*sizeof(double));
-
-	/* Run core computations: */
-	if (verbose) _printLine_("Calling core:");
-	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
-		iret=Xy2llx(lat,lon,x,y,ncoord,sgn,cm,sp);
-	else
-		iret=Xy2llx(lat,lon,x,y,ncoord,sgn);
-
-	/*Write data: */
-	WriteData(LAT_OUT,lat,ncoord);
-	WriteData(LON_OUT,lon,ncoord);
-
-	/*Clean-up*/
-	delete options;
-
-	/*end module: */
-	MODULEEND();
-}
-
-void Xy2llUsage(void){
+void Xy2llUsage(void){/*{{{*/
 	_pprintLine_("Xy2ll - x/y to lat/long coordinate transformation module:");
 	_pprintLine_("");
@@ -95,4 +27,70 @@
 	_pprintLine_("      [lat,lon]=Xy2ll(x,y,-1,'central_meridian', 0,'standard_parallel',71);");
 	_pprintLine_("");
+}/*}}}*/
+WRAPPER(Xy2ll){
+
+	int i,verbose=1;
+
+	/*input: */
+	double  *x=NULL,*y=NULL;
+	int     nx,ny,ncoord;
+	int     sgn;
+	Options* options=NULL;
+	double   cm=0.,sp=0.;
+
+	/* output: */
+	double  *lat=NULL,*lon=NULL;
+	int     iret=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if (nlhs > NLHS) {
+		Xy2llUsage(); _error_("Xy2ll usage error");
+	}
+	if (nrhs < NRHS) {
+		Xy2llUsage(); _error_("Xy2ll usage error");
+	}
+
+	/*Input datasets: */
+	FetchData(&x,&nx,X_IN);
+	FetchData(&y,&ny,Y_IN);
+	FetchData(&sgn,SGN_IN);
+	FetchData(&options,NRHS,nrhs,prhs);
+
+	/*  defaults are in Xy2lldef, so don't duplicate them here, and only use user values if both have been specified  */
+	if (options->GetOption("central_meridian") || options->GetOption("standard_parallel")) {
+		options->Get(&cm,"central_meridian");
+		if (verbose) _printLine_("  cm=" << cm);
+		options->Get(&sp,"standard_parallel");
+		if (verbose) _printLine_("  sp=" << sp);
+	}
+
+	/*some checks*/
+	if   (nx != ny){_error_("Must have same number of x[" << nx << "] and y[" << ny << "] coordinates.");}
+	else            ncoord=nx;
+	if (sgn != +1 && sgn != -1) _error_("Hemisphere sgn=" << sgn << " must be +1 (north) or -1 (south).");
+	if (fabs(cm)      > 180.) _error_("Central meridian cm=" << cm << " must be between -180 (west) and +180 (east) degrees.");
+	if (sp < 0. || sp >  90.) _error_("Standard parallel sp=" << sp << " must be between 0 and 90 degrees (in specified hemisphere).");
+
+	lat=(double*)mxMalloc(ncoord*sizeof(double));
+	lon=(double*)mxMalloc(ncoord*sizeof(double));
+
+	/* Run core computations: */
+	if (verbose) _printLine_("Calling core:");
+	if (options->GetOption("central_meridian") && options->GetOption("standard_parallel"))
+		iret=Xy2llx(lat,lon,x,y,ncoord,sgn,cm,sp);
+	else
+		iret=Xy2llx(lat,lon,x,y,ncoord,sgn);
+
+	/*Write data: */
+	WriteData(LAT_OUT,lat,ncoord);
+	WriteData(LON_OUT,lon,ncoord);
+
+	/*Clean-up*/
+	delete options;
+
+	/*end module: */
+	MODULEEND();
 }
-
Index: /issm/trunk/src/modules/Xy2ll/Xy2ll.h
===================================================================
--- /issm/trunk/src/modules/Xy2ll/Xy2ll.h	(revision 13394)
+++ /issm/trunk/src/modules/Xy2ll/Xy2ll.h	(revision 13395)
@@ -6,6 +6,14 @@
 #define _XY2LL_H
 
-/* local prototypes: */
-void Xy2llUsage(void);
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
 
 #include "../../c/include/globals.h"
@@ -18,13 +26,23 @@
 #define __FUNCT__  "Xy2ll"
 
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define X_IN   prhs[0]
+#define Y_IN   prhs[1]
+#define SGN_IN prhs[2]
+/* serial output macros: */
+#define LAT_OUT (mxArray**)&plhs[0]
+#define LON_OUT (mxArray**)&plhs[1]
+#endif
 
+#ifdef _HAVE_PYTHON_MODULES_
 /* serial input macros: */
-#define X_IN      prhs[0]
-#define Y_IN      prhs[1]
-#define SGN_IN    prhs[2]
-
+#define X_IN   PyTuple_GetItem(args,0)
+#define Y_IN   PyTuple_GetItem(args,1)
+#define SGN_IN PyTuple_GetItem(args,2)
 /* serial output macros: */
-#define LAT_OUT    (mxArray**)&plhs[0]
-#define LON_OUT    (mxArray**)&plhs[1]
+#define LAT_OUT output,0
+#define LON_OUT output,1
+#endif
 
 /* serial arg counts: */
@@ -35,3 +53,2 @@
 
 #endif
-
Index: /issm/trunk/src/modules/matlab/Makefile.am
===================================================================
--- /issm/trunk/src/modules/matlab/Makefile.am	(revision 13394)
+++ /issm/trunk/src/modules/matlab/Makefile.am	(revision 13395)
@@ -1,45 +1,61 @@
-INCLUDES = @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
+AM_CPPFLAGS = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@ @ADOLCINCL@
+
 EXEEXT=$(MATLABWRAPPEREXT)
-#Bin programs {{{1
+
+#Modules {{{
 if MODULES
-bin_PROGRAMS =  AverageFilter\
-				BamgMesher\
-				BamgConvertMesh\
-				BamgTriangulate\
-				Chaco\
-				ContourToMesh \
-				ContourToNodes \
-				ElementConnectivity\
-				EnumToString\
-				Exp2Kml \
-				HoleFiller \
-				InternalFront\
-				InterpFromGridToMesh \
-				InterpFromMeshToMesh2d \
-				InterpFromMeshToMesh3d \
-				InterpFromMeshToGrid \
-				InterpFromMesh2d \
-				KMLFileRead \
-				KMLMeshWrite \
-				KMLOverlay \
-				Kml2Exp \
-				Kriging \
-				Ll2xy \
-				NodeConnectivity \
-				MeshPartition\
-				MeshProfileIntersection\
-				PointCloudFindNeighbors\
-				PropagateFlagsFromConnectivity\
-				Scotch\
-				Shp2Kml\
-				StringToEnum\
-				TriaSearch\
-				TriMesh\
-				TriMeshProcessRifts\
-				Xy2ll
+lib_LTLIBRARIES =  AverageFilter.la\
+						 BamgMesher.la\
+						 BamgConvertMesh.la\
+						 BamgTriangulate.la\
+						 ContourToMesh.la\
+						 ContourToNodes.la\
+						 ElementConnectivity.la\
+						 EnumToString.la\
+						 HoleFiller.la\
+						 InternalFront.la\
+						 InterpFromGridToMesh.la\
+						 InterpFromMeshToMesh2d.la\
+						 InterpFromMeshToMesh3d.la\
+						 InterpFromMeshToGrid.la\
+						 InterpFromMesh2d.la\
+						 Ll2xy.la\
+						 NodeConnectivity.la\
+						 MeshPartition.la\
+						 MeshProfileIntersection.la\
+						 PointCloudFindNeighbors.la\
+						 PropagateFlagsFromConnectivity.la\
+						 StringToEnum.la\
+						 TriaSearch.la\
+						 TriMesh.la\
+						 TriMeshProcessRifts.la\
+						 Scotch.la\
+						 Xy2ll.la\
+						 Chaco.la
+
+if KRIGING
+lib_LTLIBRARIES +=  Kriging.la
+endif
+if KML
+lib_LTLIBRARIES +=  KMLFileRead.la\
+				   KMLMeshWrite.la\
+				   KMLOverlay.la\
+				   Shp2Kml.la\
+				   Exp2Kml.la\
+				   Kml2Exp.la
+endif
 endif 
+
 #}}}
-#Flags and libraries {{{1
-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)
+#Flags and libraries {{{
+if SHAREDLIBS
+deps = ../../c/libISSMCore.la ../../c/libISSMModules.la
+else
+deps = ../../c/libISSMCore.a ../../c/libISSMModules.a
+endif
+
+deps +=  $(MATHLIB) ${MEXLIB}
+
+#$(TRIANGLELIB) $(PETSCLIB) $(FLIBS) $(PLAPACKLIB) $(SPOOLESLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MPILIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(SHAPELIBLIB) $(GSLLIB) 
 
 #Triangle library
@@ -47,120 +63,178 @@
 
 #Matlab part
-AM_LDFLAGS   = $(MEXLINK)
+AM_LDFLAGS = $(MEXLINK) -shrext ${EXEEXT} -module
+if VERSION
+AM_LDFLAGS +=
+else
+AM_LDFLAGS += -avoid-version
+endif
+if SHAREDLIBS
+deps += ../../c/libISSMMatlab.la 
+else
+deps += ../../c/libISSMMatlab.a
+AM_LDFLAGS += --no-warnings 
+endif
+
 AM_CXXFLAGS +=  -D_HAVE_MATLAB_MODULES_ -D_GNU_SOURCE -fPIC -fno-omit-frame-pointer -pthread 
-LDADD       += $(MEXLIB) ../../c/libISSMMatlab.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
+
+######################################################################################
+# Circular dependencies may not be necessary here.
+#deps += ../../c/libISSMCore.a 
+#if CIRCULAR_DEPENDENCIES
+#deps += $(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
+######################################################################################
+
+if SHAREDLIBS
+deps +=
+else
+deps += ../../c/libISSMModules.a ../../c/libISSMCore.a  
+if ADOLC
+deps += $(ADOLCLIB)
+endif
+endif
 
 #Optimization flags:
 AM_CXXFLAGS += $(CXXOPTFLAGS) 
 #}}}
-#Bin sources {{{1
-AverageFilter_SOURCES = ../AverageFilter/AverageFilter.cpp\
-			  ../AverageFilter/AverageFilter.h
-
-BamgMesher_SOURCES = ../BamgMesher/BamgMesher.cpp\
-					../BamgMesher/BamgMesher.h
-
-BamgConvertMesh_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
-					../BamgConvertMesh/BamgConvertMesh.h
-
-BamgTriangulate_SOURCES = ../BamgTriangulate/BamgTriangulate.cpp\
-								  ../BamgTriangulate/BamgTriangulate.h
-
-Chaco_SOURCES = ../Chaco/Chaco.cpp\
-					../Chaco/Chaco.h
-
-ContourToMesh_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
-			  ../ContourToMesh/ContourToMesh.h
-
-ContourToNodes_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
-			  ../ContourToNodes/ContourToNodes.h
-
-ElementConnectivity_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
-			  ../ElementConnectivity/ElementConnectivity.h
-
-EnumToString_SOURCES = ../EnumToString/EnumToString.cpp\
-			  ../EnumToString/EnumToString.h
-
-StringToEnum_SOURCES = ../StringToEnum/StringToEnum.cpp\
-			  ../StringToEnum/StringToEnum.h
-
-HoleFiller_SOURCES = ../HoleFiller/HoleFiller.cpp\
-			  ../HoleFiller/HoleFiller.h
-
-InternalFront_SOURCES = ../InternalFront/InternalFront.cpp\
-										 ../InternalFront/InternalFront.h
-
-InterpFromGridToMesh_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
-			  ../InterpFromGridToMesh/InterpFromGridToMesh.h
-
-InterpFromMeshToMesh2d_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
-							../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
-
-InterpFromMeshToMesh3d_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp\
-									../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
-
-InterpFromMeshToGrid_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp\
-									../InterpFromMeshToGrid/InterpFromMeshToGrid.h
-
-InterpFromMesh2d_SOURCES = ../InterpFromMesh2d/InterpFromMesh2d.cpp\
-									../InterpFromMesh2d/InterpFromMesh2d.h
-
-KMLFileRead_SOURCES = ../KMLFileRead/KMLFileRead.cpp\
-			  ../KMLFileRead/KMLFileRead.h
-
-KMLMeshWrite_SOURCES = ../KMLMeshWrite/KMLMeshWrite.cpp\
-			  ../KMLMeshWrite/KMLMeshWrite.h
-
-KMLOverlay_SOURCES = ../KMLOverlay/KMLOverlay.cpp\
-			  ../KMLOverlay/KMLOverlay.h
-
-Xy2ll_SOURCES = ../Xy2ll/Xy2ll.cpp\
-			  ../Xy2ll/Xy2ll.h
-
-Ll2xy_SOURCES = ../Ll2xy/Ll2xy.cpp\
-			  ../Ll2xy/Ll2xy.h
-
-Exp2Kml_SOURCES = ../Exp2Kml/Exp2Kml.cpp\
-			  ../Exp2Kml/Exp2Kml.h
-
-Kml2Exp_SOURCES = ../Kml2Exp/Kml2Exp.cpp\
-			  ../Kml2Exp/Kml2Exp.h
-
-Kriging_SOURCES = ../Kriging/Kriging.cpp\
-						../Kriging/Kriging.h
-
-MeshPartition_SOURCES = ../MeshPartition/MeshPartition.cpp\
-			  ../MeshPartition/MeshPartition.h
-
-MeshProfileIntersection_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
-			  ../MeshProfileIntersection/MeshProfileIntersection.h
-
-NodeConnectivity_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
+#Bin sources {{{
+AverageFilter_la_SOURCES = ../AverageFilter/AverageFilter.cpp\
+									../AverageFilter/AverageFilter.h
+AverageFilter_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp\
+								../BamgMesher/BamgMesher.h
+BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+BamgConvertMesh_la_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
+									  ../BamgConvertMesh/BamgConvertMesh.h
+BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+BamgTriangulate_la_SOURCES = ../BamgTriangulate/BamgTriangulate.cpp\
+									  ../BamgTriangulate/BamgTriangulate.h
+BamgTriangulate_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Chaco_la_SOURCES = ../Chaco/Chaco.cpp\
+						 ../Chaco/Chaco.h
+Chaco_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(CHACOLIB)
+
+ContourToMesh_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
+									../ContourToMesh/ContourToMesh.h
+ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+ContourToNodes_la_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
+									 ../ContourToNodes/ContourToNodes.h
+ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+ElementConnectivity_la_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
+											../ElementConnectivity/ElementConnectivity.h
+ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+EnumToString_la_SOURCES = ../EnumToString/EnumToString.cpp\
+								  ../EnumToString/EnumToString.h
+EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+StringToEnum_la_SOURCES = ../StringToEnum/StringToEnum.cpp\
+								  ../StringToEnum/StringToEnum.h
+StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+HoleFiller_la_SOURCES = ../HoleFiller/HoleFiller.cpp\
+								../HoleFiller/HoleFiller.h
+HoleFiller_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) 
+
+InternalFront_la_SOURCES = ../InternalFront/InternalFront.cpp\
+									../InternalFront/InternalFront.h
+InternalFront_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+InterpFromGridToMesh_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
+											 ../InterpFromGridToMesh/InterpFromGridToMesh.h
+InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+InterpFromMeshToMesh2d_la_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
+												../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
+InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+InterpFromMeshToMesh3d_la_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp\
+												../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
+InterpFromMeshToMesh3d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+InterpFromMeshToGrid_la_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp\
+											 ../InterpFromMeshToGrid/InterpFromMeshToGrid.h
+InterpFromMeshToGrid_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+InterpFromMesh2d_la_SOURCES = ../InterpFromMesh2d/InterpFromMesh2d.cpp\
+										../InterpFromMesh2d/InterpFromMesh2d.h
+InterpFromMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+KMLFileRead_la_SOURCES = ../KMLFileRead/KMLFileRead.cpp\
+								 ../KMLFileRead/KMLFileRead.h
+KMLFileRead_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+KMLMeshWrite_la_SOURCES = ../KMLMeshWrite/KMLMeshWrite.cpp\
+								  ../KMLMeshWrite/KMLMeshWrite.h
+KMLMeshWrite_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+KMLOverlay_la_SOURCES = ../KMLOverlay/KMLOverlay.cpp\
+								../KMLOverlay/KMLOverlay.h
+KMLOverlay_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Xy2ll_la_SOURCES = ../Xy2ll/Xy2ll.cpp\
+						 ../Xy2ll/Xy2ll.h
+Xy2ll_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Ll2xy_la_SOURCES = ../Ll2xy/Ll2xy.cpp\
+						 ../Ll2xy/Ll2xy.h
+Ll2xy_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Exp2Kml_la_SOURCES = ../Exp2Kml/Exp2Kml.cpp\
+							../Exp2Kml/Exp2Kml.h
+Exp2Kml_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Kml2Exp_la_SOURCES = ../Kml2Exp/Kml2Exp.cpp\
+							../Kml2Exp/Kml2Exp.h
+Kml2Exp_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Kriging_la_SOURCES = ../Kriging/Kriging.cpp\
+							../Kriging/Kriging.h
+Kriging_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MULTITHREADINGLIB)
+
+MeshPartition_la_SOURCES = ../MeshPartition/MeshPartition.cpp\
+									../MeshPartition/MeshPartition.h
+MeshPartition_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(METISLIB)
+
+MeshProfileIntersection_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
+												 ../MeshProfileIntersection/MeshProfileIntersection.h
+MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+NodeConnectivity_la_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
 										../NodeConnectivity/NodeConnectivity.h
-
-PointCloudFindNeighbors_SOURCES = ../PointCloudFindNeighbors/PointCloudFindNeighbors.cpp\
-			  ../PointCloudFindNeighbors/PointCloudFindNeighbors.h
-
-PropagateFlagsFromConnectivity_SOURCES = ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp\
-			  ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
-
-Scotch_SOURCES = ../Scotch/Scotch.cpp\
-			  ../Scotch/Scotch.h
-
-Shp2Kml_SOURCES = ../Shp2Kml/Shp2Kml.cpp\
-			  ../Shp2Kml/Shp2Kml.h
-
-TriaSearch_SOURCES = ../TriaSearch/TriaSearch.cpp\
-			  ../TriaSearch/TriaSearch.h
-
-TriMesh_SOURCES = ../TriMesh/TriMesh.cpp\
-			  ../TriMesh/TriMesh.h
-
-TriMeshProcessRifts_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
-			  ../TriMeshProcessRifts/TriMeshProcessRifts.h
+NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+PointCloudFindNeighbors_la_SOURCES = ../PointCloudFindNeighbors/PointCloudFindNeighbors.cpp\
+												 ../PointCloudFindNeighbors/PointCloudFindNeighbors.h
+PointCloudFindNeighbors_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+PropagateFlagsFromConnectivity_la_SOURCES = ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp\
+														  ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
+PropagateFlagsFromConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+Scotch_la_SOURCES = ../Scotch/Scotch.cpp\
+						  ../Scotch/Scotch.h
+Scotch_la_LIBADD = ${deps} $(SCOTCHLIB)
+
+Shp2Kml_la_SOURCES = ../Shp2Kml/Shp2Kml.cpp\
+							../Shp2Kml/Shp2Kml.h
+Shp2Kml_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB)
+
+TriaSearch_la_SOURCES = ../TriaSearch/TriaSearch.cpp\
+								../TriaSearch/TriaSearch.h
+TriaSearch_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+TriMesh_la_SOURCES = ../TriMesh/TriMesh.cpp\
+							../TriMesh/TriMesh.h
+TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB)
+
+TriMeshProcessRifts_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
+											../TriMeshProcessRifts/TriMeshProcessRifts.h
+TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
 #}}}
Index: /issm/trunk/src/modules/python/Makefile.am
===================================================================
--- /issm/trunk/src/modules/python/Makefile.am	(revision 13394)
+++ /issm/trunk/src/modules/python/Makefile.am	(revision 13395)
@@ -1,14 +1,27 @@
-INCLUDES = @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
+AM_CPPFLAGS = @DAKOTAINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
+
 EXEEXT=$(PYTHONWRAPPEREXT)
-#Bin programs {{{1
+
+#Modules {{{
 if MODULES
-bin_PROGRAMS = ElementConnectivity\
-			   InterpFromMeshToMesh2d \
-			   NodeConnectivity\
-			   TriMesh 
+lib_LTLIBRARIES = BamgConvertMesh.la\
+						BamgMesher.la\
+						ContourToNodes.la\
+						ElementConnectivity.la\
+						EnumToString.la\
+						InterpFromMeshToMesh2d.la\
+						NodeConnectivity.la\
+						StringToEnum.la\
+						TriMesh.la
 endif 
 #}}}
-#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)
+#Flags and libraries {{{
+if SHAREDLIBS
+deps = ../../c/libISSMCore.la ../../c/libISSMModules.la
+else
+deps = ../../c/libISSMCore.a ../../c/libISSMModules.a
+endif
+
+deps +=  $(MATHLIB) ${PYTHONLIB}
 
 #Triangle library
@@ -16,27 +29,66 @@
 
 #Python part
-AM_LDFLAGS   = $(PYTHONLINK)
+AM_LDFLAGS   = $(PYTHONLINK) -shrext ${EXEEXT} -module
+if VERSION
+AM_LDFLAGS +=
+else
+AM_LDFLAGS += -avoid-version
+endif
+if SHAREDLIBS
+deps += ../../c/libISSMPython.la 
+else
+deps += ../../c/libISSMPython.a
+AM_LDFLAGS += --no-warnings 
+endif
+
 AM_CXXFLAGS +=  -D_HAVE_PYTHON_MODULES_  -fPIC
 if PYTHON3
 AM_CXXFLAGS +=  -DNPY_NO_DEPRECATED_API 
 endif
-LDADD       += $(BOOSTLIB) $(PYTHONLIB) ../../c/libISSMPython.a
 
-LDADD       += ../../c/libISSMCore.a ../../c/libISSMModules.a 
+if SHAREDLIBS
+deps +=
+else
+deps += ../../c/libISSMModules.a ../../c/libISSMCore.a
+endif
 
 #Optimization flags:
 AM_CXXFLAGS += $(CXXOPTFLAGS) 
 #}}}
-#Bin sources {{{1
-ElementConnectivity_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
-			  ../ElementConnectivity/ElementConnectivity.h
+#Bin sources {{{
+BamgConvertMesh_la_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
+									  ../BamgConvertMesh/BamgConvertMesh.h
+BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
 
-InterpFromMeshToMesh2d_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
-							../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
+BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp\
+								../BamgMesher/BamgMesher.h
+BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
 
-NodeConnectivity_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
+ContourToNodes_la_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
+									 ../ContourToNodes/ContourToNodes.h
+ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+ElementConnectivity_la_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
+											../ElementConnectivity/ElementConnectivity.h
+ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+EnumToString_la_SOURCES = ../EnumToString/EnumToString.cpp\
+								  ../EnumToString/EnumToString.h
+EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+InterpFromMeshToMesh2d_la_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
+												../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
+InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+NodeConnectivity_la_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
 										../NodeConnectivity/NodeConnectivity.h
+NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
 
-TriMesh_SOURCES = ../TriMesh/TriMesh.cpp\
-			  ../TriMesh/TriMesh.h
+StringToEnum_la_SOURCES = ../StringToEnum/StringToEnum.cpp\
+								  ../StringToEnum/StringToEnum.h
+StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+TriMesh_la_SOURCES = ../TriMesh/TriMesh.cpp\
+							../TriMesh/TriMesh.h
+TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB)
 #}}}
Index: sm/trunk/src/py/Makefile.am
===================================================================
--- /issm/trunk/src/py/Makefile.am	(revision 13394)
+++ 	(revision )
@@ -1,1 +1,0 @@
-SUBDIRS = model
Index: /issm/trunk/startup.m
===================================================================
--- /issm/trunk/startup.m	(revision 13394)
+++ /issm/trunk/startup.m	(revision 13395)
@@ -27,6 +27,7 @@
 
 %ISSM path
-addpath([ISSM_DIR '/src/m/utils/']); %loads recursivepath
+addpath([ISSM_DIR '/src/m/os/']); %loads recursivepath
 addpath([ISSM_DIR '/bin']);
+addpath([ISSM_DIR '/lib']);
 addpath(recursivepath([ISSM_DIR '/src/m']));
 addpath(recursivepath([ISSM_DIR '/externalpackages/scotch']));
Index: /issm/trunk/startup.py
===================================================================
--- /issm/trunk/startup.py	(revision 13394)
+++ /issm/trunk/startup.py	(revision 13395)
@@ -43,5 +43,5 @@
 				#__import__(file)
 				
-sys.path.append(ISSM_DIR + '/src/modules/python')
+sys.path.append(ISSM_DIR + '/lib')
 
 #Deal with scipy import: 
@@ -58,5 +58,5 @@
 from surfaceforcings import *
 from basalforcings import *
-from materials import *
+from matice import *
 from friction import *
 from flowequation import *
@@ -68,5 +68,4 @@
 from settings import *
 from solver import *
-from issmtier  import * 
 from ismumps  import * 
 from pairoptions  import * 
@@ -86,5 +85,4 @@
 from triangle import *
 from setmask import *
-
 #}}}
 
Index: /issm/trunk/test/Data/convertmattonc.m
===================================================================
--- /issm/trunk/test/Data/convertmattonc.m	(revision 13395)
+++ /issm/trunk/test/Data/convertmattonc.m	(revision 13395)
@@ -0,0 +1,50 @@
+function []=convertmattonc(matfile,ncfile);
+%    convertmattonc -- function to convert mat-format file to nc-format file
+%
+%    usage:
+%        convertmattonc(matfile,ncfile);
+%    where:
+%        matfile    name of mat-format file
+%        ncfile     name of nc-format file (optional)
+%
+
+	if ~exist('matfile','var') || isempty(matfile)
+		help convertmattonc
+		error('convertmattonc usage error.');
+	end
+
+	[pathstr,name,ext]=fileparts(matfile);
+	if isempty(ext)
+		ext='.mat';
+	end
+	matfile=fullfile(pathstr,[name ext]);
+
+	if ~exist('ncfile','var') || isempty(ncfile)
+		ncfile=fullfile(pathstr,[name '.nc']);
+	end
+
+	if exist(ncfile,'file')
+		delete(ncfile);
+	end
+
+	a=load(matfile,'-mat');
+	disp(sprintf('mat-format file ''%s'' read.',matfile));
+	fnames=fieldnames(a);
+
+	for i=1:length(fnames)
+		if isstruct(a.(fnames{i})) || iscell(a.(fnames{i}))
+			warning('field ''%s'' is of class ''%s'' and will not be written.',fnames{i},class(a.(fnames{i})));
+		else
+			% matlab writes the dimensions reversed and matrices transposed into netcdf, so compensate for that
+			nccreate(ncfile,fnames{i},...
+                     'Dimensions',{[fnames{i} '_2'] size(a.(fnames{i}),2) [fnames{i} '_1'] size(a.(fnames{i}),1)},...
+                     'Format','classic');
+			ncwrite(ncfile,fnames{i},transpose(a.(fnames{i})));
+			disp(sprintf('field ''%s'' of class ''%s'' and size [%dx%d] written.',...
+			             fnames{i},class(a.(fnames{i})),size(a.(fnames{i}),1),size(a.(fnames{i}),2)));
+		end
+	end
+	disp(sprintf('nc-format  file ''%s'' written.',ncfile));
+
+end
+
Index: /issm/trunk/test/Data/delta18o.data
===================================================================
--- /issm/trunk/test/Data/delta18o.data	(revision 13395)
+++ /issm/trunk/test/Data/delta18o.data	(revision 13395)
@@ -0,0 +1,2 @@
+  -3.9010000e-02  -3.9180000e-02  -3.9280000e-02  -3.9320000e-02  -3.9050000e-02  -3.8880000e-02  -3.8680000e-02  -3.8560000e-02  -3.8500000e-02  -3.8520000e-02  -3.8560000e-02
+   0.0000000e+00   2.0000000e+01   4.0000000e+01   6.0000000e+01   8.0000000e+01   1.0000000e+02   1.2000000e+02   1.4000000e+02   1.6000000e+02   1.8000000e+02   2.0000000e+02
Index: /issm/trunk/test/Data/loadnc.m
===================================================================
--- /issm/trunk/test/Data/loadnc.m	(revision 13395)
+++ /issm/trunk/test/Data/loadnc.m	(revision 13395)
@@ -0,0 +1,32 @@
+function [s]=loadnc(ncfile);
+%    loadnc -- function to read the variables from an nc-format file
+%
+%    usage:
+%        s=loadnc(ncfile);
+%    where:
+%        ncfile     name of nc-format file
+%
+
+	if ~exist('ncfile','var') || isempty(ncfile)
+		help loadnc
+		error('loadnc usage error.');
+	end
+
+	[pathstr,name,ext]=fileparts(ncfile);
+	if isempty(ext)
+		ext='.nc';
+	end
+	ncfile=fullfile(pathstr,[name ext]);
+
+	a=ncinfo(ncfile);
+	disp(sprintf('nc-format file ''%s'' read.',ncfile));
+
+	for i=1:length(a.Variables)
+		% matlab reads the dimensions reversed and matrices transposed from netcdf, so compensate for that
+		s.(a.Variables(i).Name)=transpose(ncread(ncfile,a.Variables(i).Name));
+		disp(sprintf('field ''%s'' of class ''%s'' and size [%dx%d] read.',...
+		             a.Variables(i).Name,class(s.(a.Variables(i).Name)),size(s.(a.Variables(i).Name),1),size(s.(a.Variables(i).Name),2)));
+	end
+
+end
+
Index: /issm/trunk/test/NightlyRun/IdFromString.py
===================================================================
--- /issm/trunk/test/NightlyRun/IdFromString.py	(revision 13394)
+++ /issm/trunk/test/NightlyRun/IdFromString.py	(revision 13395)
@@ -1,17 +1,16 @@
 #! /usr/bin/env python
-"""
-IDFROMSTRING - output ids from a given string
- 
-    Usage:
-       ids=IdFromString(string)
- 
-    Examples:
-       ids=IdFromString('Parallel')
-       ids=IdFromString('79North')
-"""
-
 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
Index: /issm/trunk/test/NightlyRun/IdToName.m
===================================================================
--- /issm/trunk/test/NightlyRun/IdToName.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/IdToName.m	(revision 13395)
@@ -6,291 +6,156 @@
 
 switch id,
-
-	case 101, name='SquareShelfConstrainedDiagM2dSerial';
-	case 102, name='SquareShelfConstrainedDiagM2dParallel';
-	case 103, name='SquareShelfConstrainedDiagM3dSerial';
-	case 104, name='SquareShelfConstrainedDiagM3dParallel';
-	case 105, name='SquareShelfConstrainedDiagP3dSerial';
-	case 106, name='SquareShelfConstrainedDiagP3dParallel';
-	case 107, name='SquareShelfConstrainedDiagS3dSerial';
-	case 108, name='SquareShelfConstrainedDiagS3dParallel';
-	case 109, name='SquareShelfConstrainedProg2dSerial';
-	case 110, name='SquareShelfConstrainedProg2dParallel';
-	case 111, name='SquareShelfConstrainedProg2dDGSerial';
-	case 112, name='SquareShelfConstrainedProg2dDGParallel';
-	case 113, name='SquareShelfConstrainedProg3dSerial';
-	case 114, name='SquareShelfConstrainedProg3dParallel';
-	case 115, name='SquareShelfConstrainedTherSteaSerial';
-	case 116, name='SquareShelfConstrainedTherSteaParallel';
-	case 117, name='SquareShelfConstrainedTherTranSerial';
-	case 118, name='SquareShelfConstrainedTherTranParallel';
-	case 119, name='SquareShelfConstrainedTranM2dSerial';
-	case 120, name='SquareShelfConstrainedTranM2dParallel';
-	case 121, name='SquareShelfConstrainedTranP3dSerial';
-	case 122, name='SquareShelfConstrainedTranP3dParallel';
-	case 123, name='SquareShelfConstrainedSurfSlop2dSerial';
-	case 124, name='SquareShelfConstrainedSurfSlop2dParallel';
-	case 125, name='SquareShelfConstrainedSurfSlop3dSerial';
-	case 126, name='SquareShelfConstrainedSurfSlope3dParallel';
-	case 127, name='SquareShelfConstrainedBedSlop2dSerial';
-	case 128, name='SquareShelfConstrainedBedSlop2dParallel';
-	case 129, name='SquareShelfConstrainedBedSlop3dSerial';
-	case 130, name='SquareShelfConstrainedBedSlop3dParallel';
-	case 131, name='SquareShelfConstrainedBalThic2dSerial';
-	case 132, name='SquareShelfConstrainedBalThic2dParallel';
-	case 133, name='SquareShelfConstrainedBalThic3dSerial';
-	case 134, name='SquareShelfConstrainedBalThic3dParallel';
-	case 135, name='SquareShelfConstrainedBalThic2dDGSerial';
-	case 136, name='SquareShelfConstrainedBalThic2dDGParallel';
-	case 137, name='SquareBamgMesh';
-	case 139, name='SquareShelfConstrainedEnthalpySteaSerial';
-	case 140, name='SquareShelfConstrainedEnthalpySteaParallel';
-	case 141, name='SquareShelfConstrainedEnthalpyTranSerial';
-	case 142, name='SquareShelfConstrainedEnthalpyTranParallel';
-	case 143, name='SquareShelfConstrainedTransP3dEnthSerial';
-	case 144, name='SquareShelfConstrainedTransP3dEnthParallel';
-	case 201, name='SquareShelfDiagM2dSerial';
-	case 202, name='SquareShelfDiagM2dParallel';
-	case 203, name='SquareShelfDiagM3dSerial';
-	case 204, name='SquareShelfDiagM3dParallel';
-	case 205, name='SquareShelfDiagP3dSerial';
-	case 206, name='SquareShelfDiagP3dParallel';
-	case 207, name='SquareShelfDiagS3dSerial';
-	case 208, name='SquareShelfDiagS3dParallel';
-	case 209, name='SquareShelfDiagMP3dPenaltiesSerial';
-	case 210, name='SquareShelfDiagMP3dPenaltiesParallel';
-	case 211, name='SquareShelfTherSteaSerial';
-	case 212, name='SquareShelfTherSteaParallel';
-	case 213, name='SquareShelfTherTranSerial';
-	case 214, name='SquareShelfTherTranParallel';
-	case 215, name='SquareShelfTranM2dSerial';
-	case 216, name='SquareShelfTranM2dParallel';
-	case 217, name='SquareShelfTranM3dSerial';
-	case 218, name='SquareShelfTranM3dParallel';
-	case 219, name='SquareShelfTranP3dSerial';
-	case 220, name='SquareShelfTranP3dParallel';
-	case 221, name='SquareShelfTranS3dSerial';
-	case 222, name='SquareShelfTranS3dParallel';
-	case 223, name='SquareShelfCMBM2dSerial';
-	case 224, name='SquareShelfCMBM2dParallel';
-	case 225, name='SquareShelfCMBM3dSerial';
-	case 226, name='SquareShelfCMBM3dParallel';
-	case 227, name='SquareShelfCMBP3dSerial';
-	case 228, name='SquareShelfCMBP3dParallel';
-	case 229, name='SquareShelfCMBS3dSerial';
-	case 230, name='SquareShelfCMBS3dParallel';
-	case 231, name='SquareShelfDiagM2dRiftSerial';
-	case 232, name='SquareShelfDiagM2dRiftParallel';
-	case 233, name='SquareShelfConstrainedSerial';
-	case 234, name='SquareShelfConstrainedParallel';
-	case 235, name='SquareShelfConstrainedDakotaBSerial';
-	case 236, name='SquareShelfConstrainedDakotaBParallel';
-	case 237, name='SquareShelfDiagMP3dTilingSerial';
-	case 238, name='SquareShelfDiagMP3dTilingParallel';
-	case 239, name='SquareShelfDiagPS3dTilingSerial';
-	case 240, name='SquareShelfDiagPS3dTilingParallel';
-	case 241, name='SquareShelfDiagMS3dTilingSerial';
-	case 242, name='SquareShelfDiagMS3dTilingParallel';
-	case 243, name='SquareShelfDiagM2dTransientIncrHydroSerial';
-	case 244, name='SquareShelfDiagM2dTransientIncrHydroParallel';
-	case 245, name='SquareShelfDiagM2dTransientIncrNonHydroSerial';
-	case 246, name='SquareShelfDiagM2dTransientIncrNonHydroParallel';
-	case 247, name='SquareShelfDiagP3dTransientIncrHydroSerial';
-	case 248, name='SquareShelfDiagP3dTransientIncrHydroParallel';
-	case 249, name='SquareShelfDiagP3dTransientIncrNonHydroSerial';
-	case 250, name='SquareShelfDiagP3dTransientIncrNonHydroParallel';
-	case 251, name='SquareShelfTranCflM2dSerial';
-	case 252, name='SquareShelfTranCflM2dParallel';
-	case 253, name='SquareShelfTranCflP3dSerial';
-	case 254, name='SquareShelfTranCflP3dParallel';
-	case 255, name='SquareShelfTranForceNeg2dSerial';
-	case 256, name='SquareShelfTranForceNeg2dParallel';
-	case 257, name='SquareShelfTranForcePos2dSerial';
-	case 258, name='SquareShelfTranForcePos2dParallel';
-	case 259, name='SquareShelfTranForceNeg3dSerial';
-	case 260, name='SquareShelfTranForceNeg3dParallel';
-	case 261, name='SquareShelfTranForcePos3dSerial';
-	case 262, name='SquareShelfTranForcePos3dParallel';
-	case 263, name='SquareShelfTherTranForcTempSerial';
-	case 264, name='SquareShelfTherTranForcTempParallel';
-	case 265, name='SquareShelfTranP3dForcTempSerial';
-	case 266, name='SquareShelfTranP3dForcTempParallel';
-	case 268, name='SquareShelfTranForceNeg2dDakotaSamp';
-	case 270, name='SquareShelfTranForceNeg2dDakotaLocal';
-	case 301, name='SquareSheetConstrainedDiagM2dSerial';
-	case 302, name='SquareSheetConstrainedDiagM2dParallel';
-	case 303, name='SquareSheetConstrainedDiagH2dSerial';
-	case 304, name='SquareSheetConstrainedDiagH2dParallel';
-	case 305, name='SquareSheetConstrainedDiagHM2dSerial';
-	case 306, name='SquareSheetConstrainedDiagHM2dParallel';
-	case 307, name='SquareSheetConstrainedDiagM3dSerial';
-	case 308, name='SquareSheetConstrainedDiagM3dParallel';
-	case 309, name='SquareSheetConstrainedDiagH3dSerial';
-	case 310, name='SquareSheetConstrainedDiagH3dParallel';
-	case 311, name='SquareSheetConstrainedDiagHM3dSerial';
-	case 312, name='SquareSheetConstrainedDiagHM3dParallel';
-	case 313, name='SquareSheetConstrainedDiagP3dSerial';
-	case 314, name='SquareSheetConstrainedDiagP3dParallel';
-	case 315, name='SquareSheetConstrainedDiagS3dSerial';
-	case 316, name='SquareSheetConstrainedDiagS3dParallel';
-	case 317, name='SquareSheetConstrainedProg2dSerial';
-	case 318, name='SquareSheetConstrainedProg2dParallel';
-	case 319, name='SquareSheetConstrainedProg2dDGSerial';
-	case 320, name='SquareSheetConstrainedProg2dDGParallel';
-	case 321, name='SquareSheetConstrainedProg3dSerial';
-	case 322, name='SquareSheetConstrainedProg3dParallel';
-	case 323, name='SquareSheetConstrainedTherSteaSerial';
-	case 324, name='SquareSheetConstrainedTherSteaParallel';
-	case 325, name='SquareSheetConstrainedTherTranSerial';
-	case 326, name='SquareSheetConstrainedTherTranParallel';
-	case 327, name='SquareSheetConstrainedTranH2dSerial';
-	case 328, name='SquareSheetConstrainedTranH2dParallel';
-	case 329, name='SquareSheetConstrainedTranH3dSerial';
-	case 330, name='SquareSheetConstrainedTranH3dParallel';
-	case 331, name='SquareSheetConstrainedTranM2dSerial';
-	case 332, name='SquareSheetConstrainedTranM2dParallel';
-	case 333, name='SquareSheetConstrainedTranP3dSerial';
-	case 334, name='SquareSheetConstrainedTranP3dParallel';
-	case 335, name='SquareSheetConstrainedSteaH3dSerial';
-	case 336, name='SquareSheetConstrainedSteaH3dParallel';
-	case 337, name='SquareSheetConstrainedCMDragM2dSerial';
-	case 338, name='SquareSheetConstrainedCMDragM2dParallel';
-	case 339, name='SquareSheetConstrainedCMDragM3dSerial';
-	case 340, name='SquareSheetConstrainedCMDragM3dParallel';
-	case 341, name='SquareSheetConstrainedCMDragP3dSerial';
-	case 342, name='SquareSheetConstrainedCMDragP3dParallel';
-	case 343, name='SquareSheetConstrainedCMDragS3dSerial';
-	case 344, name='SquareSheetConstrainedCMDragS3dParallel';
-	case 345, name='SquareSheetConstrainedTranCflM2dSerial';
-	case 346, name='SquareSheetConstrainedTranCflM2dParallel';
-	case 347, name='SquareSheetConstrainedTranCflH3dSerial';
-	case 348, name='SquareSheetConstrainedTranCflH3dParallel';
-	case 349, name='SquareSheetConstrainedEnthalpySteaSerial';
-	case 350, name='SquareSheetConstrainedEnthalpySteaParallel';
-	case 351, name='SquareSheetConstrainedEnthalpyTranSerial';
-	case 352, name='SquareSheetConstrainedEnthalpyTranParallel';
-	case 353, name='SquareSheetConstrainedTransP3dEnthSerial';
-	case 354, name='SquareSheetConstrainedTransP3dEnthParallel';
-	case 356, name='SquareSheetConstrainedSmbGradients2dParallel';
-	case 358, name='SquareSheetConstrainedSmbGradients3dParallel';
-	case 401, name='SquareSheetShelfDiagM2dSerial';
-	case 402, name='SquareSheetShelfDiagM2dParallel';
-	case 403, name='SquareSheetShelfDiagM3dSerial';
-	case 404, name='SquareSheetShelfDiagM3dParallel';
-	case 405, name='SquareSheetShelfDiagP3dSerial';
-	case 406, name='SquareSheetShelfDiagP3dParallel';
-	case 407, name='SquareSheetShelfDiagS3dSerial';
-	case 408, name='SquareSheetShelfDiagS3dParallel';
-	case 409, name='SquareSheetShelfDiagMP3dPenaltiesSerial';
-	case 410, name='SquareSheetShelfDiagMP3dPenaltiesParallel';
-	case 411, name='SquareSheetShelfTherSteaSerial';
-	case 412, name='SquareSheetShelfTherSteaParallel';
-	case 413, name='SquareSheetShelfTherTranSerial';
-	case 414, name='SquareSheetShelfTherTranParallel';
-	case 415, name='SquareSheetShelfTranM2dSerial';
-	case 416, name='SquareSheetShelfTranM2dParallel';
-	case 417, name='SquareSheetShelfTranMP3dPenaltiesSerial';
-	case 418, name='SquareSheetShelfTranMP3dPenaltiesParallel';
-	case 419, name='SquareSheetShelfSteaM3dSerial';
-	case 420, name='SquareSheetShelfSteaM3dParallel';
-	case 421, name='SquareSheetShelfSteaP3dSerial';
-	case 422, name='SquareSheetShelfSteaP3dParallel';
-	case 423, name='SquareSheetShelfDiadM3dDakotaSerial';
-	case 424, name='SquareSheetShelfDiadM3dDakotaParallel';
-	case 425, name='SquareSheetShelfDiadM3dDakotaPartSerial';
-	case 426, name='SquareSheetShelfDiadM3dDakotaPartParallel';
-	case 427, name='SquareSheetShelfDiadM3dDakotaMassFluxSerial';
-	case 428, name='SquareSheetShelfDiadM3dDakotaMassFluxParallel';
-	case 429, name='SquareSheetShelfCMDragSteaM3dSerial';
-	case 430, name='SquareSheetShelfCMDragSteaM3dParallel';
-	case 431, name='SquareSheetShelfCMDragSteaP3dSerial';
-	case 432, name='SquareSheetShelfCMDragSteaP3dParallel';
-	case 434, name='SquareSheetShelfDiadM3dDakotaSamp';
-	case 436, name='SquareSheetShelfDiadM3dDakotaAreaAverage';
-	case 437, name='SquareSheetShelfDiagMP3dTilingSerial';
-	case 438, name='SquareSheetShelfDiagMP3dTilingParallel';
-	case 439, name='SquareSheetShelfDakotaScaledResponse';
-	case 440, name='SquareSheetShelfDakotaScaledResponse';
-	case 441, name='SquareSheetShelfDiagPS3dTilingSerial';
-	case 442, name='SquareSheetShelfDiagPS3dTilingParallel';
-	case 443, name='SquareSheetShelfDiagMS3dTilingSerial';
-	case 444, name='SquareSheetShelfDiagMS3dTilingParallel';
-	case 445, name='RoundSheetShelfGLMigrationM2dSerial';
-	case 446, name='RoundSheetShelfGLMigrationM2dParallel';
-	case 447, name='SquareSheetShelfGroundingLine2dAgressiceSerial';
-	case 448, name='SquareSheetShelfGroundingLine2dAgressiceParallel';
-	case 449, name='SquareSheetShelfGroundingLine2dSoftSerial';
-	case 450, name='SquareSheetShelfGroundingLine2dSoftParallel';
-	case 451, name='SquareSheetShelfGroundingLine3dAgressiceSerial';
-	case 452, name='SquareSheetShelfGroundingLine3dAgressiceParallel';
-	case 453, name='SquareSheetShelfGroundingLine3dSoftSerial';
-	case 454, name='SquareSheetShelfGroundingLine3dSoftParallel';
-	case 455, name='SquareSheetShelfDiagM2dNewtonSerial';
-	case 456, name='SquareSheetShelfDiagM2dNewtonParallel';
-	case 457, name='SquareSheetShelfDiagP3dNewtonSerial';
-	case 458, name='SquareSheetShelfDiagP3dNewtonParallel';
-	case 459, name='SquareSheetShelfDiagS3dNewtonSerial';
-	case 460, name='SquareSheetShelfDiagS3dNewtonParallel';
-	case 461, name='SquareSheetShelfSteaEnthalpyM3dSerial';
-	case 462, name='SquareSheetShelfSteaEnthalpyM3dParallel';
-	case 463, name='SquareSheetShelfSteaEnthalpyP3dSerial';
-	case 464, name='SquareSheetShelfSteaEnthalpyP3dParallel';
-	case 501, name='PigDiagM2dSerial';
-	case 502, name='PigDiagM2dParallel';
-	case 503, name='PigDiagP3dSerial';
-	case 504, name='PigDiagP3dParallel';
-	case 505, name='PigDiagS3dSerial';
-	case 506, name='PigDiagS3dParallel';
-	case 507, name='PigTranM2dSerial';
-	case 508, name='PigTranM2dParallel';
-	case 509, name='PigTranM3dSerial';
-	case 510, name='PigTranM3dParallel';
-	case 511, name='PigTranP3dSerial';
-	case 512, name='PigTranP3dParallel';
-	case 513, name='PigTranS3dSerial';
-	case 514, name='PigTranS3dParallel';
-	case 515, name='PigSteaM3dSerial';
-	case 516, name='PigSteaM3dParallel';
-	case 517, name='PigSteaP3dSerial';
-	case 518, name='PigSteaP3dParallel';
-	case 519, name='PigSteaS3dSerial';
-	case 520, name='PigSteaS3dParallel';
-	case 521, name='PigCMBS3dSerial';
-	case 522, name='PigCMBS3dparallel';
-	case 523, name='PigCMDragP3dSerial';
-	case 524, name='PigCMDragP3dparallel';
-	case 525, name='PigCMDragSteaM3dSerial';
-	case 526, name='PigCMDragSteaM3dparallel';
-	case 527, name='PigBamgMesh';
-	case 529, name='PigTherTranSUPGSerial';
-	case 530, name='PigTherTranSUPGParallel';
-	case 531, name='PigTherSteaSUPGSerial';
-	case 532, name='PigTherSteaSUPGParallel';
-	case 601, name='79NorthProg2dSerial';
-	case 602, name='79NorthProg2dParallel';
-	case 603, name='79NorthProg2dDGSerial';
-	case 604, name='79NorthProg2dDGParallel';
-	case 605, name='79NorthProg3dSerial';
-	case 606, name='79NorthProg3dParallel';
-	case 607, name='79NorthSurfSlop2dSerial';
-	case 608, name='79NorthSurfSlop2dParallel';
-	case 609, name='79NorthSurfSlop3dSerial';
-	case 610, name='79NorthSurfSlop3dParallel';
-	case 611, name='79NorthBedSlop2dSerial';
-	case 612, name='79NorthBedSlop2dParallel';
-	case 613, name='79NorthBedSlop3dSerial';
-	case 614, name='79NorthBedSlop3dParallel';
-	case 615, name='79NorthBalThic2dSerial';
-	case 616, name='79NorthBalThic2dParallel';
-	case 617, name='79NorthBalThic2dDGSerial';
-	case 618, name='79NorthBalThic2dDGParallel';
-	case 619, name='79NorthBalThic3dSerial';
-	case 620, name='79NorthBalThic3dParallel';
-	case 621, name='79NorthCMBalThic2dCGSerial';
-	case 622, name='79NorthCMBalThic2dCGParallel';
-	case 623, name='79NorthCMBalThic2dDGSerial';
-	case 624, name='79NorthCMBalThic2dDGParallel';
-	case 625, name='79NorthCMBalThicVxVyParallel';
-	case 626, name='79NorthCMBalThicVxVySerial';
+	case 101, name='SquareShelfConstrainedDiagM2d';
+	case 102, name='SquareShelfConstrainedDiagM3d';
+	case 103, name='SquareShelfConstrainedDiagP3d';
+	case 104, name='SquareShelfConstrainedDiagS3d';
+	case 105, name='SquareShelfConstrainedProg2d';
+	case 106, name='SquareShelfConstrainedProg2dDG';
+	case 107, name='SquareShelfConstrainedProg3d';
+	case 108, name='SquareShelfConstrainedTherStea';
+	case 109, name='SquareShelfConstrainedTherTran';
+	case 110, name='SquareShelfConstrainedTranM2d';
+	case 111, name='SquareShelfConstrainedTranP3d';
+	case 112, name='SquareShelfConstrainedSurfSlop2d';
+	case 113, name='SquareShelfConstrainedSurfSlope3d';
+	case 114, name='SquareShelfConstrainedBedSlop2d';
+	case 115, name='SquareShelfConstrainedBedSlop3d';
+	case 116, name='SquareShelfConstrainedBalThic2d';
+	case 117, name='SquareShelfConstrainedBalThic3d';
+	case 118, name='SquareShelfConstrainedBalThic2dDG';
+	case 119, name='SquareBamgMesh';
+	case 120, name='SquareShelfConstrainedEnthalpyStea';
+	case 121, name='SquareShelfConstrainedEnthalpyTran';
+	case 122, name='SquareShelfConstrainedTransP3dEnth';
+	case 201, name='SquareShelfDiagM2d';
+	case 202, name='SquareShelfDiagM3d';
+	case 203, name='SquareShelfDiagP3d';
+	case 204, name='SquareShelfDiagS3d';
+	case 205, name='SquareShelfDiagMP3dPenalties';
+	case 206, name='SquareShelfTherStea';
+	case 207, name='SquareShelfTherTran';
+	case 208, name='SquareShelfTranM2d';
+	case 209, name='SquareShelfTranM3d';
+	case 210, name='SquareShelfTranP3d';
+	case 211, name='SquareShelfTranS3d';
+	case 212, name='SquareShelfCMBM2d';
+	case 213, name='SquareShelfCMBM3d';
+	case 214, name='SquareShelfCMBP3d';
+	case 215, name='SquareShelfCMBS3d';
+	case 216, name='SquareShelfDiagM2dRift';
+	case 217, name='SquareShelfConstrained';
+	case 218, name='SquareShelfConstrainedDakotaB';
+	case 219, name='SquareShelfDiagMP3dTiling';
+	case 220, name='SquareShelfDiagPS3dTiling';
+	case 221, name='SquareShelfDiagMS3dTiling';
+	case 222, name='SquareShelfDiagM2dTransientIncrHydro';
+	case 223, name='SquareShelfDiagM2dTransientIncrNonHydro';
+	case 224, name='SquareShelfDiagP3dTransientIncrHydro';
+	case 225, name='SquareShelfDiagP3dTransientIncrNonHydro';
+	case 226, name='SquareShelfTranCflM2d';
+	case 227, name='SquareShelfTranCflP3d';
+	case 228, name='SquareShelfTranForceNeg2d';
+	case 229, name='SquareShelfTranForcePos2d';
+	case 230, name='SquareShelfTranForceNeg3d';
+	case 231, name='SquareShelfTranForcePos3d';
+	case 232, name='SquareShelfTherTranForcTemp';
+	case 233, name='SquareShelfTranP3dForcTemp';
+	case 234, name='SquareShelfTranForceNeg2dDakotaSamp';
+	case 235, name='SquareShelfTranForceNeg2dDakotaLocal';
+	case 236, name='SquareShelfTranIspddIsdeltaM2d';
+	case 237, name='SquareShelfTranIspddIsdeltaM3d';
+	case 270, name='SquareShelfDiagM2dDamage';
+	case 272, name='SquareShelfCMZM2dDamage';
+	case 274, name='SquareShelfDiagM2dDamageRift';
+	case 301, name='SquareSheetConstrainedDiagM2d';
+	case 302, name='SquareSheetConstrainedDiagH2d';
+	case 303, name='SquareSheetConstrainedDiagHM2d';
+	case 304, name='SquareSheetConstrainedDiagM3d';
+	case 305, name='SquareSheetConstrainedDiagH3d';
+	case 306, name='SquareSheetConstrainedDiagHM3d';
+	case 307, name='SquareSheetConstrainedDiagP3d';
+	case 308, name='SquareSheetConstrainedDiagS3d';
+	case 309, name='SquareSheetConstrainedProg2d';
+	case 320, name='SquareSheetConstrainedProg2dDG';
+	case 311, name='SquareSheetConstrainedProg3d';
+	case 312, name='SquareSheetConstrainedTherStea';
+	case 313, name='SquareSheetConstrainedTherTran';
+	case 314, name='SquareSheetConstrainedTranH2d';
+	case 315, name='SquareSheetConstrainedTranH3d';
+	case 316, name='SquareSheetConstrainedTranM2d';
+	case 317, name='SquareSheetConstrainedTranP3d';
+	case 318, name='SquareSheetConstrainedSteaH3d';
+	case 319, name='SquareSheetConstrainedCMDragM2d';
+	case 320, name='SquareSheetConstrainedCMDragM3d';
+	case 321, name='SquareSheetConstrainedCMDragP3d';
+	case 322, name='SquareSheetConstrainedCMDragS3d';
+	case 323, name='SquareSheetConstrainedTranCflM2d';
+	case 324, name='SquareSheetConstrainedTranCflH3d';
+	case 325, name='SquareSheetConstrainedEnthalpyStea';
+	case 326, name='SquareSheetConstrainedEnthalpyTran';
+	case 327, name='SquareSheetConstrainedTransP3dEnth';
+	case 328, name='SquareSheetConstrainedSmbGradients2d';
+	case 329, name='SquareSheetConstrainedSmbGradients3d';
+	case 401, name='SquareSheetShelfDiagM2d';
+	case 402, name='SquareSheetShelfDiagM3d';
+	case 403, name='SquareSheetShelfDiagP3d';
+	case 404, name='SquareSheetShelfDiagS3d';
+	case 405, name='SquareSheetShelfDiagMP3dPenalties';
+	case 406, name='SquareSheetShelfTherStea';
+	case 407, name='SquareSheetShelfTherTran';
+	case 408, name='SquareSheetShelfTranM2d';
+	case 409, name='SquareSheetShelfTranMP3dPenalties';
+	case 410, name='SquareSheetShelfSteaM3d';
+	case 411, name='SquareSheetShelfSteaP3d';
+	case 412, name='SquareSheetShelfDiadM3dDakota';
+	case 413, name='SquareSheetShelfDiadM3dDakotaPart';
+	case 414, name='SquareSheetShelfDiadM3dDakotaMassFlux';
+	case 415, name='SquareSheetShelfCMDragSteaM3d';
+	case 416, name='SquareSheetShelfCMDragSteaP3d';
+	case 417, name='SquareSheetShelfDiadM3dDakotaSamp';
+	case 418, name='SquareSheetShelfDiadM3dDakotaAreaAverage';
+	case 419, name='SquareSheetShelfDiagMP3dTiling';
+	case 420, name='SquareSheetShelfDakotaScaledResponse';
+	case 421, name='SquareSheetShelfDiagPS3dTiling';
+	case 422, name='SquareSheetShelfDiagMS3dTiling';
+	case 423, name='RoundSheetShelfGLMigrationM2d';
+	case 424, name='SquareSheetShelfGroundingLine2dAgressice';
+	case 425, name='SquareSheetShelfGroundingLine2dSoft';
+	case 426, name='SquareSheetShelfGroundingLine3dAgressice';
+	case 427, name='SquareSheetShelfGroundingLine3dSoft';
+	case 428, name='SquareSheetShelfDiagM2dNewton';
+	case 429, name='SquareSheetShelfDiagP3dNewton';
+	case 430, name='SquareSheetShelfDiagS3dNewton';
+	case 431, name='SquareSheetShelfSteaEnthalpyM3d';
+	case 432, name='SquareSheetShelfSteaEnthalpyP3d';
+	case 501, name='PigDiagM2d';
+	case 502, name='PigDiagP3d';
+	case 503, name='PigDiagS3d';
+	case 504, name='PigTranM2d';
+	case 505, name='PigTranM3d';
+	case 506, name='PigTranP3d';
+	case 507, name='PigTranS3d';
+	case 508, name='PigSteaM3d';
+	case 509, name='PigSteaP3d';
+	case 510, name='PigSteaS3d';
+	case 511, name='PigCMBS3d';
+	case 512, name='PigCMDragP3d';
+	case 513, name='PigCMDragSteaM3d';
+	case 514, name='PigBamgMesh';
+	case 515, name='PigTherTranSUPG';
+	case 516, name='PigTherSteaSUPG';
+	case 601, name='79NorthProg2d';
+	case 602, name='79NorthProg2dDG';
+	case 603, name='79NorthProg3d';
+	case 604, name='79NorthSurfSlop2d';
+	case 605, name='79NorthSurfSlop3d';
+	case 606, name='79NorthBedSlop2d';
+	case 607, name='79NorthBedSlop3d';
+	case 608, name='79NorthBalThic2d';
+	case 609, name='79NorthBalThic2dDG';
+	case 610, name='79NorthBalThic3d';
+	case 611, name='79NorthCMBalThic2dCG';
+	case 612, name='79NorthCMBalThic2dDG';
+	case 613, name='79NorthCMBalThicVxVyParalle';
 	case 1101, name='ISMIPAPattyn';
 	case 1102, name='ISMIPAStokes';
@@ -321,4 +186,15 @@
 	case 1601, name='SquareShelfM2dRotation';
 	case 1602, name='SquareSheetShelfP3dRotation';
+	case 3001, name='SquareShelfConstrainedDiagM2dAdolc';
+	case 3002, name='SquareShelfConstrainedDiagM3dAdolc';
+	case 3003, name='SquareShelfConstrainedDiagP3dAdolc';
+	case 3004, name='SquareShelfConstrainedDiagS3dAdolc';
+	case 3005, name='SquareShelfConstrainedProg2dAdolc';
+	case 3006, name='SquareShelfConstrainedProg2dDGAdolc';
+	case 3007, name='SquareShelfConstrainedProg3dAdolc';
+	case 3008, name='SquareShelfConstrainedTherSteaAdolc';
+	case 3009, name='SquareShelfConstrainedTherTranAdolc';
+	case 3010, name='SquareShelfConstrainedTranM2dAdolc';
+
 	otherwise, name='N/A';
 end
Index: /issm/trunk/test/NightlyRun/IdToName.py
===================================================================
--- /issm/trunk/test/NightlyRun/IdToName.py	(revision 13394)
+++ /issm/trunk/test/NightlyRun/IdToName.py	(revision 13395)
@@ -1,296 +1,162 @@
 #! /usr/bin/env python
-"""
-IDTONAME- return name of test
+
+def IdToName(id):
+	"""
+	IDTONAME- return name of test
  
-    Usage:
-       name=IdToName(id)
-"""
-
-def IdToName(id):
+	    Usage:
+	       name=IdToName(id)
+	"""
+
 	idname={
-		101 : 'SquareShelfConstrainedDiagM2dSerial',
-		102 : 'SquareShelfConstrainedDiagM2dParallel',
-		103 : 'SquareShelfConstrainedDiagM3dSerial',
-		104 : 'SquareShelfConstrainedDiagM3dParallel',
-		105 : 'SquareShelfConstrainedDiagP3dSerial',
-		106 : 'SquareShelfConstrainedDiagP3dParallel',
-		107 : 'SquareShelfConstrainedDiagS3dSerial',
-		108 : 'SquareShelfConstrainedDiagS3dParallel',
-		109 : 'SquareShelfConstrainedProg2dSerial',
-		110 : 'SquareShelfConstrainedProg2dParallel',
-		111 : 'SquareShelfConstrainedProg2dDGSerial',
-		112 : 'SquareShelfConstrainedProg2dDGParallel',
-		113 : 'SquareShelfConstrainedProg3dSerial',
-		114 : 'SquareShelfConstrainedProg3dParallel',
-		115 : 'SquareShelfConstrainedTherSteaSerial',
-		116 : 'SquareShelfConstrainedTherSteaParallel',
-		117 : 'SquareShelfConstrainedTherTranSerial',
-		118 : 'SquareShelfConstrainedTherTranParallel',
-		119 : 'SquareShelfConstrainedTranM2dSerial',
-		120 : 'SquareShelfConstrainedTranM2dParallel',
-		121 : 'SquareShelfConstrainedTranP3dSerial',
-		122 : 'SquareShelfConstrainedTranP3dParallel',
-		123 : 'SquareShelfConstrainedSurfSlop2dSerial',
-		124 : 'SquareShelfConstrainedSurfSlop2dParallel',
-		125 : 'SquareShelfConstrainedSurfSlop3dSerial',
-		126 : 'SquareShelfConstrainedSurfSlope3dParallel',
-		127 : 'SquareShelfConstrainedBedSlop2dSerial',
-		128 : 'SquareShelfConstrainedBedSlop2dParallel',
-		129 : 'SquareShelfConstrainedBedSlop3dSerial',
-		130 : 'SquareShelfConstrainedBedSlop3dParallel',
-		131 : 'SquareShelfConstrainedBalThic2dSerial',
-		132 : 'SquareShelfConstrainedBalThic2dParallel',
-		133 : 'SquareShelfConstrainedBalThic3dSerial',
-		134 : 'SquareShelfConstrainedBalThic3dParallel',
-		135 : 'SquareShelfConstrainedBalThic2dDGSerial',
-		136 : 'SquareShelfConstrainedBalThic2dDGParallel',
-		137 : 'SquareBamgMesh',
-		139 : 'SquareShelfConstrainedEnthalpySteaSerial',
-		140 : 'SquareShelfConstrainedEnthalpySteaParallel',
-		141 : 'SquareShelfConstrainedEnthalpyTranSerial',
-		142 : 'SquareShelfConstrainedEnthalpyTranParallel',
-		143 : 'SquareShelfConstrainedTransP3dEnthSerial',
-		144 : 'SquareShelfConstrainedTransP3dEnthParallel',
-		201 : 'SquareShelfDiagM2dSerial',
-		202 : 'SquareShelfDiagM2dParallel',
-		203 : 'SquareShelfDiagM3dSerial',
-		204 : 'SquareShelfDiagM3dParallel',
-		205 : 'SquareShelfDiagP3dSerial',
-		206 : 'SquareShelfDiagP3dParallel',
-		207 : 'SquareShelfDiagS3dSerial',
-		208 : 'SquareShelfDiagS3dParallel',
-		209 : 'SquareShelfDiagMP3dPenaltiesSerial',
-		210 : 'SquareShelfDiagMP3dPenaltiesParallel',
-		211 : 'SquareShelfTherSteaSerial',
-		212 : 'SquareShelfTherSteaParallel',
-		213 : 'SquareShelfTherTranSerial',
-		214 : 'SquareShelfTherTranParallel',
-		215 : 'SquareShelfTranM2dSerial',
-		216 : 'SquareShelfTranM2dParallel',
-		217 : 'SquareShelfTranM3dSerial',
-		218 : 'SquareShelfTranM3dParallel',
-		219 : 'SquareShelfTranP3dSerial',
-		220 : 'SquareShelfTranP3dParallel',
-		221 : 'SquareShelfTranS3dSerial',
-		222 : 'SquareShelfTranS3dParallel',
-		223 : 'SquareShelfCMBM2dSerial',
-		224 : 'SquareShelfCMBM2dParallel',
-		225 : 'SquareShelfCMBM3dSerial',
-		226 : 'SquareShelfCMBM3dParallel',
-		227 : 'SquareShelfCMBP3dSerial',
-		228 : 'SquareShelfCMBP3dParallel',
-		229 : 'SquareShelfCMBS3dSerial',
-		230 : 'SquareShelfCMBS3dParallel',
-		231 : 'SquareShelfDiagM2dRiftSerial',
-		232 : 'SquareShelfDiagM2dRiftParallel',
-		233 : 'SquareShelfConstrainedSerial',
-		234 : 'SquareShelfConstrainedParallel',
-		235 : 'SquareShelfConstrainedDakotaBSerial',
-		236 : 'SquareShelfConstrainedDakotaBParallel',
-		237 : 'SquareShelfDiagMP3dTilingSerial',
-		238 : 'SquareShelfDiagMP3dTilingParallel',
-		239 : 'SquareShelfDiagPS3dTilingSerial',
-		240 : 'SquareShelfDiagPS3dTilingParallel',
-		241 : 'SquareShelfDiagMS3dTilingSerial',
-		242 : 'SquareShelfDiagMS3dTilingParallel',
-		243 : 'SquareShelfDiagM2dTransientIncrHydroSerial',
-		244 : 'SquareShelfDiagM2dTransientIncrHydroParallel',
-		245 : 'SquareShelfDiagM2dTransientIncrNonHydroSerial',
-		246 : 'SquareShelfDiagM2dTransientIncrNonHydroParallel',
-		247 : 'SquareShelfDiagP3dTransientIncrHydroSerial',
-		248 : 'SquareShelfDiagP3dTransientIncrHydroParallel',
-		249 : 'SquareShelfDiagP3dTransientIncrNonHydroSerial',
-		250 : 'SquareShelfDiagP3dTransientIncrNonHydroParallel',
-		251 : 'SquareShelfTranCflM2dSerial',
-		252 : 'SquareShelfTranCflM2dParallel',
-		253 : 'SquareShelfTranCflP3dSerial',
-		254 : 'SquareShelfTranCflP3dParallel',
-		255 : 'SquareShelfTranForceNeg2dSerial',
-		256 : 'SquareShelfTranForceNeg2dParallel',
-		257 : 'SquareShelfTranForcePos2dSerial',
-		258 : 'SquareShelfTranForcePos2dParallel',
-		259 : 'SquareShelfTranForceNeg3dSerial',
-		260 : 'SquareShelfTranForceNeg3dParallel',
-		261 : 'SquareShelfTranForcePos3dSerial',
-		262 : 'SquareShelfTranForcePos3dParallel',
-		263 : 'SquareShelfTherTranForcTempSerial',
-		264 : 'SquareShelfTherTranForcTempParallel',
-		265 : 'SquareShelfTranP3dForcTempSerial',
-		266 : 'SquareShelfTranP3dForcTempParallel',
-		267 : 'SquareShelfTranForceNeg2dDakotaSamp',
-   	268 : 'SquareShelfTranForceNeg2dDakotaLocal',
-		301 : 'SquareSheetConstrainedDiagM2dSerial',
-		302 : 'SquareSheetConstrainedDiagM2dParallel',
-		303 : 'SquareSheetConstrainedDiagH2dSerial',
-		304 : 'SquareSheetConstrainedDiagH2dParallel',
-		305 : 'SquareSheetConstrainedDiagHM2dSerial',
-		306 : 'SquareSheetConstrainedDiagHM2dParallel',
-		307 : 'SquareSheetConstrainedDiagM3dSerial',
-		308 : 'SquareSheetConstrainedDiagM3dParallel',
-		309 : 'SquareSheetConstrainedDiagH3dSerial',
-		310 : 'SquareSheetConstrainedDiagH3dParallel',
-		311 : 'SquareSheetConstrainedDiagHM3dSerial',
-		312 : 'SquareSheetConstrainedDiagHM3dParallel',
-		313 : 'SquareSheetConstrainedDiagP3dSerial',
-		314 : 'SquareSheetConstrainedDiagP3dParallel',
-		315 : 'SquareSheetConstrainedDiagS3dSerial',
-		316 : 'SquareSheetConstrainedDiagS3dParallel',
-		317 : 'SquareSheetConstrainedProg2dSerial',
-		318 : 'SquareSheetConstrainedProg2dParallel',
-		319 : 'SquareSheetConstrainedProg2dDGSerial',
-		320 : 'SquareSheetConstrainedProg2dDGParallel',
-		321 : 'SquareSheetConstrainedProg3dSerial',
-		322 : 'SquareSheetConstrainedProg3dParallel',
-		323 : 'SquareSheetConstrainedTherSteaSerial',
-		324 : 'SquareSheetConstrainedTherSteaParallel',
-		325 : 'SquareSheetConstrainedTherTranSerial',
-		326 : 'SquareSheetConstrainedTherTranParallel',
-		327 : 'SquareSheetConstrainedTranH2dSerial',
-		328 : 'SquareSheetConstrainedTranH2dParallel',
-		329 : 'SquareSheetConstrainedTranH3dSerial',
-		330 : 'SquareSheetConstrainedTranH3dParallel',
-		331 : 'SquareSheetConstrainedTranM2dSerial',
-		332 : 'SquareSheetConstrainedTranM2dParallel',
-		333 : 'SquareSheetConstrainedTranP3dSerial',
-		334 : 'SquareSheetConstrainedTranP3dParallel',
-		335 : 'SquareSheetConstrainedSteaH3dSerial',
-		336 : 'SquareSheetConstrainedSteaH3dParallel',
-		337 : 'SquareSheetConstrainedCMDragM2dSerial',
-		338 : 'SquareSheetConstrainedCMDragM2dParallel',
-		339 : 'SquareSheetConstrainedCMDragM3dSerial',
-		340 : 'SquareSheetConstrainedCMDragM3dParallel',
-		341 : 'SquareSheetConstrainedCMDragP3dSerial',
-		342 : 'SquareSheetConstrainedCMDragP3dParallel',
-		343 : 'SquareSheetConstrainedCMDragS3dSerial',
-		344 : 'SquareSheetConstrainedCMDragS3dParallel',
-		345 : 'SquareSheetConstrainedTranCflM2dSerial',
-		346 : 'SquareSheetConstrainedTranCflM2dParallel',
-		347 : 'SquareSheetConstrainedTranCflH3dSerial',
-		348 : 'SquareSheetConstrainedTranCflH3dParallel',
-		349 : 'SquareSheetConstrainedEnthalpySteaSerial',
-		350 : 'SquareSheetConstrainedEnthalpySteaParallel',
-		351 : 'SquareSheetConstrainedEnthalpyTranSerial',
-		352 : 'SquareSheetConstrainedEnthalpyTranParallel',
-		353 : 'SquareSheetConstrainedTransP3dEnthSerial',
-		354 : 'SquareSheetConstrainedTransP3dEnthParallel',
-		401 : 'SquareSheetShelfDiagM2dSerial',
-		402 : 'SquareSheetShelfDiagM2dParallel',
-		403 : 'SquareSheetShelfDiagM3dSerial',
-		404 : 'SquareSheetShelfDiagM3dParallel',
-		405 : 'SquareSheetShelfDiagP3dSerial',
-		406 : 'SquareSheetShelfDiagP3dParallel',
-		407 : 'SquareSheetShelfDiagS3dSerial',
-		408 : 'SquareSheetShelfDiagS3dParallel',
-		409 : 'SquareSheetShelfDiagMP3dPenaltiesSerial',
-		410 : 'SquareSheetShelfDiagMP3dPenaltiesParallel',
-		411 : 'SquareSheetShelfTherSteaSerial',
-		412 : 'SquareSheetShelfTherSteaParallel',
-		413 : 'SquareSheetShelfTherTranSerial',
-		414 : 'SquareSheetShelfTherTranParallel',
-		415 : 'SquareSheetShelfTranM2dSerial',
-		416 : 'SquareSheetShelfTranM2dParallel',
-		417 : 'SquareSheetShelfTranMP3dPenaltiesSerial',
-		418 : 'SquareSheetShelfTranMP3dPenaltiesParallel',
-		419 : 'SquareSheetShelfSteaM3dSerial',
-		420 : 'SquareSheetShelfSteaM3dParallel',
-		421 : 'SquareSheetShelfSteaP3dSerial',
-		422 : 'SquareSheetShelfSteaP3dParallel',
-		423 : 'SquareSheetShelfDiadM3dDakotaSerial',
-		424 : 'SquareSheetShelfDiadM3dDakotaParallel',
-		425 : 'SquareSheetShelfDiadM3dDakotaPartSerial',
-		426 : 'SquareSheetShelfDiadM3dDakotaPartParallel',
-		427 : 'SquareSheetShelfDiadM3dDakotaMassFluxSerial',
-		428 : 'SquareSheetShelfDiadM3dDakotaMassFluxParallel',
-		429 : 'SquareSheetShelfCMDragSteaM3dSerial',
-		430 : 'SquareSheetShelfCMDragSteaM3dParallel',
-		431 : 'SquareSheetShelfCMDragSteaP3dSerial',
-		432 : 'SquareSheetShelfCMDragSteaP3dParallel',
-		434 : 'SquareSheetShelfDiadM3dDakotaSamp',
-		435 : 'SquareSheetShelfDiadM3dDakotaAreaAverage',
-		437 : 'SquareSheetShelfDiagMP3dTilingSerial',
-		438 : 'SquareSheetShelfDiagMP3dTilingParallel',
-		439 : 'SquareSheetShelfDakotaScaledResponse',
-		440 : 'SquareSheetShelfDakotaScaledResponse',
-		441 : 'SquareSheetShelfDiagPS3dTilingSerial',
-		442 : 'SquareSheetShelfDiagPS3dTilingParallel',
-		443 : 'SquareSheetShelfDiagMS3dTilingSerial',
-		444 : 'SquareSheetShelfDiagMS3dTilingParallel',
-		445 : 'RoundSheetShelfGLMigrationM2dSerial',
-		446 : 'RoundSheetShelfGLMigrationM2dParallel',
-		447 : 'SquareSheetShelfGroundingLine2dAgressiceSerial',
-		448 : 'SquareSheetShelfGroundingLine2dAgressiceParallel',
-		449 : 'SquareSheetShelfGroundingLine2dSoftSerial',
-		450 : 'SquareSheetShelfGroundingLine2dSoftParallel',
-		451 : 'SquareSheetShelfGroundingLine3dAgressiceSerial',
-		452 : 'SquareSheetShelfGroundingLine3dAgressiceParallel',
-		453 : 'SquareSheetShelfGroundingLine3dSoftSerial',
-		454 : 'SquareSheetShelfGroundingLine3dSoftParallel',
-		455 : 'SquareSheetShelfDiagM2dNewtonSerial',
-		456 : 'SquareSheetShelfDiagM2dNewtonParallel',
-		457 : 'SquareSheetShelfDiagP3dNewtonSerial',
-		458 : 'SquareSheetShelfDiagP3dNewtonParallel',
-		459 : 'SquareSheetShelfDiagS3dNewtonSerial',
-		460 : 'SquareSheetShelfDiagS3dNewtonParallel',
-		461 : 'SquareSheetShelfSteaEnthalpyM3dSerial',
-		462 : 'SquareSheetShelfSteaEnthalpyM3dParallel',
-		463 : 'SquareSheetShelfSteaEnthalpyP3dSerial',
-		464 : 'SquareSheetShelfSteaEnthalpyP3dParallel',
-		501 : 'PigDiagM2dSerial',
-		502 : 'PigDiagM2dParallel',
-		503 : 'PigDiagP3dSerial',
-		504 : 'PigDiagP3dParallel',
-		505 : 'PigDiagS3dSerial',
-		506 : 'PigDiagS3dParallel',
-		507 : 'PigTranM2dSerial',
-		508 : 'PigTranM2dParallel',
-		509 : 'PigTranM3dSerial',
-		510 : 'PigTranM3dParallel',
-		511 : 'PigTranP3dSerial',
-		512 : 'PigTranP3dParallel',
-		513 : 'PigTranS3dSerial',
-		514 : 'PigTranS3dParallel',
-		515 : 'PigSteaM3dSerial',
-		516 : 'PigSteaM3dParallel',
-		517 : 'PigSteaP3dSerial',
-		518 : 'PigSteaP3dParallel',
-		519 : 'PigSteaS3dSerial',
-		520 : 'PigSteaS3dParallel',
-		521 : 'PigCMBS3dSerial',
-		522 : 'PigCMBS3dparallel',
-		523 : 'PigCMDragP3dSerial',
-		524 : 'PigCMDragP3dparallel',
-		525 : 'PigCMDragSteaM3dSerial',
-		526 : 'PigCMDragSteaM3dparallel',
-		527 : 'PigBamgMesh',
-		529 : 'PigTherTranSUPGSerial',
-		530 : 'PigTherTranSUPGParallel',
-		531 : 'PigTherSteaSUPGSerial',
-		532 : 'PigTherSteaSUPGParallel',
-		601 : '79NorthProg2dSerial',
-		602 : '79NorthProg2dParallel',
-		603 : '79NorthProg2dDGSerial',
-		604 : '79NorthProg2dDGParallel',
-		605 : '79NorthProg3dSerial',
-		606 : '79NorthProg3dParallel',
-		607 : '79NorthSurfSlop2dSerial',
-		608 : '79NorthSurfSlop2dParallel',
-		609 : '79NorthSurfSlop3dSerial',
-		610 : '79NorthSurfSlop3dParallel',
-		611 : '79NorthBedSlop2dSerial',
-		612 : '79NorthBedSlop2dParallel',
-		613 : '79NorthBedSlop3dSerial',
-		614 : '79NorthBedSlop3dParallel',
-		615 : '79NorthBalThic2dSerial',
-		616 : '79NorthBalThic2dParallel',
-		617 : '79NorthBalThic2dDGSerial',
-		618 : '79NorthBalThic2dDGParallel',
-		619 : '79NorthBalThic3dSerial',
-		620 : '79NorthBalThic3dParallel',
-		621 : '79NorthCMBalThic2dCGSerial',
-		622 : '79NorthCMBalThic2dCGParallel',
-		623 : '79NorthCMBalThic2dDGSerial',
-		624 : '79NorthCMBalThic2dDGParallel',
-		625 : '79NorthCMBalThicVxVyParallel',
-		626 : '79NorthCMBalThicVxVySerial',
+		101 : 'SquareShelfConstrainedDiagM2d',
+		102 : 'SquareShelfConstrainedDiagM3d',
+		103 : 'SquareShelfConstrainedDiagP3d',
+		104 : 'SquareShelfConstrainedDiagS3d',
+		105 : 'SquareShelfConstrainedProg2d',
+		106 : 'SquareShelfConstrainedProg2dDG',
+		107 : 'SquareShelfConstrainedProg3d',
+		108 : 'SquareShelfConstrainedTherStea',
+		109 : 'SquareShelfConstrainedTherTran',
+		110 : 'SquareShelfConstrainedTranM2d',
+		111 : 'SquareShelfConstrainedTranP3d',
+		112 : 'SquareShelfConstrainedSurfSlop2d',
+		113 : 'SquareShelfConstrainedSurfSlope3d',
+		114 : 'SquareShelfConstrainedBedSlop2d',
+		115 : 'SquareShelfConstrainedBedSlop3d',
+		116 : 'SquareShelfConstrainedBalThic2d',
+		117 : 'SquareShelfConstrainedBalThic3d',
+		118 : 'SquareShelfConstrainedBalThic2dDG',
+		119 : 'SquareBamgMesh',
+		120 : 'SquareShelfConstrainedEnthalpyStea',
+		121 : 'SquareShelfConstrainedEnthalpyTran',
+		122 : 'SquareShelfConstrainedTransP3dEnth',
+		201 : 'SquareShelfDiagM2d',
+		202 : 'SquareShelfDiagM3d',
+		203 : 'SquareShelfDiagP3d',
+		204 : 'SquareShelfDiagS3d',
+		205 : 'SquareShelfDiagMP3dPenalties',
+		206 : 'SquareShelfTherStea',
+		207 : 'SquareShelfTherTran',
+		208 : 'SquareShelfTranM2d',
+		209 : 'SquareShelfTranM3d',
+		210 : 'SquareShelfTranP3d',
+		211 : 'SquareShelfTranS3d',
+		212 : 'SquareShelfCMBM2d',
+		213 : 'SquareShelfCMBM3d',
+		214 : 'SquareShelfCMBP3d',
+		215 : 'SquareShelfCMBS3d',
+		216 : 'SquareShelfDiagM2dRift',
+		217 : 'SquareShelfConstrained',
+		218 : 'SquareShelfConstrainedDakotaB',
+		219 : 'SquareShelfDiagMP3dTiling',
+		220 : 'SquareShelfDiagPS3dTiling',
+		221 : 'SquareShelfDiagMS3dTiling',
+		222 : 'SquareShelfDiagM2dTransientIncrHydro',
+		223 : 'SquareShelfDiagM2dTransientIncrNonHydro',
+		224 : 'SquareShelfDiagP3dTransientIncrHydro',
+		225 : 'SquareShelfDiagP3dTransientIncrNonHydro',
+		226 : 'SquareShelfTranCflM2d',
+		227 : 'SquareShelfTranCflP3d',
+		228 : 'SquareShelfTranForceNeg2d',
+		229 : 'SquareShelfTranForcePos2d',
+		230 : 'SquareShelfTranForceNeg3d',
+		231 : 'SquareShelfTranForcePos3d',
+		232 : 'SquareShelfTherTranForcTemp',
+		233 : 'SquareShelfTranP3dForcTemp',
+		234 : 'SquareShelfTranForceNeg2dDakotaSamp',
+		235 : 'SquareShelfTranForceNeg2dDakotaLocal',
+		236 : 'SquareShelfTranIspddIsdeltaM2d',
+		237 : 'SquareShelfTranIspddIsdeltaM3d',
+		301 : 'SquareSheetConstrainedDiagM2d',
+		302 : 'SquareSheetConstrainedDiagH2d',
+		303 : 'SquareSheetConstrainedDiagHM2d',
+		304 : 'SquareSheetConstrainedDiagM3d',
+		305 : 'SquareSheetConstrainedDiagH3d',
+		306 : 'SquareSheetConstrainedDiagHM3d',
+		307 : 'SquareSheetConstrainedDiagP3d',
+		308 : 'SquareSheetConstrainedDiagS3d',
+		309 : 'SquareSheetConstrainedProg2d',
+		310 : 'SquareSheetConstrainedProg2dDG',
+		311 : 'SquareSheetConstrainedProg3d',
+		312 : 'SquareSheetConstrainedTherStea',
+		313 : 'SquareSheetConstrainedTherTran',
+		314 : 'SquareSheetConstrainedTranH2d',
+		315 : 'SquareSheetConstrainedTranH3d',
+		316 : 'SquareSheetConstrainedTranM2d',
+		317 : 'SquareSheetConstrainedTranP3d',
+		318 : 'SquareSheetConstrainedSteaH3d',
+		319 : 'SquareSheetConstrainedCMDragM2d',
+		320 : 'SquareSheetConstrainedCMDragM3d',
+		321 : 'SquareSheetConstrainedCMDragP3d',
+		322 : 'SquareSheetConstrainedCMDragS3d',
+		323 : 'SquareSheetConstrainedTranCflM2d',
+		324 : 'SquareSheetConstrainedTranCflH3d',
+		325 : 'SquareSheetConstrainedEnthalpyStea',
+		326 : 'SquareSheetConstrainedEnthalpyTran',
+		327 : 'SquareSheetConstrainedTransP3dEnth',
+		328 : 'SquareSheetConstrainedSmbGradients2d',
+		329 : 'SquareSheetConstrainedSmbGradients3d',
+		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',
@@ -320,5 +186,15 @@
 		1502 : 'SquareShelfTranSawTooth3d',
 		1601 : 'SquareShelfM2dRotation',
-		1602 : 'SquareSheetShelfP3dRotation',
+		1602 : 'SquareSheetShelfP3dRotation', 
+		3001 : 'SquareShelfConstrainedDiagM2dAdolc',
+		3002 : 'SquareShelfConstrainedDiagM3dAdolc',
+		3003 : 'SquareShelfConstrainedDiagP3dAdolc',
+		3004 : 'SquareShelfConstrainedDiagS3dAdolc',
+		3005 : 'SquareShelfConstrainedProg2dAdolc',
+		3006 : 'SquareShelfConstrainedProg2dDGAdolc',
+		3007 : 'SquareShelfConstrainedProg3dAdolc',
+		3008 : 'SquareShelfConstrainedTherSteaAdolc',
+		3009 : 'SquareShelfConstrainedTherTranAdolc',
+		3010 : 'SquareShelfConstrainedTranM2dAdolc',
 	}
 
Index: /issm/trunk/test/NightlyRun/Makefile
===================================================================
--- /issm/trunk/test/NightlyRun/Makefile	(revision 13394)
+++ /issm/trunk/test/NightlyRun/Makefile	(revision 13395)
@@ -1,2 +1,2 @@
 clean: 
-	rm -rf *.tar.gz *.bin *.errlog *.outlog  *.outbin *.petsc *.queue *.run valgrind.log* *.bat *.lock
+	rm -rf *.tar.gz *.bin *.errlog *.outlog  *.outbin *.petsc *.queue *.run valgrind.log* *.bat *.lock qmu*
Index: /issm/trunk/test/NightlyRun/README
===================================================================
--- /issm/trunk/test/NightlyRun/README	(revision 13394)
+++ /issm/trunk/test/NightlyRun/README	(revision 13395)
@@ -31,7 +31,6 @@
 6: 79North
 Add the id and testname in IdToName.m (incresing order)
-We try not to create to many .par and .exp files, so try to use the existing ones as much as possible.
+We try not to create too many .par and .exp files, so try to use the existing ones as much as possible.
 To modify some characteristics, do it in the testxxx.m file.
-The testxxx_nightly.m is used to define the parameters you want to check in the nightlyruns.
-Specify the field_names the field_values and the tolerance in this file.
-Don't forget to commit the archive (Archivexxx in ../Archives)
+Specify the field_names the field_values and the tolerance at the end of the test file.
+Don't forget to commit the archive (Archivexxx.nc in ../Archives)
Index: /issm/trunk/test/NightlyRun/ad.m
===================================================================
--- /issm/trunk/test/NightlyRun/ad.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/ad.m	(revision 13395)
@@ -0,0 +1,26 @@
+md=triangle(model,'../Exp/Square.exp',50000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.diagnostic.requested_outputs=StressTensorEnum;
+md.autodiff.isautodiff=true;
+md.autodiff.independents={'Thickness','Surface'};
+md.autodiff.dependents={'IceVolume'};
+%md=solve(md,TransientSolutionEnum);
+md=solve(md,PrognosticSolutionEnum);
+
+%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.TransientSolution.Vx),...
+	(md.results.TransientSolution.Vy),...
+	(md.results.TransientSolution.Vel),...
+	(md.results.TransientSolution.Pressure),...
+	(md.results.TransientSolution.StressTensorxx),...
+	(md.results.TransientSolution.StressTensoryy),...
+	(md.results.TransientSolution.StressTensorxy),...
+	};
Index: /issm/trunk/test/NightlyRun/runme.m
===================================================================
--- /issm/trunk/test/NightlyRun/runme.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/runme.m	(revision 13395)
@@ -17,4 +17,5 @@
 %                      'thermal': validation of thermal tests
 %                      'mesh'   : validation of mesh tests
+%                      'adolc'   : validation of adolc tests
 %                      ...
 %      'procedure'     'check' : run the test (default)
@@ -34,5 +35,5 @@
 
 %Check inputs
-% {{{1
+% {{{
 if nargout>1
 	help runme
@@ -45,12 +46,12 @@
 
 %Process options
-%GET benchmark {{{1
+%GET benchmark {{{
 benchmark=getfieldvalue(options,'benchmark','nightly');
-if ~ismember(benchmark,{'all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing'})
+if ~ismember(benchmark,{'all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing','adolc'})
 	disp('runme warning: benchmark not supported, defaulting to test ''nightly''')
 	benchmark='nightly';
 end
 % }}}
-%GET procedure {{{1
+%GET procedure {{{
 procedure=getfieldvalue(options,'procedure','check');
 if ~ismember(procedure,{'check','update'})
@@ -59,5 +60,5 @@
 end
 % }}}
-%GET output {{{1
+%GET output {{{
 output=getfieldvalue(options,'output','none');
 if ~ismember(output,{'nightly','daily','none'})
@@ -66,17 +67,17 @@
 end
 % }}}
-%GET RANK and NUMPROCS for mutlithreaded runs  {{{1
+%GET RANK and NUMPROCS for mutlithreaded runs  {{{
 rank=getfieldvalue(options,'rank',1);
 numprocs=getfieldvalue(options,'numprocs',1);
 if (numprocs<rank), numprocs=1; end
 % }}}
-%GET ids  {{{1
-list=dir;%use dir, as it seems to act OS independent
+%GET ids  {{{
+flist=dir;%use dir, as it seems to act OS independent
 list_ids=[];
-for i=1:numel(list),
-	if ( strncmp(list(i).name,'test',4) &...                         %File name must start with 'test'
-			strncmp(fliplr(list(i).name),fliplr('.m'),2)&...           %File name must end by '.m'
-			~strcmp(list(i).name,'test.m'))                            %File name must be different than 'test.m'
-		list_ids(end+1)=eval(list(i).name(5:end-2));                  %Keep test id only (skip 'test' and '.m')
+for i=1:numel(flist),
+	if ( strncmp(flist(i).name,'test',4) &...                         %File name must start with 'test'
+			strncmp(fliplr(flist(i).name),fliplr('.m'),2)&...           %File name must end by '.m'
+			~strcmp(flist(i).name,'test.m'))                            %File name must be different than 'test.m'
+		list_ids(end+1)=eval(flist(i).name(5:end-2));                  %Keep test id only (skip 'test' and '.m')
 	end
 end
@@ -87,5 +88,5 @@
 test_ids=intersect(test_ids,list_ids);
 % }}}
-%GET exclude {{{1
+%GET exclude {{{
 exclude_ids=getfieldvalue(options,'exclude',[]);
 exclude_ids=[exclude_ids];
@@ -93,5 +94,5 @@
 test_ids(pos)=[];
 % }}}
-%Process Ids according to benchmarks{{{1
+%Process Ids according to benchmarks{{{
 if strcmpi(benchmark,'nightly'),
 	test_ids=intersect(test_ids,[1:999]);
@@ -104,4 +105,6 @@
 elseif strcmpi(benchmark,'mesh'),
 	test_ids=intersect(test_ids,[1401:1499]);
+elseif strcmpi(benchmark,'adolc'),
+	test_ids=intersect(test_ids,[3001:3010]);
 elseif strcmpi(benchmark,'validation'),
 	test_ids=intersect(test_ids,[1001:1999]);
@@ -124,21 +127,17 @@
 		archive_name=['Archive' num2str(id) ];
 		if strcmpi(procedure,'update'),
-
-			if ~strcmp(oshostname(),'larsen');
-				error(['Nightly run archives must be saved on "larsen" (hostname is "' oshostname() '")']);
-			end
+			delete(['../Archives/' archive_name '.nc'])
 			for k=1:length(field_names),
 				field=field_values{k};
-				eval([ archive_name '_field' num2str(k) ' =  field ;']);
+				% matlab writes the dimensions reversed and matrices transposed into netcdf, so compensate for that
+				nccreate(['../Archives/' archive_name '.nc'],[archive_name '_field' num2str(k)],...
+				         'Dimensions',{[archive_name '_field' num2str(k) '_2'] size(field,2) [archive_name '_field' num2str(k) '_1'] size(field,1)},...
+				         'Format','classic');
+				ncwrite(['../Archives/' archive_name '.nc'],[archive_name '_field' num2str(k)],transpose(field));
 			end
-			eval(['save ../Archives/' archive_name ' ' archive_name '_field*']);
-			disp(sprintf(['File ./../Archives/' archive_name ' saved\n']));
+			disp(sprintf(['File ./../Archives/' archive_name '.nc saved\n']));
 
 		%ELSE: CHECK TEST
 		else,
-
-			%load archive
-			load(['../Archives/' archive_name ]);
-
 			for k=1:length(field_names),
 
@@ -150,5 +149,6 @@
 
 					%compare to archive
-					eval(['archive=' archive_name '_field' num2str(k) ';']);
+					% matlab reads the dimensions reversed and matrices transposed from netcdf, so compensate for that
+					archive=transpose(ncread(['../Archives/' archive_name '.nc'],[archive_name '_field' num2str(k)]));
 					error_diff=full(max(abs(archive(:)-field(:)))/(max(abs(archive))+eps));
 
Index: /issm/trunk/test/NightlyRun/runme.py
===================================================================
--- /issm/trunk/test/NightlyRun/runme.py	(revision 13394)
+++ /issm/trunk/test/NightlyRun/runme.py	(revision 13395)
@@ -1,34 +1,3 @@
 #! /usr/bin/env python
-"""
-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')
-"""
-
 import os
 import glob
@@ -40,49 +9,71 @@
 
 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
+	from MatlabFuncs import strcmpi
+	from MatlabFuncs import ismember
 
 	#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']:
+	#GET benchmark {{{
+	if not ismember(benchmark,['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']:
+	#GET procedure {{{
+	if not ismember(procedure,['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']:
+	#GET output {{{
+	if not ismember(output,['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
+	#GET RANK and NUMPROCS for multithreaded runs {{{
 	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
+	#GET ids  {{{
 	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
+	#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
+	#print 'list_ids after parallelrange =',list_ids
 
 	if id:
@@ -94,8 +85,7 @@
 	else:
 		test_ids=set(list_ids)
-#	print 'test_ids after list =',test_ids
-	# }}}
-
-	#GET exclude {{{1
+	#print 'test_ids after list =',test_ids
+	# }}}
+	#GET exclude {{{
 	if exclude:
 		if isinstance(exclude,list):
@@ -106,24 +96,23 @@
 #	print 'test_ids after exclude =',test_ids
 	# }}}
-
-	#Process Ids according to benchmarks {{{1
-	if   benchmark.lower() == 'nightly':
+	#Process Ids according to benchmarks {{{
+	if   strcmpi(benchmark,'nightly'):
 		test_ids=test_ids.intersection(set(range(1,1000)))
-	elif benchmark.lower() == 'ismip':
+	elif strcmpi(benchmark,'ismip'):
 		test_ids=test_ids.intersection(set(range(1101,1200)))
-	elif benchmark.lower() == 'eismint':
+	elif strcmpi(benchmark,'eismint'):
 		test_ids=test_ids.intersection(set(range(1201,1300)))
-	elif benchmark.lower() == 'thermal':
+	elif strcmpi(benchmark,'thermal'):
 		test_ids=test_ids.intersection(set(range(1301,1400)))
-	elif benchmark.lower() == 'mesh':
+	elif strcmpi(benchmark,'mesh'):
 		test_ids=test_ids.intersection(set(range(1401,1500)))
-	elif benchmark.lower() == 'validation':
+	elif strcmpi(benchmark,'validation'):
 		test_ids=test_ids.intersection(set(range(1001,2000)))
-	elif benchmark.lower() == 'tranforcing':
+	elif strcmpi(benchmark,'tranforcing'):
 		test_ids=test_ids.intersection(set(range(1501,1503)))
-#	print 'test_ids after benchmark =',test_ids
+	#print 'test_ids after benchmark =',test_ids
 	test_ids=list(test_ids)
 	test_ids.sort()
-	print 'test_ids after sort =',test_ids
+	#print 'test_ids after sort =',test_ids
 	# }}}
 
@@ -140,17 +129,19 @@
 			#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')
+			if strcmpi(procedure,'update'):
+
+				os.remove(os.path.join('..','Archives',archive_name+'.nc'))
+				f = netCDF4.Dataset(os.path.join('..','Archives',archive_name+'.nc'),'w',format='NETCDF3_CLASSIC')
 				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'))
+					if len(field.shape) == 1:
+						if numpy.size(field):
+							field=field.reshape(numpy.size(field),1)
+						else:
+							field=field.reshape(0,0)
+					# Matlab uses base 1, so use base 1 in labels
+					f.createDimension(archive_name+'_field'+str(k+1)+'_1',numpy.size(field,0))
+					f.createDimension(archive_name+'_field'+str(k+1)+'_2',numpy.size(field,1))
+					v = f.createVariable(archive_name+'_field'+str(k+1),field.dtype,(archive_name+'_field'+str(k+1)+'_1',archive_name+'_field'+str(k+1)+'_2'))
 					v[:] = field
 				f.close()
@@ -162,5 +153,4 @@
 				#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:
@@ -171,23 +161,23 @@
 					try:
 						#Get field and tolerance
-						field=numpy.array(field_values[k],dtype=float)
-#						print 'field =',field
+						field=numpy.array(field_values[k])
+						if len(field.shape) == 1:
+							if numpy.size(field):
+								field=field.reshape(numpy.size(field),1)
+							else:
+								field=field.reshape(0,0)
 						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
+						# Matlab uses base 1, so use base 1 in labels
+						if archive_name+'_field'+str(k+1) in f.variables:
+							archive=f.variables[archive_name+'_field'+str(k+1)][:]
+						else:
+							raise NameError("Field name '"+archive_name+'_field'+str(k+1)+"' does not exist in archive file.")
+						error_diff=numpy.amax(numpy.abs(archive-field),axis=0)/ \
+								   (numpy.amax(numpy.abs(archive),axis=0)+sys.float_info.epsilon)
 
 						#disp test result
-						if (error_diff>tolerance):
+						if (numpy.any(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)
@@ -201,12 +191,12 @@
 						directory=os.getcwd().split('/')    #  not used?
 						message=me2
-						if   output.lower() == 'nightly':
-							fid=open(os.path.join(ISSM_DIR,'nightlylog','matlaberror.log'), 'a')
+						if   strcmpi(output,'nightly'):
+							fid=open(os.path.join(ISSM_DIR,'nightlylog','pythonerror.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')
+						elif strcmpi(output,'daily'):
+							fid=open(os.path.join(ISSM_DIR,'dailylog','pythonerror.log'), 'a')
 							fid.write('%s' % message)
 							fid.write('\n------------------------------------------------------------------\n')
@@ -224,12 +214,12 @@
 			directory=os.getcwd().split('/')    #  not used?
 			message=me
-			if   output.lower() == 'nightly':
-				fid=open(os.path.join(ISSM_DIR+'nightlylog','matlaberror.log'), 'a')
+			if   strcmpi(output,'nightly'):
+				fid=open(os.path.join(ISSM_DIR+'nightlylog','pythonerror.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')
+			elif strcmpi(output,'daily'):
+				fid=open(os.path.join(ISSM_DIR+'dailylog','pythonerror.log'), 'a')
 				fid.write('%s' % message)
 				fid.write('\n------------------------------------------------------------------\n')
@@ -247,8 +237,9 @@
 	return
 
+import argparse
 if __name__ == '__main__':
 	if 'PYTHONSTARTUP' in os.environ:
 		PYTHONSTARTUP=os.environ['PYTHONSTARTUP']
-		print 'PYTHONSTARTUP =',PYTHONSTARTUP
+		#print 'PYTHONSTARTUP =',PYTHONSTARTUP
 		if os.path.exists(PYTHONSTARTUP):
 			try:
@@ -259,5 +250,4 @@
 			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=[])
Index: /issm/trunk/test/NightlyRun/test101.m
===================================================================
--- /issm/trunk/test/NightlyRun/test101.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test101.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test101.py
===================================================================
--- /issm/trunk/test/NightlyRun/test101.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test101.py	(revision 13395)
@@ -0,0 +1,31 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',50000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+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'][1]['Vx'],\
+	md.results['DiagnosticSolution'][1]['Vy'],\
+	md.results['DiagnosticSolution'][1]['Vel'],\
+	md.results['DiagnosticSolution'][1]['Pressure'],\
+	md.results['DiagnosticSolution'][1]['StressTensorxx'],\
+	md.results['DiagnosticSolution'][1]['StressTensoryy'],\
+	md.results['DiagnosticSolution'][1]['StressTensorxy'],\
+	]
Index: /issm/trunk/test/NightlyRun/test102.m
===================================================================
--- /issm/trunk/test/NightlyRun/test102.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test102.m	(revision 13395)
@@ -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: /issm/trunk/test/NightlyRun/test102.py
===================================================================
--- /issm/trunk/test/NightlyRun/test102.py	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test102.py	(revision 13395)
@@ -3,22 +3,26 @@
 from setmask import *
 from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
 
-md=model()
-md=triangle(md,'../Exp/Square.exp',50000)
+md=triangle(model(),'../Exp/Square.exp',180000)
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(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',\
-	'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.Vel],\
-	[md.results.DiagnosticSolution.Pressure],\
-	[md.results.DiagnosticSolution.StressTensorxx],\
-	[md.results.DiagnosticSolution.StressTensoryy],\
-	[md.results.DiagnosticSolution.StressTensorxy],\
+	md.results['DiagnosticSolution'][1]['Vx'],\
+	md.results['DiagnosticSolution'][1]['Vy'],\
+	md.results['DiagnosticSolution'][1]['Vz'],\
+	md.results['DiagnosticSolution'][1]['Vel'],\
+	md.results['DiagnosticSolution'][1]['Pressure'],\
 	]
+
Index: /issm/trunk/test/NightlyRun/test103.m
===================================================================
--- /issm/trunk/test/NightlyRun/test103.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test103.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test103.py
===================================================================
--- /issm/trunk/test/NightlyRun/test103.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test103.py	(revision 13395)
@@ -0,0 +1,36 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(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'][1]['Vx'],\
+	md.results['DiagnosticSolution'][1]['Vy'],\
+	md.results['DiagnosticSolution'][1]['Vz'],\
+	md.results['DiagnosticSolution'][1]['Vel'],\
+	md.results['DiagnosticSolution'][1]['Pressure'],\
+	md.results['DiagnosticSolution'][1]['StressTensorxx'],\
+	md.results['DiagnosticSolution'][1]['StressTensoryy'],\
+	md.results['DiagnosticSolution'][1]['StressTensorzz'],\
+	md.results['DiagnosticSolution'][1]['StressTensorxy'],\
+	md.results['DiagnosticSolution'][1]['StressTensorxz'],\
+	md.results['DiagnosticSolution'][1]['StressTensoryz'],\
+	]
Index: /issm/trunk/test/NightlyRun/test104.m
===================================================================
--- /issm/trunk/test/NightlyRun/test104.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test104.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test104.py
===================================================================
--- /issm/trunk/test/NightlyRun/test104.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test104.py	(revision 13395)
@@ -0,0 +1,27 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,2)
+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-08,1e-08,1e-07,1e-08,1e-08]
+field_values=[\
+	md.results['DiagnosticSolution'][1]['Vx'],\
+	md.results['DiagnosticSolution'][1]['Vy'],\
+	md.results['DiagnosticSolution'][1]['Vz'],\
+	md.results['DiagnosticSolution'][1]['Vel'],\
+	md.results['DiagnosticSolution'][1]['Pressure'],\
+	]
Index: /issm/trunk/test/NightlyRun/test105.m
===================================================================
--- /issm/trunk/test/NightlyRun/test105.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test105.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test105.py
===================================================================
--- /issm/trunk/test/NightlyRun/test105.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test105.py	(revision 13395)
@@ -0,0 +1,22 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=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'][1]['Thickness'],\
+	]
Index: /issm/trunk/test/NightlyRun/test106.m
===================================================================
--- /issm/trunk/test/NightlyRun/test106.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test106.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test106.py
===================================================================
--- /issm/trunk/test/NightlyRun/test106.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test106.py	(revision 13395)
@@ -0,0 +1,26 @@
+from model import *
+from triangle import *
+from meshconvert import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=meshconvert(md)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=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())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results['PrognosticSolution'][1]['Thickness'],\
+	]
Index: /issm/trunk/test/NightlyRun/test107.m
===================================================================
--- /issm/trunk/test/NightlyRun/test107.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test107.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test107.py
===================================================================
--- /issm/trunk/test/NightlyRun/test107.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test107.py	(revision 13395)
@@ -0,0 +1,23 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'macayeal','all')
+md.extrude(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'][1]['Thickness'],\
+	]
Index: /issm/trunk/test/NightlyRun/test108.m
===================================================================
--- /issm/trunk/test/NightlyRun/test108.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test108.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test108.py
===================================================================
--- /issm/trunk/test/NightlyRun/test108.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test108.py	(revision 13395)
@@ -0,0 +1,25 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1)
+md=setflowequation(md,'macayeal','all')
+md.timestepping.time_step=0
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,ThermalSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Temperature','BasalforcingsMeltingRate']
+field_tolerances=[1e-13,1e-13]
+field_values=[\
+	md.results['ThermalSolution'][1]['Temperature'],\
+	md.results['ThermalSolution'][1]['BasalforcingsMeltingRate'],\
+	]
Index: /issm/trunk/test/NightlyRun/test109.m
===================================================================
--- /issm/trunk/test/NightlyRun/test109.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test109.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test109.py
===================================================================
--- /issm/trunk/test/NightlyRun/test109.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test109.py	(revision 13395)
@@ -0,0 +1,28 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(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/trunk/test/NightlyRun/test110.m
===================================================================
--- /issm/trunk/test/NightlyRun/test110.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test110.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test110.py
===================================================================
--- /issm/trunk/test/NightlyRun/test110.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test110.py	(revision 13395)
@@ -0,0 +1,49 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'macayeal','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','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['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/trunk/test/NightlyRun/test1107.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1107.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test1107.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test1108.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1108.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test1108.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test111.m
===================================================================
--- /issm/trunk/test/NightlyRun/test111.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test111.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test111.py
===================================================================
--- /issm/trunk/test/NightlyRun/test111.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test111.py	(revision 13395)
@@ -0,0 +1,62 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(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/trunk/test/NightlyRun/test112.m
===================================================================
--- /issm/trunk/test/NightlyRun/test112.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test112.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test112.py
===================================================================
--- /issm/trunk/test/NightlyRun/test112.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test112.py	(revision 13395)
@@ -0,0 +1,23 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=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'][1]['SurfaceSlopeX'],\
+	md.results['SurfaceSlopeSolution'][1]['SurfaceSlopeY'],\
+	]
Index: /issm/trunk/test/NightlyRun/test113.m
===================================================================
--- /issm/trunk/test/NightlyRun/test113.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test113.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test113.py
===================================================================
--- /issm/trunk/test/NightlyRun/test113.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test113.py	(revision 13395)
@@ -0,0 +1,24 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(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'][1]['SurfaceSlopeX'],\
+	md.results['SurfaceSlopeSolution'][1]['SurfaceSlopeY'],\
+	]
Index: /issm/trunk/test/NightlyRun/test114.m
===================================================================
--- /issm/trunk/test/NightlyRun/test114.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test114.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test114.py
===================================================================
--- /issm/trunk/test/NightlyRun/test114.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test114.py	(revision 13395)
@@ -0,0 +1,23 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=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'][1]['BedSlopeX'],\
+	md.results['BedSlopeSolution'][1]['BedSlopeY'],\
+	]
Index: /issm/trunk/test/NightlyRun/test115.m
===================================================================
--- /issm/trunk/test/NightlyRun/test115.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test115.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test115.py
===================================================================
--- /issm/trunk/test/NightlyRun/test115.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test115.py	(revision 13395)
@@ -0,0 +1,24 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(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'][1]['BedSlopeX'],\
+	md.results['BedSlopeSolution'][1]['BedSlopeY'],\
+	]
Index: /issm/trunk/test/NightlyRun/test116.m
===================================================================
--- /issm/trunk/test/NightlyRun/test116.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test116.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test116.py
===================================================================
--- /issm/trunk/test/NightlyRun/test116.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test116.py	(revision 13395)
@@ -0,0 +1,26 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+#Add boundary conditions on thickness on the border
+pos=numpy.nonzero(md.mesh.vertexonboundary)
+md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
+md=setflowequation(md,'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'][1]['Thickness'],\
+	]
Index: /issm/trunk/test/NightlyRun/test117.m
===================================================================
--- /issm/trunk/test/NightlyRun/test117.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test117.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test117.py
===================================================================
--- /issm/trunk/test/NightlyRun/test117.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test117.py	(revision 13395)
@@ -0,0 +1,27 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(5,1)
+#Add boundary conditions on thickness on the border
+pos=numpy.nonzero(md.mesh.vertexonboundary)
+md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
+md=setflowequation(md,'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'][1]['Thickness'],\
+	]
Index: /issm/trunk/test/NightlyRun/test118.m
===================================================================
--- /issm/trunk/test/NightlyRun/test118.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test118.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test118.py
===================================================================
--- /issm/trunk/test/NightlyRun/test118.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test118.py	(revision 13395)
@@ -0,0 +1,26 @@
+from model import *
+from triangle import *
+from meshconvert import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=meshconvert(md)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.balancethickness.stabilization=3
+md.initialization.vy=md.initialization.vy+400.
+md=setflowequation(md,'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'][1]['Thickness'],\
+	]
Index: /issm/trunk/test/NightlyRun/test119.m
===================================================================
--- /issm/trunk/test/NightlyRun/test119.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test119.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test120.m
===================================================================
--- /issm/trunk/test/NightlyRun/test120.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test120.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test120.py
===================================================================
--- /issm/trunk/test/NightlyRun/test120.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test120.py	(revision 13395)
@@ -0,0 +1,28 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1)
+md=setflowequation(md,'macayeal','all')
+md.timestepping.time_step=0
+md.cluster=generic('name',oshostname(),'np',3)
+md.initialization.waterfraction=numpy.zeros(md.mesh.numberofvertices)
+md=solve(md,EnthalpySolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Enthalpy','Waterfraction','Temperature']
+field_tolerances=[1e-13,1e-10,1e-13]
+field_values=[\
+	md.results['EnthalpySolution'][1]['Enthalpy'],\
+	md.results['EnthalpySolution'][1]['Waterfraction'],\
+	md.results['EnthalpySolution'][1]['Temperature'],\
+	]
Index: /issm/trunk/test/NightlyRun/test121.m
===================================================================
--- /issm/trunk/test/NightlyRun/test121.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test121.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test121.py
===================================================================
--- /issm/trunk/test/NightlyRun/test121.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test121.py	(revision 13395)
@@ -0,0 +1,39 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1)
+md=setflowequation(md,'macayeal','all')
+md.cluster=generic('name',oshostname(),'np',3);
+md.initialization.waterfraction=numpy.zeros(md.mesh.numberofvertices)
+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/trunk/test/NightlyRun/test122.m
===================================================================
--- /issm/trunk/test/NightlyRun/test122.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test122.m	(revision 13395)
@@ -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: /issm/trunk/test/NightlyRun/test122.py
===================================================================
--- /issm/trunk/test/NightlyRun/test122.py	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test122.py	(revision 13395)
@@ -0,0 +1,63 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(3,1)
+md=setflowequation(md,'pattyn','all')
+md.initialization.waterfraction=numpy.zeros(md.mesh.numberofvertices)
+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: sm/trunk/test/NightlyRun/test124.m
===================================================================
--- /issm/trunk/test/NightlyRun/test124.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test126.m
===================================================================
--- /issm/trunk/test/NightlyRun/test126.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test128.m
===================================================================
--- /issm/trunk/test/NightlyRun/test128.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test130.m
===================================================================
--- /issm/trunk/test/NightlyRun/test130.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test132.m
===================================================================
--- /issm/trunk/test/NightlyRun/test132.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test134.m
===================================================================
--- /issm/trunk/test/NightlyRun/test134.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test136.m
===================================================================
--- /issm/trunk/test/NightlyRun/test136.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test137.m
===================================================================
--- /issm/trunk/test/NightlyRun/test137.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test140.m
===================================================================
--- /issm/trunk/test/NightlyRun/test140.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test142.m
===================================================================
--- /issm/trunk/test/NightlyRun/test142.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test144.m
===================================================================
--- /issm/trunk/test/NightlyRun/test144.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test201.m
===================================================================
--- /issm/trunk/test/NightlyRun/test201.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test201.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test202.m
===================================================================
--- /issm/trunk/test/NightlyRun/test202.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test202.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test203.m
===================================================================
--- /issm/trunk/test/NightlyRun/test203.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test203.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test204.m
===================================================================
--- /issm/trunk/test/NightlyRun/test204.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test204.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test205.m
===================================================================
--- /issm/trunk/test/NightlyRun/test205.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test205.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test206.m
===================================================================
--- /issm/trunk/test/NightlyRun/test206.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test206.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test207.m
===================================================================
--- /issm/trunk/test/NightlyRun/test207.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test207.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test208.m
===================================================================
--- /issm/trunk/test/NightlyRun/test208.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test208.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test209.m
===================================================================
--- /issm/trunk/test/NightlyRun/test209.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test209.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test210.m
===================================================================
--- /issm/trunk/test/NightlyRun/test210.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test210.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test211.m
===================================================================
--- /issm/trunk/test/NightlyRun/test211.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test211.m	(revision 13395)
@@ -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,...
+	2e-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,2e-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/trunk/test/NightlyRun/test212.m
===================================================================
--- /issm/trunk/test/NightlyRun/test212.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test212.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test213.m
===================================================================
--- /issm/trunk/test/NightlyRun/test213.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test213.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test214.m
===================================================================
--- /issm/trunk/test/NightlyRun/test214.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test214.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test215.m
===================================================================
--- /issm/trunk/test/NightlyRun/test215.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test215.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test216.m
===================================================================
--- /issm/trunk/test/NightlyRun/test216.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test216.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test217.m
===================================================================
--- /issm/trunk/test/NightlyRun/test217.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test217.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test218.m
===================================================================
--- /issm/trunk/test/NightlyRun/test218.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test218.m	(revision 13395)
@@ -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.qmu.results=md.results.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/trunk/test/NightlyRun/test219.m
===================================================================
--- /issm/trunk/test/NightlyRun/test219.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test219.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test220.m
===================================================================
--- /issm/trunk/test/NightlyRun/test220.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test220.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test221.m
===================================================================
--- /issm/trunk/test/NightlyRun/test221.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test221.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test222.m
===================================================================
--- /issm/trunk/test/NightlyRun/test222.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test222.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test223.m
===================================================================
--- /issm/trunk/test/NightlyRun/test223.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test223.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test224.m
===================================================================
--- /issm/trunk/test/NightlyRun/test224.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test224.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test225.m
===================================================================
--- /issm/trunk/test/NightlyRun/test225.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test225.m	(revision 13395)
@@ -0,0 +1,50 @@
+md=triangle(model,'../Exp/Square.exp',200000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md.geometry.bed=md.geometry.bed+50; md.geometry.surface=md.geometry.surface+50;
+md=extrude(md,3,1);
+md=setflowequation(md,'pattyn','all');
+md.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/trunk/test/NightlyRun/test226.m
===================================================================
--- /issm/trunk/test/NightlyRun/test226.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test226.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test227.m
===================================================================
--- /issm/trunk/test/NightlyRun/test227.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test227.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test228.m
===================================================================
--- /issm/trunk/test/NightlyRun/test228.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test228.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test229.m
===================================================================
--- /issm/trunk/test/NightlyRun/test229.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test229.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test230.m
===================================================================
--- /issm/trunk/test/NightlyRun/test230.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test230.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test231.m
===================================================================
--- /issm/trunk/test/NightlyRun/test231.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test231.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test232.m
===================================================================
--- /issm/trunk/test/NightlyRun/test232.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test232.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test233.m
===================================================================
--- /issm/trunk/test/NightlyRun/test233.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test233.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test234.m
===================================================================
--- /issm/trunk/test/NightlyRun/test234.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test234.m	(revision 13395)
@@ -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.qmu.results=md.results.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/trunk/test/NightlyRun/test235.m
===================================================================
--- /issm/trunk/test/NightlyRun/test235.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test235.m	(revision 13395)
@@ -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.qmu.results=md.results.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/trunk/test/NightlyRun/test236.m
===================================================================
--- /issm/trunk/test/NightlyRun/test236.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test236.m	(revision 13395)
@@ -1,92 +1,87 @@
-md=squaremesh(model,1000000,1000000,5,5);
+md=triangle(model,'../Exp/Square.exp',150000);
 md=setmask(md,'all','');
+
+% Use of ispdd and isdelta18o methods
+md.surfaceforcings.ispdd=1;
+md.surfaceforcings.isdelta18o=1;
+
 md=parameterize(md,'../Par/SquareShelf.par');
+
+% Add temperature, precipitation and delta18o needed to measure the surface mass balance
+% creating delta18o
+load '../Data/delta18o.data'
+md.surfaceforcings.delta18o=delta18o;
+%  creating delta18oSurface
+md.surfaceforcings.delta18o_surface(1,1:(length(delta18o))) = 0;
+md.surfaceforcings.delta18o_surface(2,:) = delta18o(2,:);
+
+% creating Present day and lgm temperatures
+% Same temperature over the all region :
+imonth=0:11;
+tmonth(1:12)=238.15+20;
+for imonth=0:11
+    md.surfaceforcings.temperatures_presentday(1:md.mesh.numberofvertices,imonth+1)=tmonth(imonth+1);
+    md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,imonth+1)=tmonth(imonth+1)-20;
+    % Time for the last line:
+    md.surfaceforcings.temperatures_presentday(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+    md.surfaceforcings.temperatures_lgm(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+end
+
+% creating initialization and spc temperatures initialization and spc
+md.thermal.spctemperature=mean(md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,1:12),2); %-10*ones(md.mesh.numberofvertices,1);
+md.thermal.spctemperature=repmat(md.thermal.spctemperature,1,md.timestepping.final_time/md.timestepping.time_step);
+itemp = 0:md.timestepping.time_step:md.timestepping.final_time-md.timestepping.time_step;
+md.thermal.spctemperature(md.mesh.numberofvertices+1,:)=itemp;
+
+md.initialization.temperature=md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,1); %*ones(md.mesh.numberofvertices,1);
+
+% creating precipitation
+for imonth=0:11
+    md.surfaceforcings.precipitations_presentday(1:md.mesh.numberofvertices,imonth+1)=-0.4*10^(-6)*md.mesh.y+0.5;
+    md.surfaceforcings.precipitations_presentday(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+end
+
+% time steps and resolution
+md.timestepping.time_step=20;
+md.timestepping.final_time= 60;
+
+% 
 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
-md=tres(md,'dakota');
-md.results.dakota.importancefactors=importancefactors(md,'scaled_MaterialsRheologyB','MaxVel')';
-field_names     ={'importancefactors'};
-field_tolerances={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-13,1e-13,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).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).SurfaceforcingsMonthlytemperatures),...
+	(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).SurfaceforcingsMonthlytemperatures),...
+	(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).SurfaceforcingsMonthlytemperatures),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
 	};
Index: /issm/trunk/test/NightlyRun/test237.m
===================================================================
--- /issm/trunk/test/NightlyRun/test237.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test237.m	(revision 13395)
@@ -0,0 +1,101 @@
+md=triangle(model,'../Exp/Square.exp',600000);%180000
+md=setmask(md,'all','');
+
+% Use of ispdd and isdelta18o methods
+md.surfaceforcings.ispdd=1;
+md.surfaceforcings.isdelta18o=1;
+
+md=parameterize(md,'../Par/SquareShelf.par');
+
+% Add temperature, precipitation and delta18o needed to measure the surface mass balance
+% creating delta18o
+load '../Data/delta18o.data'
+md.surfaceforcings.delta18o=delta18o;
+%  creating delta18oSurface
+md.surfaceforcings.delta18o_surface(1,1:(length(delta18o))) = 0;
+md.surfaceforcings.delta18o_surface(2,:) = delta18o(2,:);
+
+% creating Present day and lgm temperatures
+% Same temperature over the all region :
+imonth=0:11;
+tmonth(1:12)=238.15+20;
+for imonth=0:11
+    md.surfaceforcings.temperatures_presentday(1:md.mesh.numberofvertices,imonth+1)=tmonth(imonth+1);
+    md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,imonth+1)=tmonth(imonth+1)-20;
+    % Time for the last line:
+    md.surfaceforcings.temperatures_presentday(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+    md.surfaceforcings.temperatures_lgm(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+end
+
+% creating initialization and spc temperatures initialization and spc
+md.thermal.spctemperature=mean(md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,1:12),2); %-10*ones(md.mesh.numberofvertices,1);
+md.thermal.spctemperature=repmat(md.thermal.spctemperature,1,md.timestepping.final_time/md.timestepping.time_step);
+itemp = 0:md.timestepping.time_step:md.timestepping.final_time-md.timestepping.time_step;
+md.thermal.spctemperature(md.mesh.numberofvertices+1,:)=itemp;
+
+md.initialization.temperature=md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,1); %*ones(md.mesh.numberofvertices,1);
+
+% creating precipitation
+for imonth=0:11
+    md.surfaceforcings.precipitations_presentday(1:md.mesh.numberofvertices,imonth+1)=-0.4*10^(-6)*md.mesh.y+0.5;
+    md.surfaceforcings.precipitations_presentday(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+end
+
+% time steps and resolution
+md.timestepping.time_step=20;
+md.settings.output_frequency=1;
+md.timestepping.final_time= 60;
+
+%
+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(1).SurfaceforcingsMonthlytemperatures),...
+	(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).Temperature),...
+	(md.results.TransientSolution(2).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(2).SurfaceforcingsMonthlytemperatures),...
+	(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).Temperature),...
+	(md.results.TransientSolution(3).BasalforcingsMeltingRate),...
+	(md.results.TransientSolution(3).SurfaceforcingsMonthlytemperatures),...
+	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
+	};
Index: sm/trunk/test/NightlyRun/test238.m
===================================================================
--- /issm/trunk/test/NightlyRun/test238.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test240.m
===================================================================
--- /issm/trunk/test/NightlyRun/test240.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test242.m
===================================================================
--- /issm/trunk/test/NightlyRun/test242.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test244.m
===================================================================
--- /issm/trunk/test/NightlyRun/test244.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test246.m
===================================================================
--- /issm/trunk/test/NightlyRun/test246.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test248.m
===================================================================
--- /issm/trunk/test/NightlyRun/test248.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test250.m
===================================================================
--- /issm/trunk/test/NightlyRun/test250.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test252.m
===================================================================
--- /issm/trunk/test/NightlyRun/test252.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test254.m
===================================================================
--- /issm/trunk/test/NightlyRun/test254.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test256.m
===================================================================
--- /issm/trunk/test/NightlyRun/test256.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test258.m
===================================================================
--- /issm/trunk/test/NightlyRun/test258.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test260.m
===================================================================
--- /issm/trunk/test/NightlyRun/test260.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test262.m
===================================================================
--- /issm/trunk/test/NightlyRun/test262.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test264.m
===================================================================
--- /issm/trunk/test/NightlyRun/test264.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test266.m
===================================================================
--- /issm/trunk/test/NightlyRun/test266.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test268.m
===================================================================
--- /issm/trunk/test/NightlyRun/test268.m	(revision 13394)
+++ 	(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,0.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]);
-
-%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;
-
-%%  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');
-
-%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;
-
-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/trunk/test/NightlyRun/test270.m
===================================================================
--- /issm/trunk/test/NightlyRun/test270.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test270.m	(revision 13395)
@@ -1,72 +1,20 @@
-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.materials=matdamageice();
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.materials.rheology_Z=0.5*ones(md.mesh.numberofvertices,1);
 md=setflowequation(md,'macayeal','all');
 md.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');
+md=solve(md,DiagnosticSolutionEnum);
 
 %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_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/trunk/test/NightlyRun/test272.m
===================================================================
--- /issm/trunk/test/NightlyRun/test272.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test272.m	(revision 13395)
@@ -0,0 +1,38 @@
+md=triangle(model,'../Exp/Square.exp',150000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md.materials=matdamageice();
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.materials.rheology_Z=0.5*ones(md.mesh.numberofvertices,1);
+md=setflowequation(md,'macayeal','all');
+
+%control parameters
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'MaterialsRheologyZbar'};
+md.inversion.min_parameters=10^-13*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=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=0.9*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' 'MaterialsRheologyZbar' '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.MaterialsRheologyZbar),...
+   (md.results.DiagnosticSolution.Pressure),...
+   (md.results.DiagnosticSolution.Vel),...
+   (md.results.DiagnosticSolution.Vx),...
+   (md.results.DiagnosticSolution.Vy)
+};
Index: /issm/trunk/test/NightlyRun/test274.m
===================================================================
--- /issm/trunk/test/NightlyRun/test274.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test274.m	(revision 13395)
@@ -0,0 +1,22 @@
+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.materials=matdamageice();
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+md.materials.rheology_Z=0.5*ones(md.mesh.numberofvertices,1);
+md=setflowequation(md,'macayeal','all');
+
+md.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-11,1e-11,1e-11,1e-11};
+field_values={...
+	   (md.results.DiagnosticSolution.Vx),...
+	   (md.results.DiagnosticSolution.Vy),...
+	   (md.results.DiagnosticSolution.Vel),...
+	   (md.results.DiagnosticSolution.Pressure),...
+	   };
Index: /issm/trunk/test/NightlyRun/test3001.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3001.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test3001.m	(revision 13395)
@@ -0,0 +1,23 @@
+md=triangle(model,'../Exp/Square.exp',50000);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelfConstrained.par');
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.diagnostic.requested_outputs=StressTensorEnum;
+md.autodiff.isautodiff=true;
+md=solve(md,DiagnosticSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vel','Pressure',...
+	'StressTensorxx','StressTensoryy','StressTensorxy'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,...
+	1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.DiagnosticSolution.StressTensorxx),...
+	(md.results.DiagnosticSolution.StressTensoryy),...
+	(md.results.DiagnosticSolution.StressTensorxy),...
+	};
Index: /issm/trunk/test/NightlyRun/test3002.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3002.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test3002.m	(revision 13395)
@@ -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,2);
+md=setflowequation(md,'macayeal','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+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/trunk/test/NightlyRun/test3003.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3003.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test3003.m	(revision 13395)
@@ -0,0 +1,28 @@
+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.autodiff.isautodiff=true;
+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/trunk/test/NightlyRun/test3004.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3004.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test3004.m	(revision 13395)
@@ -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,2);
+md=setflowequation(md,'stokes','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+md=solve(md,DiagnosticSolutionEnum);
+
+%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_values={...
+	(md.results.DiagnosticSolution.Vx),...
+	(md.results.DiagnosticSolution.Vy),...
+	(md.results.DiagnosticSolution.Vz),...
+	(md.results.DiagnosticSolution.Vel),...
+	(md.results.DiagnosticSolution.Pressure),...
+	};
Index: /issm/trunk/test/NightlyRun/test3005.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3005.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test3005.m	(revision 13395)
@@ -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.cluster=generic('name',oshostname(),'np',3);
+md.autodiff.isautodiff=true;
+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/trunk/test/NightlyRun/test3006.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3006.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test3006.m	(revision 13395)
@@ -0,0 +1,17 @@
+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.autodiff.isautodiff=true;
+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/trunk/test/NightlyRun/test3007.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3007.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test3007.m	(revision 13395)
@@ -0,0 +1,15 @@
+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.autodiff.isautodiff=true;
+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/trunk/test/NightlyRun/test3008.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3008.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test3008.m	(revision 13395)
@@ -0,0 +1,17 @@
+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.autodiff.isautodiff=true;
+md=solve(md,ThermalSolutionEnum);
+
+%Fields and tolerances to track changes
+field_names     ={'Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-13,1e-13};
+field_values={...
+	(md.results.ThermalSolution.Temperature),...
+	(md.results.ThermalSolution.BasalforcingsMeltingRate),...
+	};
Index: /issm/trunk/test/NightlyRun/test3009.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3009.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test3009.m	(revision 13395)
@@ -0,0 +1,20 @@
+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.autodiff.isautodiff=true;
+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/trunk/test/NightlyRun/test301.m
===================================================================
--- /issm/trunk/test/NightlyRun/test301.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test301.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test3010.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3010.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test3010.m	(revision 13395)
@@ -0,0 +1,41 @@
+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.transient.requested_outputs=IceVolumeEnum();
+
+md.autodiff.isautodiff=true;
+md=solve(md,TransientSolutionEnum);
+
+%Fields and tolerances to track changes
+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.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/trunk/test/NightlyRun/test302.m
===================================================================
--- /issm/trunk/test/NightlyRun/test302.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test302.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test303.m
===================================================================
--- /issm/trunk/test/NightlyRun/test303.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test303.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test304.m
===================================================================
--- /issm/trunk/test/NightlyRun/test304.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test304.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test305.m
===================================================================
--- /issm/trunk/test/NightlyRun/test305.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test305.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test306.m
===================================================================
--- /issm/trunk/test/NightlyRun/test306.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test306.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test307.m
===================================================================
--- /issm/trunk/test/NightlyRun/test307.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test307.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test308.m
===================================================================
--- /issm/trunk/test/NightlyRun/test308.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test308.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test309.m
===================================================================
--- /issm/trunk/test/NightlyRun/test309.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test309.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test310.m
===================================================================
--- /issm/trunk/test/NightlyRun/test310.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test310.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test311.m
===================================================================
--- /issm/trunk/test/NightlyRun/test311.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test311.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test312.m
===================================================================
--- /issm/trunk/test/NightlyRun/test312.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test312.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test313.m
===================================================================
--- /issm/trunk/test/NightlyRun/test313.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test313.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test314.m
===================================================================
--- /issm/trunk/test/NightlyRun/test314.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test314.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test315.m
===================================================================
--- /issm/trunk/test/NightlyRun/test315.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test315.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test316.m
===================================================================
--- /issm/trunk/test/NightlyRun/test316.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test316.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test317.m
===================================================================
--- /issm/trunk/test/NightlyRun/test317.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test317.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test318.m
===================================================================
--- /issm/trunk/test/NightlyRun/test318.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test318.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test319.m
===================================================================
--- /issm/trunk/test/NightlyRun/test319.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test319.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test320.m
===================================================================
--- /issm/trunk/test/NightlyRun/test320.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test320.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test321.m
===================================================================
--- /issm/trunk/test/NightlyRun/test321.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test321.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test322.m
===================================================================
--- /issm/trunk/test/NightlyRun/test322.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test322.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test323.m
===================================================================
--- /issm/trunk/test/NightlyRun/test323.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test323.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test324.m
===================================================================
--- /issm/trunk/test/NightlyRun/test324.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test324.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test325.m
===================================================================
--- /issm/trunk/test/NightlyRun/test325.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test325.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test326.m
===================================================================
--- /issm/trunk/test/NightlyRun/test326.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test326.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test327.m
===================================================================
--- /issm/trunk/test/NightlyRun/test327.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test327.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test328.m
===================================================================
--- /issm/trunk/test/NightlyRun/test328.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test328.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test329.m
===================================================================
--- /issm/trunk/test/NightlyRun/test329.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test329.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test330.m
===================================================================
--- /issm/trunk/test/NightlyRun/test330.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test332.m
===================================================================
--- /issm/trunk/test/NightlyRun/test332.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test334.m
===================================================================
--- /issm/trunk/test/NightlyRun/test334.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test336.m
===================================================================
--- /issm/trunk/test/NightlyRun/test336.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test338.m
===================================================================
--- /issm/trunk/test/NightlyRun/test338.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test340.m
===================================================================
--- /issm/trunk/test/NightlyRun/test340.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test342.m
===================================================================
--- /issm/trunk/test/NightlyRun/test342.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test344.m
===================================================================
--- /issm/trunk/test/NightlyRun/test344.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test346.m
===================================================================
--- /issm/trunk/test/NightlyRun/test346.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test348.m
===================================================================
--- /issm/trunk/test/NightlyRun/test348.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test350.m
===================================================================
--- /issm/trunk/test/NightlyRun/test350.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test352.m
===================================================================
--- /issm/trunk/test/NightlyRun/test352.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test354.m
===================================================================
--- /issm/trunk/test/NightlyRun/test354.m	(revision 13394)
+++ 	(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: sm/trunk/test/NightlyRun/test356.m
===================================================================
--- /issm/trunk/test/NightlyRun/test356.m	(revision 13394)
+++ 	(revision )
@@ -1,41 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',150000);
-md=setmask(md,'','');
-md=parameterize(md,'../Par/SquareSheetConstrained.par');
-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.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx1','Vy1','Vel1','Bed1','Surface1','Thickness1','SMB1','Vx2','Vy2','Vel2','Bed2','Surface2','Thickness2','SMB2','Vx3','Vy3','Vel3','Bed3','Surface3','Thickness3','SMB3'};
-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).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).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).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
-	};
Index: sm/trunk/test/NightlyRun/test358.m
===================================================================
--- /issm/trunk/test/NightlyRun/test358.m	(revision 13394)
+++ 	(revision )
@@ -1,51 +1,0 @@
-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.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','Vx2','Vy2','Vz2','Vel2','Bed2','Surface2','Thickness2','Temperature2','SMB2','Vx3','Vy3','Vz3','Vel3','Bed3','Surface3','Thickness3','Temperature3','SMB3'};
-field_tolerances={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-09,5e-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).Bed),...
-	(md.results.TransientSolution(1).Surface),...
-	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).Temperature),...
-	(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).Bed),...
-	(md.results.TransientSolution(2).Surface),...
-	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).Temperature),...
-	(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).Bed),...
-	(md.results.TransientSolution(3).Surface),...
-	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).Temperature),...
-	(md.results.TransientSolution(3).SurfaceforcingsMassBalance),...
-	};
Index: /issm/trunk/test/NightlyRun/test401.m
===================================================================
--- /issm/trunk/test/NightlyRun/test401.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test401.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test402.m
===================================================================
--- /issm/trunk/test/NightlyRun/test402.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test402.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test403.m
===================================================================
--- /issm/trunk/test/NightlyRun/test403.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test403.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test404.m
===================================================================
--- /issm/trunk/test/NightlyRun/test404.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test404.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test405.m
===================================================================
--- /issm/trunk/test/NightlyRun/test405.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test405.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test406.m
===================================================================
--- /issm/trunk/test/NightlyRun/test406.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test406.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test407.m
===================================================================
--- /issm/trunk/test/NightlyRun/test407.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test407.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test408.m
===================================================================
--- /issm/trunk/test/NightlyRun/test408.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test408.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test409.m
===================================================================
--- /issm/trunk/test/NightlyRun/test409.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test409.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test410.m
===================================================================
--- /issm/trunk/test/NightlyRun/test410.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test410.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test411.m
===================================================================
--- /issm/trunk/test/NightlyRun/test411.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test411.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test412.m
===================================================================
--- /issm/trunk/test/NightlyRun/test412.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test412.m	(revision 13395)
@@ -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.qmu.results=md.results.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/trunk/test/NightlyRun/test413.m
===================================================================
--- /issm/trunk/test/NightlyRun/test413.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test413.m	(revision 13395)
@@ -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.qmu.results=md.results.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/trunk/test/NightlyRun/test414.m
===================================================================
--- /issm/trunk/test/NightlyRun/test414.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test414.m	(revision 13395)
@@ -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.qmu.results=md.results.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/trunk/test/NightlyRun/test415.m
===================================================================
--- /issm/trunk/test/NightlyRun/test415.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test415.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test416.m
===================================================================
--- /issm/trunk/test/NightlyRun/test416.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test416.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test417.m
===================================================================
--- /issm/trunk/test/NightlyRun/test417.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test417.m	(revision 13395)
@@ -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.qmu.results=md.results.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/trunk/test/NightlyRun/test418.m
===================================================================
--- /issm/trunk/test/NightlyRun/test418.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test418.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test419.m
===================================================================
--- /issm/trunk/test/NightlyRun/test419.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test419.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test420.m
===================================================================
--- /issm/trunk/test/NightlyRun/test420.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test420.m	(revision 13395)
@@ -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.qmu.results=md.results.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/trunk/test/NightlyRun/test421.m
===================================================================
--- /issm/trunk/test/NightlyRun/test421.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test421.m	(revision 13395)
@@ -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,2e-09,2e-05,1e-09,2e-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/trunk/test/NightlyRun/test422.m
===================================================================
--- /issm/trunk/test/NightlyRun/test422.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test422.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test423.m
===================================================================
--- /issm/trunk/test/NightlyRun/test423.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test423.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test424.m
===================================================================
--- /issm/trunk/test/NightlyRun/test424.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test424.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test425.m
===================================================================
--- /issm/trunk/test/NightlyRun/test425.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test425.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test426.m
===================================================================
--- /issm/trunk/test/NightlyRun/test426.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test426.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test427.m
===================================================================
--- /issm/trunk/test/NightlyRun/test427.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test427.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test428.m
===================================================================
--- /issm/trunk/test/NightlyRun/test428.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test428.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test429.m
===================================================================
--- /issm/trunk/test/NightlyRun/test429.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test429.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test430.m
===================================================================
--- /issm/trunk/test/NightlyRun/test430.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test430.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test431.m
===================================================================
--- /issm/trunk/test/NightlyRun/test431.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test431.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test432.m
===================================================================
--- /issm/trunk/test/NightlyRun/test432.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test432.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test434.m
===================================================================
--- /issm/trunk/test/NightlyRun/test434.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test436.m
===================================================================
--- /issm/trunk/test/NightlyRun/test436.m	(revision 13394)
+++ 	(revision )
@@ -1,21 +1,0 @@
-%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=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
-
-%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={...
-         vector_on_nodes,...
-	};
Index: sm/trunk/test/NightlyRun/test438.m
===================================================================
--- /issm/trunk/test/NightlyRun/test438.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test440.m
===================================================================
--- /issm/trunk/test/NightlyRun/test440.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test442.m
===================================================================
--- /issm/trunk/test/NightlyRun/test442.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test444.m
===================================================================
--- /issm/trunk/test/NightlyRun/test444.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test446.m
===================================================================
--- /issm/trunk/test/NightlyRun/test446.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test448.m
===================================================================
--- /issm/trunk/test/NightlyRun/test448.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test450.m
===================================================================
--- /issm/trunk/test/NightlyRun/test450.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test452.m
===================================================================
--- /issm/trunk/test/NightlyRun/test452.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test454.m
===================================================================
--- /issm/trunk/test/NightlyRun/test454.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test456.m
===================================================================
--- /issm/trunk/test/NightlyRun/test456.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test458.m
===================================================================
--- /issm/trunk/test/NightlyRun/test458.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test460.m
===================================================================
--- /issm/trunk/test/NightlyRun/test460.m	(revision 13394)
+++ 	(revision )
@@ -1,20 +1,0 @@
-md=triangle(model,'../Exp/Square.exp',180000);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,3,1);
-md=setflowequation(md,'stokes','all');
-md.diagnostic.isnewton=1;
-md.diagnostic.restol=0.0001;
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-07,1e-07,1e-06,1e-07,1e-07};
-field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	};
Index: sm/trunk/test/NightlyRun/test462.m
===================================================================
--- /issm/trunk/test/NightlyRun/test462.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test464.m
===================================================================
--- /issm/trunk/test/NightlyRun/test464.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test501.m
===================================================================
--- /issm/trunk/test/NightlyRun/test501.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test501.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test502.m
===================================================================
--- /issm/trunk/test/NightlyRun/test502.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test502.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test503.m
===================================================================
--- /issm/trunk/test/NightlyRun/test503.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test503.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test504.m
===================================================================
--- /issm/trunk/test/NightlyRun/test504.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test504.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test505.m
===================================================================
--- /issm/trunk/test/NightlyRun/test505.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test505.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test506.m
===================================================================
--- /issm/trunk/test/NightlyRun/test506.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test506.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test507.m
===================================================================
--- /issm/trunk/test/NightlyRun/test507.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test507.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test508.m
===================================================================
--- /issm/trunk/test/NightlyRun/test508.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test508.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test509.m
===================================================================
--- /issm/trunk/test/NightlyRun/test509.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test509.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test510.m
===================================================================
--- /issm/trunk/test/NightlyRun/test510.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test510.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test511.m
===================================================================
--- /issm/trunk/test/NightlyRun/test511.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test511.m	(revision 13395)
@@ -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=extract(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/trunk/test/NightlyRun/test512.m
===================================================================
--- /issm/trunk/test/NightlyRun/test512.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test512.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test513.m
===================================================================
--- /issm/trunk/test/NightlyRun/test513.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test513.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test514.m
===================================================================
--- /issm/trunk/test/NightlyRun/test514.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test514.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test515.m
===================================================================
--- /issm/trunk/test/NightlyRun/test515.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test515.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test516.m
===================================================================
--- /issm/trunk/test/NightlyRun/test516.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test516.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test518.m
===================================================================
--- /issm/trunk/test/NightlyRun/test518.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test520.m
===================================================================
--- /issm/trunk/test/NightlyRun/test520.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test522.m
===================================================================
--- /issm/trunk/test/NightlyRun/test522.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test524.m
===================================================================
--- /issm/trunk/test/NightlyRun/test524.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test526.m
===================================================================
--- /issm/trunk/test/NightlyRun/test526.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test527.m
===================================================================
--- /issm/trunk/test/NightlyRun/test527.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test530.m
===================================================================
--- /issm/trunk/test/NightlyRun/test530.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test532.m
===================================================================
--- /issm/trunk/test/NightlyRun/test532.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test601.m
===================================================================
--- /issm/trunk/test/NightlyRun/test601.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test601.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test602.m
===================================================================
--- /issm/trunk/test/NightlyRun/test602.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test602.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test603.m
===================================================================
--- /issm/trunk/test/NightlyRun/test603.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test603.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test604.m
===================================================================
--- /issm/trunk/test/NightlyRun/test604.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test604.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test605.m
===================================================================
--- /issm/trunk/test/NightlyRun/test605.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test605.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test606.m
===================================================================
--- /issm/trunk/test/NightlyRun/test606.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test606.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test607.m
===================================================================
--- /issm/trunk/test/NightlyRun/test607.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test607.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test608.m
===================================================================
--- /issm/trunk/test/NightlyRun/test608.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test608.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test609.m
===================================================================
--- /issm/trunk/test/NightlyRun/test609.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test609.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test610.m
===================================================================
--- /issm/trunk/test/NightlyRun/test610.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test610.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test611.m
===================================================================
--- /issm/trunk/test/NightlyRun/test611.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test611.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test612.m
===================================================================
--- /issm/trunk/test/NightlyRun/test612.m	(revision 13394)
+++ /issm/trunk/test/NightlyRun/test612.m	(revision 13395)
@@ -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/trunk/test/NightlyRun/test613.m
===================================================================
--- /issm/trunk/test/NightlyRun/test613.m	(revision 13395)
+++ /issm/trunk/test/NightlyRun/test613.m	(revision 13395)
@@ -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=extract(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/trunk/test/NightlyRun/test614.m
===================================================================
--- /issm/trunk/test/NightlyRun/test614.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test616.m
===================================================================
--- /issm/trunk/test/NightlyRun/test616.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test618.m
===================================================================
--- /issm/trunk/test/NightlyRun/test618.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test620.m
===================================================================
--- /issm/trunk/test/NightlyRun/test620.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test622.m
===================================================================
--- /issm/trunk/test/NightlyRun/test622.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test624.m
===================================================================
--- /issm/trunk/test/NightlyRun/test624.m	(revision 13394)
+++ 	(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/trunk/test/NightlyRun/test626.m
===================================================================
--- /issm/trunk/test/NightlyRun/test626.m	(revision 13394)
+++ 	(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: sm/trunk/test/NightlyRun/test999.py
===================================================================
--- /issm/trunk/test/NightlyRun/test999.py	(revision 13394)
+++ 	(revision )
@@ -1,27 +1,0 @@
-#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/trunk/test/Par/79North.par
===================================================================
--- /issm/trunk/test/Par/79North.par	(revision 13394)
+++ /issm/trunk/test/Par/79North.par	(revision 13395)
@@ -2,5 +2,11 @@
 
 %Geometry and observation
-load('../Data/79North.data','-mat');
+x=transpose(ncread('../Data/79North.nc','x'));
+y=transpose(ncread('../Data/79North.nc','y'));
+vx=transpose(ncread('../Data/79North.nc','vx'));
+vy=transpose(ncread('../Data/79North.nc','vy'));
+index=transpose(ncread('../Data/79North.nc','index'));
+surface=transpose(ncread('../Data/79North.nc','surface'));
+thickness=transpose(ncread('../Data/79North.nc','thickness'));
 md.initialization.vx       =InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
 md.initialization.vy       =InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
Index: /issm/trunk/test/Par/ISMIPE.par
===================================================================
--- /issm/trunk/test/Par/ISMIPE.par	(revision 13394)
+++ /issm/trunk/test/Par/ISMIPE.par	(revision 13395)
@@ -2,6 +2,5 @@
 
 disp('      creating thickness');
-data=load('../Data/ISMIPE.data','-mat');
-data=data.data;
+data=transpose(ncread('../Data/ISMIPE.nc','data'));
 md.geometry.surface=zeros(md.mesh.numberofvertices,1);
 md.geometry.bed=zeros(md.mesh.numberofvertices,1);
Index: /issm/trunk/test/Par/Pig.par
===================================================================
--- /issm/trunk/test/Par/Pig.par	(revision 13394)
+++ /issm/trunk/test/Par/Pig.par	(revision 13395)
@@ -2,5 +2,11 @@
 
 %Geometry and observation
-load('../Data/Pig.data','-mat');
+x         = transpose(ncread('../Data/Pig.nc','x'));
+y         = transpose(ncread('../Data/Pig.nc','y'));
+vx_obs    = transpose(ncread('../Data/Pig.nc','vx_obs'));
+vy_obs    = transpose(ncread('../Data/Pig.nc','vy_obs'));
+index     = transpose(ncread('../Data/Pig.nc','index'));
+surface   = transpose(ncread('../Data/Pig.nc','surface'));
+thickness = transpose(ncread('../Data/Pig.nc','thickness'));
 md.inversion.vx_obs   =InterpFromMeshToMesh2d(index,x,y,vx_obs,md.mesh.x,md.mesh.y);
 md.inversion.vy_obs   =InterpFromMeshToMesh2d(index,x,y,vy_obs,md.mesh.x,md.mesh.y);
Index: /issm/trunk/test/Par/SquareSheetConstrained.par
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 13394)
+++ /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 13395)
@@ -11,5 +11,9 @@
 
 %Initial velocity 
-load('../Data/SquareSheetConstrained.data','-mat');
+x     = transpose(ncread('../Data/SquareSheetConstrained.nc','x'));
+y     = transpose(ncread('../Data/SquareSheetConstrained.nc','y'));
+vx    = transpose(ncread('../Data/SquareSheetConstrained.nc','vx'));
+vy    = transpose(ncread('../Data/SquareSheetConstrained.nc','vy'));
+index = transpose(ncread('../Data/SquareSheetConstrained.nc','index'));
 md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
 md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
Index: /issm/trunk/test/Par/SquareSheetShelf.par
===================================================================
--- /issm/trunk/test/Par/SquareSheetShelf.par	(revision 13394)
+++ /issm/trunk/test/Par/SquareSheetShelf.par	(revision 13395)
@@ -14,5 +14,9 @@
 
 %Initial velocity 
-load('../Data/SquareSheetShelf.data','-mat');
+x     = transpose(ncread('../Data/SquareSheetShelf.nc','x'));
+y     = transpose(ncread('../Data/SquareSheetShelf.nc','y'));
+vx    = transpose(ncread('../Data/SquareSheetShelf.nc','vx'));
+vy    = transpose(ncread('../Data/SquareSheetShelf.nc','vy'));
+index = transpose(ncread('../Data/SquareSheetShelf.nc','index'));
 md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
 md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
Index: /issm/trunk/test/Par/SquareShelf.par
===================================================================
--- /issm/trunk/test/Par/SquareShelf.par	(revision 13394)
+++ /issm/trunk/test/Par/SquareShelf.par	(revision 13395)
@@ -11,5 +11,9 @@
 
 %Initial velocity and pressure
-load('../Data/SquareShelf.data','-mat');
+x     = transpose(ncread('../Data/SquareShelf.nc','x'));
+y     = transpose(ncread('../Data/SquareShelf.nc','y'));
+vx    = transpose(ncread('../Data/SquareShelf.nc','vx'));
+vy    = transpose(ncread('../Data/SquareShelf.nc','vy'));
+index = transpose(ncread('../Data/SquareShelf.nc','index'));
 md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
 md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
Index: /issm/trunk/test/Par/SquareShelfConstrained.par
===================================================================
--- /issm/trunk/test/Par/SquareShelfConstrained.par	(revision 13394)
+++ /issm/trunk/test/Par/SquareShelfConstrained.par	(revision 13395)
@@ -11,5 +11,9 @@
 
 %Initial velocity 
-load('../Data/SquareShelfConstrained.data','-mat');
+x     = transpose(ncread('../Data/SquareShelfConstrained.nc','x'));
+y     = transpose(ncread('../Data/SquareShelfConstrained.nc','y'));
+vx    = transpose(ncread('../Data/SquareShelfConstrained.nc','vx'));
+vy    = transpose(ncread('../Data/SquareShelfConstrained.nc','vy'));
+index = transpose(ncread('../Data/SquareShelfConstrained.nc','index'));
 md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
 md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
@@ -50,5 +54,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/trunk/test/Par/SquareShelfConstrained.py
===================================================================
--- /issm/trunk/test/Par/SquareShelfConstrained.py	(revision 13394)
+++ /issm/trunk/test/Par/SquareShelfConstrained.py	(revision 13395)
@@ -1,7 +1,10 @@
+import os.path
+import inspect
+import netCDF4
 from numpy import *
 from verbose import *
-import scipy.io as matio
-import InterpFromMeshToMesh2d as im
-from   paterson import  *
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import *
+from SetIceShelfBC import *
 
 #Start defining model parameters here
@@ -13,15 +16,21 @@
 
 md.geometry.thickness = hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)
-md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+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 
-mat=matio.loadmat('../Data/SquareShelfConstrained.data')
+f = netCDF4.Dataset('../Data/SquareShelfConstrained.nc','r')
+#Reshape as Rank-1 arrays
+x=reshape(f.variables['x'][:],(-1))
+y=reshape(f.variables['y'][:],(-1))
+vx=f.variables['vx'][:]
+vy=f.variables['vy'][:]
 #deal with 'F' oriented matlab matrices!
-index=mat['index'].astype(float)
+index=f.variables['index'][:].astype(float)
 index=reshape(index.T,(len(index),3),order='F')
+f.close()
 
-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] = InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y)
+[md.initialization.vy] = InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y)
 md.initialization.vz = zeros(md.mesh.numberofvertices)
 md.initialization.pressure = zeros(md.mesh.numberofvertices)
@@ -53,7 +62,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 = os.path.basename(inspect.stack()[2][1]).split('.')[0]
 
